|
1 | | -pub use redis; |
| 1 | +use std::sync::LazyLock; |
2 | 2 |
|
3 | | -pub fn open(url: &str) -> Result<redis::Client, Box<dyn std::error::Error>> { |
4 | | - let client = redis::Client::open(url)?; |
5 | | - Ok(client) |
| 3 | +pub use deadpool_redis::redis; |
| 4 | +use deadpool_redis::{self as deadpool, redis::AsyncCommands, Connection}; |
| 5 | + |
| 6 | +static GLOBAL_REDIS_POOL: LazyLock<deadpool::Pool> = LazyLock::new(|| { |
| 7 | + let config = get_config(); |
| 8 | + config.create_pool(Some(deadpool::Runtime::Tokio1)).unwrap() |
| 9 | +}); |
| 10 | + |
| 11 | +pub fn get_connection() -> deadpool::Pool { |
| 12 | + GLOBAL_REDIS_POOL.clone() |
6 | 13 | } |
7 | 14 |
|
8 | | -pub fn save_vec_to_set<'a, V: serde::Deserialize<'a> + serde::Serialize>( |
9 | | - name: String, |
| 15 | +pub fn get_config() -> deadpool::Config { |
| 16 | + let url = std::env::var("REDIS_URL"); |
| 17 | + let url = url.expect("Redis connection URI required"); |
| 18 | + deadpool::Config::from_url(url) |
| 19 | +} |
| 20 | + |
| 21 | +pub async fn save_vec_to_set<'a, V: serde::Deserialize<'a> + serde::Serialize>( |
| 22 | + name: &str, |
10 | 23 | data: Vec<V>, |
11 | 24 | overwrite: bool, |
12 | | - mut conn: &mut redis::Connection, |
13 | | -) -> Result<(), Box<dyn std::error::Error>> { |
| 25 | + redis: &mut Connection, |
| 26 | +) -> Result<(), anyhow::Error> { |
14 | 27 | if overwrite { |
15 | | - redis::cmd("DEL").arg(&name).query(&mut conn)?; |
| 28 | + redis.del::<_, ()>(&name).await?; |
16 | 29 | } |
17 | 30 |
|
18 | 31 | for i in data { |
19 | 32 | let value_name = serde_json::to_string(&i)?; |
20 | | - redis::cmd("SADD") |
21 | | - .arg(&name) |
22 | | - .arg(value_name) |
23 | | - .query(&mut conn)?; |
| 33 | + redis.sadd::<_, _, ()>(&name, value_name).await?; |
24 | 34 | } |
25 | 35 |
|
26 | 36 | Ok(()) |
27 | 37 | } |
28 | 38 |
|
29 | | -pub fn load_set_to_vec( |
30 | | - name: String, |
31 | | - mut conn: &mut redis::Connection, |
32 | | -) -> Result<Vec<String>, Box<dyn std::error::Error>> { |
33 | | - let set_values: Vec<String> = redis::cmd("SMEMBERS").arg(&name).query(&mut conn)?; |
34 | | - |
| 39 | +pub async fn load_set_to_vec( |
| 40 | + name: &str, |
| 41 | + redis: &mut Connection, |
| 42 | +) -> Result<Vec<String>, anyhow::Error> { |
| 43 | + let set_members = redis.smembers::<_, Vec<String>>(&name).await?; |
35 | 44 | let mut result = Vec::new(); |
36 | | - for mut value in set_values { |
| 45 | + for mut value in set_members { |
37 | 46 | if value.starts_with('"') { |
38 | 47 | value = value[1..value.len() - 1].to_string(); |
39 | 48 | } |
|
0 commit comments