是的,不同的 gRPC 方法可以共享同一个存根(stub)和同一个通道(channel)。下面是一个代码示例:
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.examples.helloworld.HelloResponse;
public class GrpcClient {
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public GrpcClient(ManagedChannel channel) {
// 创建存根(stub)
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public HelloResponse sayHello(String name) {
// 调用 gRPC 方法
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
return blockingStub.sayHello(request);
}
public static void main(String[] args) {
// 创建通道(channel)
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
.usePlaintext()
.build();
// 创建 gRPC 客户端
GrpcClient client = new GrpcClient(channel);
// 调用不同的 gRPC 方法
HelloResponse response1 = client.sayHello("Alice");
System.out.println("Response 1: " + response1.getMessage());
HelloResponse response2 = client.sayHello("Bob");
System.out.println("Response 2: " + response2.getMessage());
// 关闭通道(channel)
channel.shutdown();
}
}
在上面的示例中,我们创建了一个 GrpcClient
类,它接受一个 ManagedChannel
作为参数并创建存根(stub)。然后,我们可以调用不同的 gRPC 方法,比如 sayHello
,并使用同一个存根和通道进行通信。
请注意,通道(channel)在使用后需要关闭,以释放资源。在示例中,我们在最后关闭了通道。
上一篇:不同的GraphQL指令的解释