Actix-web Rust连接Postgres数据库
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作为数据库连接。直接支持异步省去很多麻烦。
- deadpool-postgres
- tokio-postgres
- actix-web v:
2.0.0-alpha.4
初始化项目
直接用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::Dataextractor. 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数据库的更多相关文章
- pgadmin(IDE)工具连接postgres数据库
1. 下载软件 软件地址:http://www.pgadmin.org/download/pgagent.php 2.安装软件 安装过程:略 打开软件64位会出现 “无 ...
- Java Web工程连接MySQL数据库及Tomcat服务器页面中文乱码
Java Web工程连接MySQL数据库 一. 准备工作 1.下载连接MySQL数据库的JDBC (可以去官网下,也可以去百度云找) 2.将下载的jar文件复制到Tomcat的lib目录下 3.新建一 ...
- ArcGIS连接Postgres 数据库
ArcGIS连接Postgres 数据库 此前在使用ArcGIS的过程中,一般使用文件方式对数据进行管理,后面也有使用 GeoDatabase 数据库对数据进行管理,但是这种管理方式也存在一些弊端,特 ...
- shell编程连接postgres数据库(数据备份)
第一步:通过xshell或者其他工具连接到linux服务, 第二步:创建一个脚本:touch se.sh 第三步:输入i,代表开始输入内容 输入以下命令: 脚本如下:(sql语句可以是任何复杂的sql ...
- rust连接oracle数据库遇到DPI-1047: Cannot locate a 64-bit Oracle Client library的解决方案
这两天要实现一个用rust连接远程的oracle数据库的需求,所以就需要用rust连接oracle. 在github上面找到一个库,地址:https://github.com/kubo/rust-or ...
- kaili 2.0 metasploit连接postgres数据库
第一步:使用命令 db_init 初始化数据库
- Rust 连接 PostgreSQL 数据库
这次,我们使用 postgres 这个 crate 来连接和操作 PostgreSQL 数据库. 创建好项目后,在 cargo.toml 里添加 postgres 的依赖: 首先,导入相关的类型,并创 ...
- Metasploit连接postgres数据库
操作环境为Kali虚拟机 root@kali:~# apt-get install postgresql 启动服务 root@kali:~# service postgresql start [ ok ...
- kali 2.0中msf连接postgres数据库
装好kali 2.0后直接运行msfconsole msf> db_status postgres selected, no connection 百度到的解决方法多是针对BT和kali 1.0 ...
随机推荐
- Ant Design Pro路由传值
Ant Design Pro 路由传值 了解Ant Design Pro组件间通讯原理的小伙伴肯定都知道,两个页面之间可以通过Models进行传值,在以往的传值过程中,我都是直接将需要的值直接一股脑的 ...
- 2019 年百度之星 初赛一 1002 Game
传送门 Problem Description 度度熊在玩一个好玩的游戏.游戏的主人公站在一根数轴上,他可以在数轴上任意移动,对于每次移动,他可以选择往左或往右走一格或两格.现在他要依次完成 n 个任 ...
- Sql Server执行一条Update语句很慢,插入数据失败
今天同事要我修改服务器数据库里面的2条数据,查看服务器上的SQL Server数据库的时候,发现这几天数据没有添加成功,然后发现磁盘很快就满了,执行Update语句时,执行半天都提示还在执行,查询语句 ...
- 人脸识别系统 —— 基于python的人工智能识别核心
起因 自打用python+django写了一个点菜系统,就一直沉迷python编程.正好前几天公司boss要我研究一下人脸识别,于是我先用python编写了一个人脸识别系统的核心,用于之后的整个系统. ...
- 理解 SQL 开窗函数
一次面试被问到开窗函数,懵逼了,赶紧补补总结一下.... 开窗函数也是函数,所以 比如在原来的查询上添加一个总数列 create table ztest( id int identity, c1 in ...
- 全网最详细的Linux命令系列-sed文本处理命令
Sed简介 SED是一个非交互式文本编辑器,它可对文本文件和标准输入进行编辑,标准输入可以来自键盘输入.文本重定向.字符串.变量,甚至来自于管道的文本,与VIM编辑器类似,它一次处理一行内容,Sed可 ...
- map set vector用法小总结
1.Map 定义 #include<map> map<string,bool> mp; 插入 mp[s]=; mp.insert(make_pair(s,)); 输出 cout ...
- STL 结构体内重载 一个比较运算符
struct node { ll a, b; bool operator< (const node &c)const{ return a < c.a; } }pre[eps];
- 《C# 爬虫 破境之道》:第二境 爬虫应用 — 第三节:处理压缩数据
续上一节内容,本节主要讲解一下Web压缩数据的处理方法. 在HTTP协议中指出,可以通过对内容压缩来减少网络流量,从而提高网络传输的性能. 那么问题来了,在HTTP中,采用的是什么样的压缩格式和机制呢 ...
- python中常⽤的excel模块库
python中常用的excel模块库&安装方法 openpyxl openpyxl是⼀个Python库,用于读取/写⼊Excel 2010 xlsx / xlsm / xltx / xltm⽂ ...