亚洲综合图片区自拍_思思91精品国产综合在线观看_一区二区三区欧美_欧美黑人又粗又大_亚洲人成精品久久久久桥本

全球快播:文盤Rust -- r2d2 實(shí)現(xiàn)redis連接池

2022-12-07 15:12:16 來源:51CTO博客

作者:賈世聞

我們?cè)陂_發(fā)應(yīng)用后端系統(tǒng)的時(shí)候經(jīng)常要和各種數(shù)據(jù)庫(kù)、緩存等資源打交道。這一期,我們聊聊如何訪問redis 并將資源池化。

在一個(gè)應(yīng)用后端程序訪問redis主要要做的工作有兩個(gè),單例和池化。


(相關(guān)資料圖)

在后端應(yīng)用集成redis,我們主要用到以下幾個(gè)crate:??once_cell???、??redis-rs???、??r2d2???.once_cell 實(shí)現(xiàn)單例;redis-rs 是 redis的 rust 驅(qū)動(dòng);r2d2 是一個(gè)池化連接的工具包。本期代碼均出現(xiàn)在??fullstack-rs???項(xiàng)目中。??fullstack-rs???是我新開的一個(gè)實(shí)驗(yàn)性項(xiàng)目,目標(biāo)是做一個(gè)類似??gin-vue-admin??的集成開發(fā)框架。

redis資源的定義主要是在??https://github.com/jiashiwen/fullstack-rs/blob/main/backend/src/resources/redis_resource.rs??中實(shí)現(xiàn)的。

一、redis-rs 封裝

在實(shí)際開發(fā)中,我們面對(duì)的redis資源可能是單實(shí)例也有可能是集群,在這里我們對(duì)redis-rs進(jìn)行了簡(jiǎn)單封裝,便于適應(yīng)這兩種情況。

```rust#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, Clone)]#[serde(rename_all = "lowercase")]pub struct RedisInstance {    #[serde(default = "RedisInstance::urls_default")]    pub urls: Vec,    #[serde(default = "RedisInstance::password_default")]    pub password: String,    #[serde(default = "RedisInstance::instance_type_default")]    pub instance_type: InstanceType,}```

RedisInstance,定義redis資源的描述,與配置文件相對(duì)應(yīng)。詳細(xì)的配置描述可以參考??https://github.com/jiashiwen/fullstack-rs/blob/main/backend/src/configure/config_global.rs??文件中 RedisConfig 和 RedisPool 兩個(gè) struct 描述。

```rust#[derive(Clone)]pub enum RedisClient {    Single(redis::Client),    Cluster(redis::cluster::ClusterClient),}impl RedisClient {    pub fn get_redis_connection(&self) -> RedisResult {        return match self {            RedisClient::Single(s) => {                let conn = s.get_connection()?;                Ok(RedisConnection::Single(Box::new(conn)))            }            RedisClient::Cluster(c) => {                let conn = c.get_connection()?;                Ok(RedisConnection::Cluster(Box::new(conn)))            }        };    }}pub enum RedisConnection {    Single(Box),    Cluster(Box),}impl RedisConnection {    pub fn is_open(&self) -> bool {        return match self {            RedisConnection::Single(sc) => sc.is_open(),            RedisConnection::Cluster(cc) => cc.is_open(),        };    }    pub fn query(&mut self, cmd: &redis::Cmd) -> RedisResult {        return match self {            RedisConnection::Single(sc) => match sc.as_mut().req_command(cmd) {                Ok(val) => from_redis_value(&val),                Err(e) => Err(e),            },            RedisConnection::Cluster(cc) => match cc.req_command(cmd) {                Ok(val) => from_redis_value(&val),                Err(e) => Err(e),            },        };    }}```

RedisClient 和 RedisConnection 對(duì)redis 的鏈接進(jìn)行了封裝,用來實(shí)現(xiàn)統(tǒng)一的調(diào)用接口。

二、基于 r2d2 實(shí)現(xiàn) redis 連接池

以上,基本完成的reids資源的準(zhǔn)備工作,下面來實(shí)現(xiàn)一個(gè)redis鏈接池。

