1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#![deny(missing_docs, missing_debug_implementations)]
pub extern crate bb8;
pub extern crate redis;
extern crate futures;
extern crate tokio;
use futures::{Future, IntoFuture};
use redis::async::Connection;
use redis::{Client, RedisError};
use std::option::Option;
type Result<T> = std::result::Result<T, RedisError>;
#[derive(Debug)]
pub struct RedisPool {
pool: bb8::Pool<RedisConnectionManager>,
}
impl RedisPool {
pub fn new(pool: bb8::Pool<RedisConnectionManager>) -> RedisPool {
RedisPool { pool }
}
pub fn run<'a, T, E, U, F>(
&self,
f: F,
) -> impl Future<Item = T, Error = bb8::RunError<E>> + Send + 'a
where
F: FnOnce(Connection) -> U + Send + 'a,
U: IntoFuture<Item = (Connection, T), Error = E> + 'a,
U::Future: Send,
E: From<<RedisConnectionManager as bb8::ManageConnection>::Error> + Send + 'a,
T: Send + 'a,
{
let f = move |conn: Option<Connection>| {
let conn = conn.unwrap();
f(conn)
.into_future()
.map(|(conn, item)| (item, Some(conn)))
.map_err(|err| (err, None))
};
self.pool.run(f)
}
}
#[derive(Clone, Debug)]
pub struct RedisConnectionManager {
client: Client,
}
impl RedisConnectionManager {
pub fn new(client: Client) -> Result<RedisConnectionManager> {
Ok(RedisConnectionManager { client })
}
}
impl bb8::ManageConnection for RedisConnectionManager {
type Connection = Option<Connection>;
type Error = RedisError;
fn connect(
&self,
) -> Box<Future<Item = Self::Connection, Error = Self::Error> + Send + 'static> {
Box::new(self.client.get_async_connection().map(|conn| Some(conn)))
}
fn is_valid(
&self,
conn: Self::Connection,
) -> Box<Future<Item = Self::Connection, Error = (Self::Error, Self::Connection)> + Send> {
Box::new(
redis::cmd("PING")
.query_async(conn.unwrap())
.map_err(|err| (err, None))
.map(|(conn, ())| Some(conn)),
)
}
fn has_broken(&self, conn: &mut Self::Connection) -> bool {
conn.is_none()
}
}