Rust语言Actix-web框架连接Redis数据库

时间:2022-01-16 05:30:33

Rust语言Actix-web框架连接Redis数据库

actix-web2.0终于发布了,不再是测试版本,基于actor系统再加上异步支持,使得actix-web成为了目前响应速度最快的服务器框架,本来计划使用deadpool-redis来写这篇博客,更新了一下actix-web的官方例子,发现actix团队新增加了一个actix-redis库,暂且尝鲜。

准备工作

框架 描述 版本号
actix-web rust 基于actor的异步网络库 2.0
actix-rt actix运行时 1.0
redis-async redis异步连接库,通过Tokio框架和Rustfuture语法编写 0.6.1
actix-redis redis连接管理工具 0.8.0
actix actix核心库 0.9.0

Cargo.toml

[package]
name = "cloud_test"
version = "0.1.0"
authors = ["yuxq"]
edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies]
actix = "0.9.0"
actix-web = "2.0"
actix-rt = "1.0"
actix-redis = "0.8.0"
redis-async = "0.6.1"

## 连接Redis

导入需要的包

#[macro_use]
extern crate redis_async;
//use serde::Deserialize;
use actix::prelude::*;
use actix_redis::{Command, RedisActor, Error};
use actix_web::{middleware, web, App, Error as AWError, HttpResponse, HttpServer, Responder};
use redis_async::resp::RespValue;

准备连接

        let redis_addr = RedisActor::start("localhost:6379");

绑定到actix-web中

    HttpServer::new(|| {
let redis_addr = RedisActor::start("localhost:6379");
App::new().data(redis_addr)
.route("/set", web::get().to(set))
.route("/get", web::get().to(get))
// .route("/again", web::get().to(index2))
})
.bind("127.0.0.1:8088")?
.run()
.await

准备两个测试接口,一个设置redis值,一个获取Redis值

async fn set(redis: web::Data<Addr<RedisActor>>) -> Result<HttpResponse, AWError> {
// let result:Result<RespValue,Error> = redis.send(Command(resp_array!["SET","myname","myvalue"])).await?;
let result=redis.send(Command(resp_array!["set","name","myvalue"])).await?; match result {
Ok(RespValue::SimpleString(s)) if s == "OK" => {
Ok(HttpResponse::Ok().body("Set values success!"))
}
_ => {
println!("---->{:?}", result);
Ok(HttpResponse::InternalServerError().finish())
}
}
} async fn get(redis:web::Data<Addr<RedisActor>>)-> Result<HttpResponse, AWError> {
let result=redis.send(Command(resp_array!["get","name"])).await?;
match result{
Ok(RespValue::BulkString(s)) =>{
Ok(HttpResponse::Ok().body(s))
}
_ => {
println!("---->{:?}", result);
Ok(HttpResponse::InternalServerError().finish())
}
} }

访问 localhost:8088/set

之后在访问 localhost:8088/get

由于rust是强类型,所以需要注意返回值类型,设置时返回的类型是SimpleString,获取时返回的是BulkString,关注一下失败的log,会显示返回的类型。