```rust#[derive(Clone)]pub struct RedisConnectionManager {    pub redis_client: RedisClient,}impl r2d2::ManageConnection for RedisConnectionManager {    type Connection = RedisConnection;    type Error = RedisError;    fn connect(&self) -> Result {        let conn = self.redis_client.get_redis_connection()?;        Ok(conn)    }    fn is_valid(&self, conn: &mut RedisConnection) -> Result<(), Self::Error> {        match conn {            RedisConnection::Single(sc) => {                redis::cmd("PING").query(sc)?;            }            RedisConnection::Cluster(cc) => {                redis::cmd("PING").query(cc)?;            }        }        Ok(())    }    fn has_broken(&self, conn: &mut RedisConnection) -> bool {        !conn.is_open()    }}```

利用 r2d2 來實(shí)現(xiàn)連接池需要實(shí)現(xiàn) r2d2::ManageConnection trait。connect 函數(shù)獲取連接;is_valid 函數(shù)校驗(yàn)連通性;has_broken 判斷連接是否崩潰不可用。

```Rustpub fn gen_redis_conn_pool() -> Result> {    let config = get_config()?;    let redis_client = config.redis.instance.to_redis_client()?;    let manager = RedisConnectionManager { redis_client };    let pool = r2d2::Pool::builder()        .max_size(config.redis.pool.max_size as u32)        .min_idle(Some(config.redis.pool.mini_idle as u32))        .connection_timeout(Duration::from_secs(            config.redis.pool.connection_timeout as u64,        ))        .build(manager)?;    Ok(pool)}```

gen_redis_conn_pool 函數(shù)用來生成一個(gè) redis 的連接池,根據(jù)配置文件來指定連接池的最大連接數(shù),最小閑置連接以及連接超時(shí)時(shí)長(zhǎng)。

三、連接池單例實(shí)現(xiàn)****

在后端開發(fā)中,對(duì)于單一資源一般采取單例模式避免重復(fù)產(chǎn)生實(shí)例的開銷。下面來聊一聊如果構(gòu)建一個(gè)全局的 redis 資源。

這一部分代碼在??https://github.com/jiashiwen/fullstack-rs/blob/main/backend/src/resources/init_resources.rs??文件中。

```rustpub static GLOBAL_REDIS_POOL: OnceCell> = OnceCell::new();```

利用 OnceCell 構(gòu)建全局靜態(tài)變量。

```rustfn init_global_redis() {    GLOBAL_REDIS_POOL.get_or_init(|| {        let pool = match gen_redis_conn_pool() {            Ok(it) => it,            Err(err) => panic!("{}", err.to_string()),        };        pool    });}```

init_global_redis 函數(shù),用來初始化 GLOBAL_REDIS_POOL 全局靜態(tài)變量。在一般的后端程序中,資源是強(qiáng)依賴,所以,初始化簡(jiǎn)單粗暴,要么成功要么 panic。

四、資源調(diào)用

準(zhǔn)備好 redis 資源后,我們聊聊如何調(diào)用。

調(diào)用例子在這里??https://github.com/jiashiwen/fullstack-rs/blob/main/backend/src/httpserver/service/service_redis.rs??

```rustpub fn put(kv: KV) -> Result<()> {    let conn = GLOBAL_REDIS_POOL.get();    return match conn {        Some(c) => {            c.get()?                .query(redis::cmd("set").arg(kv.Key).arg(kv.Value))?;            Ok(())        }        None => Err(anyhow!("redis pool not init")),    };}```

??https://github.com/jiashiwen/fullstack-rs/tree/main/backend??這個(gè)工程里有從http入口開始到寫入redis的完整流程,http server 不在本文討論之列,就不贅述了,有興趣的同學(xué)可以去github看看。

咱們下期見。

標(biāo)簽: 配置文件 靜態(tài)變量 單例模式

上一篇:每日觀察!不可錯(cuò)過,5張圖弄懂容器網(wǎng)絡(luò)原理
下一篇:各開發(fā)語言DNS緩存配置建議