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 ...
随机推荐
- 1089 狼人杀-简单版 (20 分)C语言
以下文字摘自<灵机一动·好玩的数学>:"狼人杀"游戏分为狼人.好人两大阵营.在一局"狼人杀"游戏中,1 号玩家说:"2 号是狼人" ...
- yum回滚至Kubernetes1.15.7版本
背景:升级Kubernetes版本从1.14.1-->1.17.0,官方说明不能跨版本升级,所以只好一个版本一个版本升级.最终升到1.17.0后发现API的格式有改动,之前的中间件版本很多不支持 ...
- (httpd、php)2
(一)再说编译安装httpd2.4 新特性: 1:MPM(多处理模块)支持运行为DSO(动态共享,动态加载模式)机制,以模块形式按需加载,支持动态加载 2:event MPM生产环境可用 3:支持异步 ...
- schedule of 2016-09-26~2016-10-02(Monday~Sunday)——1st semester of 2nd Grade
2016/9/26 Monday 1.make ppt for this afternoon's group meeting 2.ask teacher Xiqi&Liu some probl ...
- ArcEngine语法笔记(VB)
1.获取图层字段 Dim pTable As ITable = pLayer Dim pField As IField pField = pTable.Fields.Field(i) Next 2. ...
- Spring Boot2 系列教程 (十六) | 整合 WebSocket 实现广播
前言 如题,今天介绍的是 SpringBoot 整合 WebSocket 实现广播消息. 什么是 WebSocket ? WebSocket 为浏览器和服务器提供了双工异步通信的功能,即浏览器可以向服 ...
- 怎样使用七牛云CDN加速并绑定阿里云域名
昨天晚上在某个群里看到群友问,七牛云能不能绑定自己的域名作为静态资源文件的前缀,忽然想起来我已经有快两年时间没有登录过我的七牛云账号了,不禁老脸一红,这是有多久没有自己前后端都弄了,幸好还没有老年痴呆 ...
- C++ 排序引用的优化
链接:https://www.nowcoder.com/acm/contest/83/B来源:牛客网 题目描述 第一次期中考终于结束啦!沃老师是个语文老师,他在评学生的作文成绩时,给每位学生的分数都是 ...
- JS原型,原型链,类,继承,class,extends,由浅到深
一.构造函数和原型 1.构造函数.静态成员和实例成员 在ES6之前,通常用一种称为构造函数的特殊函数来定义对象及其特征,然后用构造函数来创建对象.像其他面向对象的语言一样,将抽象后的属性和方法封装到对 ...
- GStreamer基础教程13 - 调试Pipeline
摘要 在很多情况下,我们需要对GStreamer创建的Pipeline进行调试,来了解其运行机制以解决所遇到的问题.为此,GStreamer提供了相应的调试机制,方便我们快速定位问题. 查看调试日志 ...