#服务发现 #etcd #发现 #tonic #注册

etcd-discovery

Etcd发现和注册为tonic

6个版本

0.1.6 2024年4月29日
0.1.5 2024年4月29日
0.1.3 2023年11月12日

#541Web编程

Download history 233/week @ 2024-04-23 101/week @ 2024-04-30 2/week @ 2024-05-21 128/week @ 2024-07-30

每月128次下载

MIT/Apache

22KB
364

Etcd发现和注册为tonic

使用

[dependencies]
tokio = { version = "1", features = ["macros","rt-multi-thread"] }
tonic = "0.11"
etcd-discovery = "0.1"

服务器

async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let addr = "127.0.0.1:50051";
    
    // 使用etcd注册服务
    let opt = ConnectOptions::new().with_user("tonic_user", "789789");
    let mut register = EtcdRegister::connect(["127.0.0.1:2379"], Some(opt)).await?;
    register.lease_grant(30, 10).await?;
    register.put("/hello/1", format!("http://{addr}")).await?;
    
    let greeter = MyGreeter::default();
    let svc = GreeterServer::new(greeter);

    tracing::info!("GreeterServer listening on: {}", addr);
    
    Server::builder()
        // 使用拦截器
        // .layer(tonic::service::interceptor(check_auth))
        .add_service(svc)
        .serve(addr.parse()?)
        .await?;

    Ok(())
}

客户端


#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    tracing_subscriber::fmt().init();
    // 使用etcd服务发现
    let opt = ConnectOptions::new().with_user("tonic_user", "789789");
    let mut discover = EtcdTonicDiscovery::connect(["127.0.0.1:2379"], Some(opt)).await?;
    discover.service_discover("/hello").await?;
    
    let channel = discover.get_service("/hello/1").unwrap();
    let mut client = GreeterClient::new(channel);

    let request = tonic::Request::new(HelloRequest {
        name: "Tonic".into(),
    });

    let response = client.say_hello(request).await?;
    println!("RESPONSE={:?}", response);

    tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;
        
   

    Ok(())
}

依赖

~5.5–9MB
~149K SLoC