如何为 Hyper 处理程序共享可变状态? [英] How to share mutable state for a Hyper handler?

查看:48
本文介绍了如何为 Hyper 处理程序共享可变状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举一个非常简单的例子,我正在尝试编写一个简单回复的网络服务器

As a very simple example, I'm trying to write a webserver that simply replies

此页面已被请求 $N 次

this page has been requested $N times

但是我在共享可变状态时遇到了很多麻烦.这是我最好的尝试:

but I'm having a lot of trouble sharing the mutable state for this to happen. Here's my best attempt:

extern crate hyper;

use hyper::Server;
use hyper::server::Request;
use hyper::server::Response;

struct World {
    count: i64,
}

impl World {
    fn greet(&mut self, req: Request, res: Response) {
        self.count += 1;
        let str: String = format!("this page has been requested {} times", self.count);
        res.send(str.as_bytes()).unwrap();
    }
}

fn main() {
    println!("Started..");

    let mut w = World { count: 0 }; 

    Server::http("127.0.0.1:3001").unwrap()
        .handle(move |req: Request, res: Response| w.greet(req, res) ).unwrap();

}

推荐答案

因为请求处理可能发生在不同的线程中,所以需要同步访问全局状态,为此需要使用诸如 Mutex:

Because request handling may happen in different threads, you need to synchronize access to the global state, for which you need to use things like Mutex:

let w = Mutex::new(World { count: 0 });

Server::http("127.0.0.1:3001").unwrap()
    .handle(move |req: Request, res: Response| w.lock().unwrap().greet(req, res))
    .unwrap();

你可以从Server::handle():它要求它的处理程序是 Handler + 'staticHandler 本身需要Send + Sync.因此,这个闭包捕获的所有内容也必须是'static + Send + Sync,即可以安全地从多个线程访问.包装到互斥锁中的值通常满足这些要求(当然,如果它们不包含引用).

You can find this out from the signature of Server::handle(): it requires its handler to be Handler + 'static, and Handler itself requires Send + Sync. Therefore, everything this closure captures must also be 'static + Send + Sync, that is, safe to access from multiple threads. Values wrapped into a mutex usually satisfy these requirements (if they don't contain references, of course).

这篇关于如何为 Hyper 处理程序共享可变状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