Connection pool
Recipe | Crates | Categories |
---|---|---|
Create a connection pool |
Create a connection pool
deadpool
is a simple async pool for connections and objects of any type.
use deadpool::managed; #[derive(Debug)] enum Error { Fail, } struct Server; impl Server { async fn get_answer(&self) -> i32 { 42 } } struct Manager; impl managed::Manager for Manager { type Error = Error; type Type = Server; async fn create(&self) -> Result<Server, Error> { Ok(Server) } async fn recycle( &self, _: &mut Server, _: &managed::Metrics, ) -> managed::RecycleResult<Error> { Ok(()) } } type Pool = managed::Pool<Manager>; #[tokio::main] async fn main() -> anyhow::Result<()> { let mgr = Manager; let pool = Pool::builder(mgr).build()?; let conn = pool.get().await.map_err(|err| { anyhow::anyhow!("Could not retrieve from the Pool: {:?}", err) })?; let answer = conn.get_answer().await; assert_eq!(answer, 42); println!("The answer is {}", answer); Ok(()) }
[connection_pool: expand; example (P1)](https://github.com/john-cd/rust_howto/issues/284)
use deadpool_postgres::Runtime; use dotenvy::dotenv; use tokio_postgres::NoTls; #[derive(Debug, serde::Deserialize)] struct Config { pub pg: deadpool_postgres::Config, } // Hydrate the configuration from environment variables e.g. // add to your .env file // PG__HOST=pg.example.com // PG__USER=john_doe // PG__PASSWORD=topsecret // PG__DBNAME=example // PG__POOL__MAX_SIZE=16 // PG__POOL__TIMEOUTS__WAIT__SECS=5 // PG__POOL__TIMEOUTS__WAIT__NANOS=0 impl Config { pub fn from_env() -> Result<Self, config::ConfigError> { config::Config::builder() .add_source(config::Environment::default().separator("__")) .build()? .try_deserialize() } } #[tokio::main] async fn main() -> anyhow::Result<()> { dotenv().ok(); let cfg = Config::from_env()?; let pool = cfg.pg.create_pool(Some(Runtime::Tokio1), NoTls)?; let client = pool.get().await?; let stmt = client.prepare_cached("SELECT version()").await?; let rows = client.query(&stmt, &[]).await?; for row in rows { let version: &str = row.get(0); println!("PostgreSQL version: {}", version); } Ok(()) }