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. HDU2089 不要62 题解 数位DP

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2089 题目大意:求区间 \([l,r]\) 范围内不包含数字"4"且不包含连续的数 ...

  2. K8S与harbor的集成

    文章编写在有道云笔记,采用MarkDown编写,迁移太麻烦了,具体链接如下: http://note.youdao.com/noteshare?id=a9d344951e1fbb761ef7e4979 ...

  3. 【Springboot】注解@ConfigurationProperties让配置整齐而简单

    1 简介 前面我们用一篇文章<[Spring]只想用一篇文章记录@Value的使用,不想再找其它了(附思维导图)> 详细讲解了在Spring中如何使用@Value来实现我们对配置的需求,它 ...

  4. Go中锁的那些姿势,估计你不知道

    什么是锁,为什么使用锁 用俗语来说,锁意味着一种保护,对资源的一种保护,在程序员眼中,这个资源可以是一个变量,一个代码片段,一条记录,一张数据库表等等. 就跟小孩需要保护一样,不保护的话小孩会收到伤害 ...

  5. ThreadLocal = 本地线程?

    一.定义 ThreadLocal是JDK包提供的,从名字来看,ThreadLocal意思就是本地线程的意思. 1.1 是什么? 要想知道他是个啥,我们看看ThreadLocal的源码(基于JDK 1. ...

  6. Thinkpad S440 I/O接口配置

    HDMI 视频接口 SS USB3.0接口 电源接口 音频接口 网络接口 没有com口可以用USB口,然后安装一个USB转com口的驱动.

  7. vnpy源码阅读学习(4):自己写一个类似vnpy的UI框架

    自己写一个类似vnpy的界面框架 概述 通过之前3次对vnpy的界面代码的研究,我们去模仿做一个vn.py的大框架.巩固一下PyQt5的学习. 这部分的代码相对来说没有难度和深度,基本上就是把PyQt ...

  8. NumPy排序

    numpy.sort()函数 该函数提供了多种排序功能,支持归并排序,堆排序,快速排序等多种排序算法 使用numpy.sort()方法的格式为: numpy.sort(a,axis,kind,orde ...

  9. get_字段_display()

    gender_choices = ((1, '男'), (2, '女')) gender = models.IntegerField(verbose_name='性别', choices=gender ...

  10. python常用内置模块-random模块

    random模块:用于生成随机数 '''关于数据类型序列相关,参照https://www.cnblogs.com/yyds/p/6123692.html''' random() 随机获取0 到1 之间 ...