< 返回版块

xznsoft 发表于 2024-03-05 07:07

Tags:actix-web, middleware, session

Cargo.toml 依赖如下:

actix-web = "4.5.1"
actix-session = { version = "0.9.0", features = ["redis-actor-session"] }

main.rs 代码如下:

use actix_session::{storage::RedisActorSessionStore, Session, SessionExt, SessionMiddleware};
use actix_web::{cookie::Key, dev::Service, web, App, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let secret_key = Key::generate();
    HttpServer::new(move || {
        App::new()
            .wrap(
                SessionMiddleware::builder(
                    RedisActorSessionStore::new("127.0.0.1:6379"),
                    secret_key.clone(),
                )
                .build(),
            )
            .wrap_fn(|req, srv| {
                if let Ok(Some(user)) = req.get_session().get::<i32>("user") {
                    println!("middleware: {}", user);
                } else {
                    println!("middleware: {}", 0);
                }
                srv.call(req)
            })
            .route(
                "/set",
                web::to(|session: Session| {
                    let _ = session.insert("user", 1);
                    HttpResponse::Ok()
                }),
            )
            .route(
                "/get",
                web::to(|session: Session| {
                    if let Ok(Some(user)) = session.get::<i32>("user") {
                        println!("get: {}", user);
                    } else {
                        println!("get: {}", 0);
                    }
                    HttpResponse::Ok()
                }),
            )
    })
    .bind(("0.0.0.0", 8000))?
    .run()
    .await
}

先执行 http://127.0.0.1:8000/set 设置 session 值

再执行 http://127.0.0.1:8000/get 打印 session 值

路由 “/get” 中可以获取 session 值,但是 wrap_fn(middleware) 中无法获取 session 值,出题出在哪?请高手给指点下。

感谢 liusen-adalab 的帮忙,原来是因为两个中间件位置反了,已经把正确的代码也加上了,方便和我一样遇到这个问题的人

main.rs 正确代码如下:

use actix_session::{storage::RedisActorSessionStore, Session, SessionExt, SessionMiddleware};
use actix_web::{cookie::Key, dev::Service, web, App, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let secret_key = Key::generate();
    HttpServer::new(move || {
        App::new()
            .wrap_fn(|req, srv| {
                if let Ok(Some(user)) = req.get_session().get::<i32>("user") {
                    println!("middleware: {}", user);
                } else {
                    println!("middleware: {}", 0);
                }
                srv.call(req)
            })
            .wrap(
                SessionMiddleware::builder(
                    RedisActorSessionStore::new("127.0.0.1:6379"),
                    secret_key.clone(),
                )
                .build(),
            )
            .route(
                "/set",
                web::to(|session: Session| {
                    let _ = session.insert("user", 1);
                    HttpResponse::Ok()
                }),
            )
            .route(
                "/get",
                web::to(|session: Session| {
                    if let Ok(Some(user)) = session.get::<i32>("user") {
                        println!("get: {}", user);
                    } else {
                        println!("get: {}", 0);
                    }
                    HttpResponse::Ok()
                }),
            )
    })
    .bind(("0.0.0.0", 8000))?
    .run()
    .await
}

评论区

写评论
作者 xznsoft 2024-03-07 07:42

是的,比写 Java 麻烦一点、性能高一点

--
👇
cybertheye: 这是写业务用的库吗?比起Java去写请求对比怎么样?

cybertheye 2024-03-06 21:59

这是写业务用的库吗?比起Java去写请求对比怎么样?

作者 xznsoft 2024-03-06 16:58

把位置调了就可以了,非常感谢

--
👇
liusen-adalab: 你的两个中间件位置反了

liusen-adalab 2024-03-05 10:27

https://actix.rs/docs/middleware#:~:text=Middleware%20is%20registered%20for%20each%20App%2C%20scope%2C%20or%20Resource%20and%20executed%20in%20opposite%20order%20as%20registration.

liusen-adalab 2024-03-05 10:23

你的两个中间件位置反了

1 共 5 条评论, 1 页