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库,方法如下

#[actix_rt::main]
async fn main()-> std::io::Result<()> {
HttpServer::new( ||
App::new()
.bind("127.0.0.1:8080")?
.start()
.await
}

创建postgres连接池

use deadpool_postgres::{Manager, Pool};
use tokio_postgres::{Config, NoTls}; #[actix_rt::main]
async fn main()-> std::io::Result<()> {
let mut cfg = Config::new();
cfg.host("localhost");//数据库地址
cfg.user("db");//数据库用户名
cfg.password("db");//数据库密码
cfg.dbname("asynctest");//数据库名称
let mgr = Manager::new(cfg, tokio_postgres::NoTls);
let pool = Pool::new(mgr, 15);//最大15个连接
}

绑定连接池对象

actix-web官方文档对State的解释

Application state is shared with all routes and resources within the same scope. State can be accessed with the web::Data extractor. State is also available for route matching guards and middlewares.

我们可以把对象绑定进Application,同所有具有相同命名空间的路径和资源共享,之后再用web::Data提取器获取到。

use deadpool_postgres::{Manager, Pool};
use tokio_postgres::{Config, NoTls}; #[actix_rt::main]
async fn main()-> std::io::Result<()> {
let mut cfg = Config::new();
cfg.host("localhost");//数据库地址
cfg.user("db");//数据库用户名
cfg.password("db");//数据库密码
cfg.dbname("asynctest");//数据库名称
let mgr = Manager::new(cfg, tokio_postgres::NoTls);
let pool = Pool::new(mgr, 15);//最大15个连接 HttpServer::new( move ||
App::new().data(pool.clone())
.bind("127.0.0.1:8080")?
.start()
.await
}

handler中获取数据库连接池

首先让我们创建一个具有web::Data提取器的handler

我在本机上跑了一个docker运行postgres数据库

创建了一个users的表,字段有【id,name,age】例子只获取name

use actix_web::{web,Responder};
use deadpool_postgres::{Manager, Pool}; async fn get_user(db:web::Data<Pool>)->impl Responder{
let mut conn=db.get().await.unwrap();
let rows=conn.query("select * from users",&[]).await.unwrap();
let v:String=rows[0].get("name");//get参数可以是str,也可以是i32,获取第几个。但是必须要指明获取的类型
format!("{}",v)
}

将handler绑定至server application

    HttpServer::new( move ||
App::new().data(pool.clone()).route("user",web::get().to(get_user))
.bind("127.0.0.1:8080")?
.start()
.await

通过cargo run运行即可。

Actix-web Rust连接Postgres数据库的更多相关文章

  1. pgadmin(IDE)工具连接postgres数据库

    1. 下载软件        软件地址:http://www.pgadmin.org/download/pgagent.php   2.安装软件    安装过程:略    打开软件64位会出现  “无 ...

  2. Java Web工程连接MySQL数据库及Tomcat服务器页面中文乱码

    Java Web工程连接MySQL数据库 一. 准备工作 1.下载连接MySQL数据库的JDBC (可以去官网下,也可以去百度云找) 2.将下载的jar文件复制到Tomcat的lib目录下 3.新建一 ...

  3. ArcGIS连接Postgres 数据库

    ArcGIS连接Postgres 数据库 此前在使用ArcGIS的过程中,一般使用文件方式对数据进行管理,后面也有使用 GeoDatabase 数据库对数据进行管理,但是这种管理方式也存在一些弊端,特 ...

  4. shell编程连接postgres数据库(数据备份)

    第一步:通过xshell或者其他工具连接到linux服务, 第二步:创建一个脚本:touch se.sh 第三步:输入i,代表开始输入内容 输入以下命令: 脚本如下:(sql语句可以是任何复杂的sql ...

  5. rust连接oracle数据库遇到DPI-1047: Cannot locate a 64-bit Oracle Client library的解决方案

    这两天要实现一个用rust连接远程的oracle数据库的需求,所以就需要用rust连接oracle. 在github上面找到一个库,地址:https://github.com/kubo/rust-or ...

  6. kaili 2.0 metasploit连接postgres数据库

    第一步:使用命令 db_init 初始化数据库

  7. Rust 连接 PostgreSQL 数据库

    这次,我们使用 postgres 这个 crate 来连接和操作 PostgreSQL 数据库. 创建好项目后,在 cargo.toml 里添加 postgres 的依赖: 首先,导入相关的类型,并创 ...

  8. Metasploit连接postgres数据库

    操作环境为Kali虚拟机 root@kali:~# apt-get install postgresql 启动服务 root@kali:~# service postgresql start [ ok ...

  9. kali 2.0中msf连接postgres数据库

    装好kali 2.0后直接运行msfconsole msf> db_status postgres selected, no connection 百度到的解决方法多是针对BT和kali 1.0 ...

随机推荐

  1. 使用阿里云 ECS 快速部署 WordPress 博客系统

    今天在 阿里云 ECS上 部署了一套 Lamp 系统,建了一个WordPress的网站,把操作过程记录下来,文中所列脚本可以直接应用. 废话不多说直接开动,ECS云服务购买可以点击 阿里云ECS 云主 ...

  2. 《【面试突击】— Redis篇》--Redis都有哪些数据类型?分别在哪些场景下使用比较合适?

    能坚持别人不能坚持的,才能拥有别人不能拥有的.关注编程大道公众号,让我们一同坚持心中所想,一起成长!! <[面试突击]— Redis篇>--Redis都有哪些数据类型?分别在哪些场景下使用 ...

  3. codeforces 上的找两人的幸运天

    Bob and Alice are often participating in various programming competitions. Like many competitive pro ...

  4. 解决 VS Code 中 golang.org 被墙导致的 Go 插件安装失败问题

    微软官方开发的 Go for Visual Studio Code 插件为 Go 语言 提供了丰富的支持.在 VS Code 中首次打开 Go 工作区后,VS Code 会自动检测当前开发环境为 Go ...

  5. Redis常用命令详细介绍

    一.字符串 字符串键是Redis最基本的键值对类型,将一个单独的键和一个单独的值关联起来.通过字符串键,不仅可以存储和读取字符串,如果输入能被解释为整数和浮点数,还能执行自增或自减操作. 1.SET: ...

  6. git 工作中实用 多人协同开发

    多人协同开发 .克隆分支 git clone -b dev1. url .创建并关联远程分支 git checkout -b dev_wt origin/dev_wt 情况一获取其它分支的代码,并合并 ...

  7. numpy 其它常用方法

    一.创建特殊的数组 1.ones() 语法 np.ones(shape, dtype=None) # shape 创建数组的shape # dtype 指定数组的数据类型 例子 import nump ...

  8. Scrapy持久化(items+pipelines)

    一.items保存爬取的文件 items.py import scrapy class QuoteItem(scrapy.Item): # define the fields for your ite ...

  9. Redis(六):list/lpush/lrange/lpop 命令源码解析

    上一篇讲了hash数据类型的相关实现方法,没有茅塞顿开也至少知道redis如何搞事情的了吧. 本篇咱们继续来看redis中的数据类型的实现: list 相关操作实现. 同样,我们以使用者的角度,开始理 ...

  10. 发现 一个业务管理系统 解决了 orm 和 前端框架 剩下的 是 业务逻辑 了 。 哈

    解决了 orm 和 前端框架 剩下的 是 业务逻辑 了 . 哈 还有 各种 aop 组件 呢 . 大家 high 来 准备 用 fluent data  和 mysql 写一个 wcf 的 接口呢. ...