Actix-web Rust连接Postgres数据库
Rust1.39支持了异步async,await,Actix-web在2.0.0-alpha支持了原生异步写法,所以本文中使用的Actix-web版本为2.0.0-alpha.4。
Actix-web官方例子使用的是r2d2连接池库,这个库并不是异步库,需要用web::block的api,不是很方便,我找到了一个deadpool-postgres连接池库,采用tokio-postgres作为数据库连接。直接支持异步省去很多麻烦。
初始化项目
直接用cargo new pgtest来初始化一个项目
修改Cargo.toml
[package]
name = "pgtest"
version = "0.1.0"
authors = ["yuxq"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "2.0.0-alpha.4"
# actix运行时
actix-rt = "1.0.0-alpha.3"
tokio-postgres = "0.5.0-alpha.2"
deadpool-postgres = "0.2.3"
修改默认main方法
官方运行异步actix服务器是使用actix-rt库