我正在用Rust
编写我的第一个hyper
微服务。经过C++
和Go
的多年开发,我倾向于使用控制器来处理请求(如此处-https://github.com/raycad/go-microservices/blob/master/src/user-microservice/controllers/user.go),其中该控制器存储共享数据,如db连接池和不同类型的缓存。我知道,使用hyper
,我可以这样写:
use hyper::{Body, Request, Response};
pub struct Controller {
// pub cache: Cache,
// pub db: DbConnectionPool
}
impl Controller {
pub fn echo(&mut self, req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
// extensively using db and cache here...
let mut response = Response::new(Body::empty());
*response.body_mut() = req.into_body();
Ok(response)
}
}
然后使用它:
use hyper::{Server, Request, Response, Body, Error};
use hyper::service::{make_service_fn, service_fn};
use std::{convert::Infallible, net::SocketAddr, sync::Arc, sync::Mutex};
async fn route(controller: Arc<Mutex<Controller>>, req: Request<Body>) -> Result<Response<Body>, hyper::Error> {
let mut c = controller.lock().unwrap();
c.echo(req)
}
#[tokio::main]
async fn main() {
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let controller = Arc::new(Mutex::new(Controller{}));
let make_svc = make_service_fn(move |_conn| {
let controller = Arc::clone(&controller);
async move {
Ok::<_, Infallible>(service_fn(move |req| {
let c = Arc::clone(&controller);
route(c, req)
}))
}
});
let server = Server::bind(&addr).serve(make_svc);
if let Err(e) = server.await {
eprintln!("server error: {}", e);
}
}
由于编译器不允许我在线程之间共享可变结构,因此我不得不使用Arc<Mutex<T>>
习惯用法。但是,恐怕let mut c = controller.lock().unwrap();
部分会在处理单个请求时阻塞整个控制器,即此处没有并发性。解决此问题的惯用方法是什么?
&mut
始终获取对该值的(编译时或运行时)排他锁。仅在要锁定的确切范围内获取&mut
。如果锁定值拥有的值需要单独的锁定管理,将其包装在Mutex
中。
假设您的DbConnectionPool
的结构如下:
struct DbConnectionPool {
conns: HashMap<ConnId, Conn>,
}
我们在&mut
上添加/删除项目时需要HashMap
HashMap
,但是我们不需要&mut
中的值。因此,Conn
允许我们将可变性边界与其父项分开,而Arc
允许我们添加其自身的内部可变性。
此外,我们的Mutex
方法不想成为echo
,因此需要在&mut
上添加另一层内部可变性。
所以我们将其更改为
HashMap
然后,当您想建立连接时,
struct DbConnectionPool {
conns: Mutex<HashMap<ConnId, Arc<Mutex<Conn>>>,
}
([fn get(&self, id: ConnId) -> Arc<Mutex<Conn>> {
let mut pool = self.db.conns.lock().unwrap(); // ignore error if another thread panicked
if let Some(conn) = pool.get(id) {
Arc::clone(conn)
} else {
// here we will utilize the interior mutability of `pool`
let arc = Arc::new(Mutex::new(new_conn()));
pool.insert(id, Arc::clone(&arc));
arc
}
}
参数和if-exists-else逻辑用于简化代码;您可以更改逻辑)
您可以执行返回值
ConnId
为了方便说明,我将逻辑更改为用户提供ID。实际上,您应该能够找到尚未获取的self.get(id).lock().unwrap().query(...)
并将其返回。然后,您可以返回Conn
的RAII防护,类似于Conn
的工作方式,当用户停止使用时自动释放连接。
如果可能会提高性能,也请考虑使用MutexGuard
而不是RwLock
。