rust的axum使用bb8连接池访问redis

https://zhuanlan.zhihu.com/p/617450207

这是redis的语法

下面是axum的example,需要axum-0.8apa.1

Cargo.toml

c 复制代码
[package]
name = "hello-axum"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "0.8.0-alpha.1"
bb8 = "0.8.5"
bb8-redis = "0.17.0"
redis = "0.27.2"
tokio = { version = "1.0", features = ["full", "macros", "rt-multi-thread"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }

以下是main.src

c 复制代码
 

use axum::{extract::{FromRef, FromRequestParts, Path, State},
    http::{request::{self, Parts}, StatusCode},
    routing::get,
    Router,
};
use bb8::{Pool, PooledConnection};
use bb8_redis::RedisConnectionManager;
use redis::AsyncCommands;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};

use bb8_redis::bb8;

#[tokio::main]
async fn main() {
    tracing_subscriber::registry()
        .with(
            tracing_subscriber::EnvFilter::try_from_default_env()
                .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()),
        )
        .with(tracing_subscriber::fmt::layer())
        .init();

    tracing::debug!("connecting to redis");
    let manager = RedisConnectionManager::new("redis://192.168.1.231:6379/9").unwrap();
    let pool = bb8::Pool::builder().build(manager).await.unwrap();

    {
        // ping the database before starting
        let mut conn = pool.get().await.unwrap();
        conn.set::<&str, &str, ()>("foo", "barr").await.unwrap();
        let result: String = conn.get("foo").await.unwrap();
        assert_eq!(result, "barr");
    }
    tracing::debug!("successfully connected to redis and pinged it");

    // build our application with some routes
    let app = Router::new()
        .route(
            "/",
            get(using_connection_pool_extractor),
           // post.(using_connection_extractor),
        )
      .route("/sta/{day}/{sta}", get( bsta),
    )
     .route("/check/{sta}/{person}",get(check))
       .route("/check",get(using_connection_extractor)
        ).with_state(pool);

    // run it
    let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();
    tracing::debug!("listening on {}", listener.local_addr().unwrap());
    axum::serve(listener, app).await.unwrap();
}

type ConnectionPool = Pool<RedisConnectionManager>;

async fn using_connection_pool_extractor(
    State(pool): State<ConnectionPool>,
) -> Result<String, (StatusCode, String)> {
    let mut conn = pool.get().await.map_err(internal_error)?;
    let result: String = conn.get("foo").await.map_err(internal_error)?;
    Ok(format!("车站:{}",result))
}
// my first  python route 
async fn bsta(
    State(pool): State<ConnectionPool>,Path((day, sta)): Path<(String, String)>
) -> Result<String, (StatusCode, String)> {
    let mut conn = pool.get().await.map_err(internal_error)?;
     let result :Vec<String>= conn.smembers(&format!("check:{sta}")).await.map_err(internal_error)?;
  // let result:Vec<String>= conn.keys("*").await.map_err(internal_error)?;
    Ok(format!("车站:{}{:?}",sta,result))
}
async fn check(
    State(pool): State<ConnectionPool>,Path((sta, person)): Path<(String, String)>
) -> Result<String, (StatusCode, String)> {
    let mut conn = pool.get().await.map_err(internal_error)?;
    let result: String = conn.sadd(&format!("check:{sta}"),&[&person]).await.map_err(internal_error)?;
    Ok(format!("车站:{}re:{}",sta,result))
}
// we can also write a custom extractor that grabs a connection from the pool
// which setup is appropriate depends on your application
struct DatabaseConnection(PooledConnection<'static, RedisConnectionManager>);

impl<S> FromRequestParts<S> for DatabaseConnection
where
    ConnectionPool: FromRef<S>,
    S: Send + Sync,
{
    type Rejection = (StatusCode, String);

    async fn from_request_parts(  _parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
        let pool = ConnectionPool::from_ref(state);

        let conn = pool.get_owned().await.map_err(internal_error)?;

        Ok(Self(conn))
    }
}

async fn using_connection_extractor(
    DatabaseConnection(mut conn): DatabaseConnection,
) -> Result<String, (StatusCode, String)> {
    conn.set::<&str, &str, ()>("station", "wjc,zhw,sd").await.unwrap();
       
    let result: String = conn.get("station").await.map_err(internal_error)?;

    Ok(result)
} 

/// Utility function for mapping any error into a `500 Internal Server Error`     
/// response.
fn internal_error<E>(err: E) -> (StatusCode, String)  
where
    E: std::error::Error,
{
    (StatusCode::INTERNAL_SERVER_ERROR, err.to_string())
}

tom

相关推荐
张哈大24 分钟前
【 Redis | 实战篇 秒杀优化 】
java·数据库·redis·笔记·缓存
yezipi耶不耶5 小时前
用 Rust 带你了解 TCP 和 UDP
tcp/ip·rust·udp
勇敢牛牛_11 小时前
使用Rust开发的智能助手系统,支持多模型、知识库和MCP
ai·rust·rag·mcp
LDM>W<14 小时前
黑马点评-用户登录
java·redis
炫酷的伊莉娜17 小时前
【Redis】零碎知识点(易忘 / 易错)总结回顾
redis
Dontla17 小时前
BootCDN介绍(Bootstrap主导的前端开源项目免费CDN加速服务)
前端·开源·bootstrap
Source.Liu17 小时前
【typenum】 8 常量文件(consts.rs)
rust
一个天蝎座 白勺 程序猿19 小时前
Python爬虫(29)Python爬虫高阶:动态页面处理与云原生部署全链路实践(Selenium、Scrapy、K8s)
redis·爬虫·python·selenium·scrapy·云原生·k8s
追风赶月、20 小时前
【Redis】哨兵(Sentinel)机制
数据库·redis·sentinel
vvilkim20 小时前
Redis持久化机制详解:保障数据安全的关键策略
数据库·redis·缓存