首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >结合使用redis-rs和actix-web

结合使用redis-rs和actix-web
EN

Stack Overflow用户
提问于 2020-07-19 02:32:46
回答 1查看 1.5K关注 0票数 1

我正在尝试将redis作为web::Data上下文添加到我的actix-web rust应用程序中:

代码语言:javascript
复制
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
}

我收到以下错误:the trait bound 'redis::Connection: std::clone::Clone' is not satisfied in '[closure@src/main.rs:48:21: 48:81 redis_con:redis::Connection]'

我已经尝试将它包装为Arc<redis::Connection>,这对于redis::Connection的子模块中没有实现Sync的某些类型也不起作用。

在这种情况下,有没有我看不到的生锈概念?这是我第一个真正的Rust项目之一,所以可能会有一些我非常粗略地忽略的东西。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-29 20:33:03

这个答案是Actix解决问题方法的最小示例。不过,可能有更短的方法来实现你想要的东西。

首先,您需要导入actix机箱:

代码语言:javascript
复制
[package]
name = "test-actix-redis"
version = "0.1.0"
authors = ["Njuguna Mureithi <email@gmail.com>"]
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"

然后定义你的参与者:

代码语言:javascript
复制
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
}

现在运行您的项目:

代码语言:javascript
复制
cargo run

转到http://localhost:8088/应该会给你一个字符串形式的redis信息。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62972342

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档