GRPC: Client ID or connection information?

后端 未结 2 408
情话喂你
情话喂你 2021-01-12 12:59

Is there a way to get the connection information on RPC calls from server side? Or maybe something like unique client ID?

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-12 13:32

    There is no connecton information which may help distinguish clients. One reason of this is proxies: different clients can have same IP and port (as I understand)

    One possible solution is handshake protocol in app level. You can add rpc method "Connect" and send clientId as response from server. Afterthat you can attach custom headers (metadata) to your rpc calls.

    Client side java code:

    String clientId = getIdfromServer();
    Metadata.Key CLIENT_ID = Metadata.Key.of("client_id", ASCII_STRING_MARSHALLER);
    Metadata fixedHeaders = new Metadata();
    fixedHeaders.put(CLIENT_ID, clientId);
    blockingStub = MetadataUtils.attachHeaders(blockingStub, fixedHeaders);
    

    This C++ server side code shows how to handle such header on server:

    ::grpc::Status YourRPC(::grpc::ServerContext* context, const Your* request, YourResponse* response)
    {
        const auto clientMetadata = context->client_metadata();
        auto it = clientMetadata.find("client_id");
        auto clientId = std::string(it->second.begin(), it->second.end());
    }
    

    I noticed that metadata key is case insensitive. Grpc converts keys to lowercase.

提交回复
热议问题