< 返回我的博客

lsk569937453 发表于 2023-03-13 22:16

lazy_static! {
        pub static ref TOKIO_RUNTIME: Runtime = Builder::new_multi_thread()
            .worker_threads(4)
            .thread_name("my-custom-name")
            .thread_stack_size(3 * 1024 * 1024)
            .max_blocking_threads(1000)
            .enable_all()
            .build()
            .unwrap();
    }
#[test]
    fn test_https_client_ok() {
        let private_key_path = env::current_dir()
            .unwrap()
            .join("config")
            .join("privkey.pem");
        let private_key = std::fs::read_to_string(private_key_path).unwrap();

        let ca_certificate_path = env::current_dir()
            .unwrap()
            .join("config")
            .join("privkey.pem");
        let ca_certificate = std::fs::read_to_string(ca_certificate_path).unwrap();

        TOKIO_RUNTIME.spawn(async {
            let (_, receiver) = tokio::sync::mpsc::channel(10);

            let mut http_proxy = HttpProxy {
                port: 4450,
                channel: receiver,
                mapping_key: String::from("random key"),
            };
            http_proxy
                .start_https_server(ca_certificate, private_key)
                .await;
        });
        let sleep_time = time::Duration::from_millis(100);
        thread::sleep(sleep_time);
        TOKIO_RUNTIME.spawn(async {
            let client = Clients::new();
            let request = Request::builder()
                .uri("https://localhost:4450/get")
                .body(Body::empty())
                .unwrap();
            let response_result = client.request_https(request).await;
            assert_eq!(response_result.is_ok(), true);
            let response = response_result.unwrap();
            assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
            let body_bytes = hyper::body::to_bytes(response.into_body()).await.unwrap();
            println!("{:?}", body_bytes);
            let base_response: BaseResponse<String> = serde_json::from_slice(&body_bytes).unwrap();
            assert_eq!(base_response.response_code, -1);
        });
        let sleep_time2 = time::Duration::from_millis(1000);
        thread::sleep(sleep_time2);
    }

以上是我的单元测试用例,主要用来启动一个http server,然后用http client去调用一下这个server。上面的代码是ok的。

问题是如果将代码里的spawn改为spawn_blocking,那么spawn_blocking包含的代码都不会执行。而如果改为spawn,则spawn包含的代码都会执行。这是为什么呢?

评论区

写评论

还没有评论

1 共 0 条评论, 1 页