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. Go中的Package和Module分析

    Package 所谓package(包)其实就是代码的一种组织管理方式,代码多了就需要放入文件,文件多了就需要归类放入文件夹,就好比我们在给电脑装软件时会进行归类安装,其实也是有意无意对电脑软件安装的 ...

  2. ThinkPHP5——接入腾讯云短信API

    接入腾讯云短信API相当简单,最重要的是第一次使用腾讯云短信的话有100条免费短信可以测试,对于开发人员是足够了,下面我就教大家接入腾讯云短信. 第一步:准备工作 首先要在腾讯云短信申请短信签名与短信 ...

  3. 更好用的 Python 任务自动化工具:nox 官方教程

    英文| nox tutorial 出处| nox 官方文档 译者| 豌豆花下猫@Python猫 Github地址:https://github.com/chinesehuazhou/nox_doc_c ...

  4. 一步一步教你PowerBI利用爬虫获取天气数据分析

    对于爬虫大家应该不会陌生,我们首先来看一下爬虫的定义:网络爬虫是一种自动获取网页内容的程序,是搜索引擎的重要组成部分.网络爬虫为搜索引擎从万维网下载网页,自动获取网页内容的应用程序.看到定义我们应该已 ...

  5. P1640 [SCOI2010]连续攻击游戏 二分图最大匹配 匈牙利算法

    题目描述 lxhgww最近迷上了一款游戏,在游戏里,他拥有很多的装备,每种装备都有2个属性,这些属性的值用[1,10000]之间的数表示.当他使用某种装备时,他只能使用该装备的某一个属性.并且每种装备 ...

  6. TCP/IP协议与HTTP协议(二)

    TCP/IP协议是传输层协议,主要解决数据如何在网络中传输,而HTTP是应用层协议,主要解决如何包装数据. 1.TCP连接 手机能够使用联网功能是因为手机底层实现了TCP/IP协议,可以使手机终端通过 ...

  7. 解决.net core读取appSetting.json文件中文字符乱码

    如上所诉 vs菜单栏中  :工具 =>自定义 => 命令 =>添加命令 =>文件 =>找到高级保存选项点击 然后关闭,这时在visual studio界面就会有高级保存选 ...

  8. java 三元运算

    一.格式: 数据类型 变量名称 = 条件判断 ? 表达式a : 表达式b; 二.注意: 1.不是打印操作时,需要 三元运算的右则 2.表达式a和表达式b的值,必须要和变量名称 的数据类型相等 貌似和C ...

  9. ssm项目中中文字符乱码

    昨天给同学改一个错,在SSM项目中,表单输入的String类型中,中文字符值,总是乱码,在控制器层获取的数据就开始乱码,先后进行了如下排查: web.xml中配置设置字符编码的监听器(过滤器), js ...

  10. 学习 lind api 十月 第一弹

    step one 我们来看一下代码的结构