RUST actix-web connection password of Redis database
actix-web inside of example, to use his own actix-redis, but I tried it, not easy to use
Replaced by another connection pool, deadpool-redis
Use the library
Storehouse | version |
---|---|
deadpool-repeat | 0.5.2 |
repeat | 0.15.1 |
actix-web | 2 |
actix-rt | 1 |
dotenv | 0.15.0 |
Set Environment Variables
REDIS_URL=redis://:password@localhost
This link can be written with the same level of form directory .env
file, password replace your password, localhost replace their link address.
dotenv library to load environment variables
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
dotenv().ok(); //加载.env文件
}
If it does not use !!! dotenv manually set environment variables in the code
#[actix_rt::main]
async fn main() -> std::io::Result<()> {
std::env::set_var("REDIS_URL", "redis://:password@localhost");
}
Configure connection pooling, and loaded into actix-web
HttpServer::new(|| {
//初始化Redis线程池
let cfg = Config::from_env("REDIS").unwrap();
let pool = cfg.create_pool().unwrap();
App::new()
.data(pool)
.configure(handler::main_config)
})
.bind("127.0.0.1:8088")?
.run()
.await
After creating two methods, one to read a written, facilitate our operations redis database
Redis simplify operation code, library code if there is a change after the operation, we can only modify this code, on the whole will not be affected, and write code to reduce duplication of effort.
use actix_web::web;
use deadpool_redis::{cmd, Pool};
use serde::{Deserialize,Serialize};
pub async fn get_str(redis: &web::Data<Pool>, name: &str) -> Option<String> {
let mut r = redis.get().await.unwrap();
let v = cmd("GET").arg(&[name]).query_async::<String>(&mut r).await;
match v{
Ok(s)=>{ Some(s)}
Err(_e)=>{None}
}
}
pub async fn set_str(redis: &web::Data<Pool>, name: &str, value: &str) {
let mut r = redis.get().await.unwrap();
cmd("SET").arg(&[name, value]).execute_async(&mut r).await.unwrap();
}
#[derive(Deserialize,Serialize)]
pub struct Success{
code:i32,
msg:String,
}
//制作一个返回,code这个参数虽然推荐使用http code,但是有些前端还是更喜欢从返回值里面取
//,所以就只能照顾一下
pub fn msg_response(code:i32,msg:&str)->Success{
Success{
code:code,
msg:String::from(msg)
}
}
Inside the handler calls
async fn test_handler(
redis: web::Data<R_Pool>,
) -> Result<HttpResponse> {
set_str(&redis,"name","value").await;
match get_str(&redis,"name").await{
Ok(result:String)=>{
Ok(HttpResponse::Ok().json(msg_response(200,format!{"{}",result}).as_str()))
}
Erro(e:Erro)=>{
Ok(HttpResponse::Ok().json(msg_response(200,format!{"{}",e}).as_str()))
}
}
}
Specific configuration handler is no longer write here where detailed tutorial address: Actix-Web
Make the project more attractive
Normally I would util saved elsewhere, handler configuration is also a place away from the initial configuration app
目录树
├─.github
│ └─workflows
├─doc //存放文档
├─main.rs //入口文件
├─src
│ ├─handler
│ │ ├─mod.rs//统一配置handler的地方
│ │ ├─mobile.rs//分割handler
│ │ └─universal.rs
│ └─util
| ├─db_util.rs //数据库工具
| ├─redis_util.rs//redis工具
| └─http_util.rs//http工具