apache_dubbo/protocol/grpc/
grpc_invoker.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements.  See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License.  You may obtain a copy of the License at
8 *
9 *     http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use std::sync::Once;
19
20use tonic::client::Grpc;
21use tonic::transport::Channel;
22use tonic::transport::Endpoint;
23
24use crate::common::url::Url;
25use crate::invocation::{Request, Response};
26use crate::protocol::Invoker;
27
28pub struct GrpcInvoker {
29    client: Grpc<Channel>,
30    url: Url,
31    once: Once,
32}
33
34impl GrpcInvoker {
35    pub fn new(url: Url) -> GrpcInvoker {
36        let endpoint = Endpoint::new(url.to_url()).unwrap();
37        let conn = endpoint.connect_lazy();
38        Self {
39            url,
40            client: Grpc::new(conn),
41            once: Once::new(),
42        }
43    }
44}
45
46impl Invoker for GrpcInvoker {
47    fn is_available(&self) -> bool {
48        true
49    }
50
51    fn destroy(&self) {
52        self.once.call_once(|| println!("destroy..."))
53    }
54
55    fn get_url(&self) -> Url {
56        self.url.to_owned()
57    }
58
59    // 根据req中的数据发起req,由Client发起请求,获取响应
60    fn invoke<M1>(&self, req: Request<M1>) -> Response<String>
61    where
62        M1: Send + 'static,
63    {
64        let (metadata, _) = req.into_parts();
65
66        let resp = Response::new("string");
67        let (_resp_meta, msg) = resp.into_parts();
68
69        Response::from_parts(metadata, msg.to_string())
70    }
71}
72
73impl Clone for GrpcInvoker {
74    fn clone(&self) -> Self {
75        Self {
76            client: self.client.clone(),
77            url: self.url.clone(),
78            once: Once::new(),
79        }
80    }
81}