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,會顯示返回的類型。