1
votes

I am trying to add redis as a web::Data context to my actix-web rust application:

extern crate redis;

// std imports
use std::net::SocketAddr;
// external imports
use actix_web::{App, HttpServer};
use redis::Client

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    // connect to redis
    let redis_con = Client::open("redis://127.0.0.1:6379")
        .unwrap()
        .get_connection()
        .unwrap();

    HttpServer::new(move || App::new().data(redis_con).service(api::get_healthz))
        .bind(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 8080)?
        .run()
        .await
}

I'm getting the following error: the trait bound 'redis::Connection: std::clone::Clone' is not satisfied in '[closure@src/main.rs:48:21: 48:81 redis_con:redis::Connection]'

I already tried to wrap it as an Arc<redis::Connection>, which also did not work for some type deep inside the sub-modules of redis::Connection which did not implement Sync.

Is there a concept of Rust I am not seeing in this context? This is one of my first real Rust projects, so there could be something I very roughly overlooked.

1

1 Answers

3
votes

This answer is a bear minimum example of the Actix way to solve your problem. There may be shorter ways to achieve what you want though.

First you need to import the actix crate:

[package]
name = "test-actix-redis"
version = "0.1.0"
authors = ["Njuguna Mureithi <[email protected]>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
actix-web = "2.0"
actix-rt = "1.0"
redis = "0.15"
actix = "0.10.0-alpha.3"

Then define your actor:

use actix_web::{web, App, HttpResponse, HttpServer, Responder};
use redis::{Client, aio::MultiplexedConnection};
use actix::prelude::*;

struct RedisActor {
    conn: MultiplexedConnection,
}

impl RedisActor {
    pub async fn new(redis_url: &'static str) -> Self {
        let client = Client::open(redis_url).unwrap();// not recommended
        let (conn, call) = client.get_multiplexed_async_connection().await.unwrap();
        actix_rt::spawn(call);
        RedisActor { conn }
    }
}

#[derive(Message, Debug)]
#[rtype(result = "Result<Option<String>, redis::RedisError>")]
struct InfoCommand;



impl Handler<InfoCommand> for RedisActor {
    type Result = ResponseFuture<Result<Option<String>, redis::RedisError>>;

    fn handle(&mut self, _msg: InfoCommand, _: &mut Self::Context) -> Self::Result {
        let mut con = self.conn.clone();
        let cmd = redis::cmd("INFO");
        let fut = async move {
            cmd
                .query_async(&mut con)
                .await
        };
        Box::pin(fut)
    }
}


impl Actor for RedisActor {
    type Context = Context<Self>;
}

async fn info(redis: web::Data<Addr<RedisActor>>) -> impl Responder {
    let res = redis.send(InfoCommand).await.unwrap().unwrap().unwrap();
    HttpResponse::Ok().body(res)
}




#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    let actor = RedisActor::new("redis://127.0.0.1:6379").await;
    let addr = actor.start();
    HttpServer::new(move || {
        App::new()
            .data(addr.clone())
            .route("/", web::get().to(info))
    })
    .bind("127.0.0.1:8088")?
    .run()
    .await
}

Now run your project:

cargo run

Going to http://localhost:8088/ should give you your redis info as a string.