我想在使用 hyper.rs 创建的服务器应用程序的开头使用 ODBC (odbc-api) 连接到 MSSQL。
我想要一个连接池,并在每个请求内获取一个连接,该连接可能在不同的线程中执行。
我的问题是了解需要在全局级别完成哪些操作以及需要向每个线程发送哪些内容,以便重用连接并避免打开和关闭可能降低连接管理效率的不同连接。
请注意,应用程序每秒可能会收到大量请求。
我在这段代码中对其进行了简化,没有考虑 hyper.rs 和最终实现的其他元素的存在,但我相信它可以提供一个想法:
https://gist.github.com/dertin/d5e6b031cb86fbe71c6d2272c764dedd
如果您能给我进行代码审查,我将不胜感激。 谢谢,有什么意见欢迎留言。
引用关于连接池的
odbc-api
指南。请参阅:https://docs.rs/odbc-api/3.0.1/odbc_api/guide/index.html
use lazy_static::lazy_static;
use odbc_api::{Environment, sys::{AttrConnectionPooling, AttrCpMatch}};
lazy_static! {
pub static ref ENV: Environment = {
// Enable connection pooling. Let driver decide whether the attributes of two connection
// are similar enough to change the attributes of a pooled one, to fit the requested
// connection, or if it is cheaper to create a new Connection from scratch.
// See <https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/driver-aware-connection-pooling>
//
// Safety: This call changes global mutable space in the underlying ODBC driver manager.
unsafe {
Environment::set_connection_pooling(AttrConnectionPooling::DriverAware).unwrap();
}
let mut env = Environment::new().unwrap();
// Strict is the default, and is set here to be explicit about it.
env.set_connection_pooling_matching(AttrCpMatch::Strict).unwrap();
env
};
}