实现跨语言通信的便捷之道:RPC在Java和Go中的使用案例
// Java 服务端代码
public class GreeterImpl implements Greeter {
@Override
public String greet(String name) {
return "Hello, " + name + "!";
}
}
// Java 客户端代码
public class GreeterClient {
private final GreeterBlockingStub stub;
public GreeterClient(String host, int port) {
ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
stub = GreeterGrpc.newBlockingStub(channel);
}
public String greet(String name) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloResponse response = stub.sayHello(request);
return response.getMessage();
}
}
// Go 服务端代码
type Greeter struct {}
func (g *Greeter) Greet(ctx context.Context, request *pb.HelloRequest) (*pb.HelloResponse, error) {
return &pb.HelloResponse{Message: "Hello, " + request.Name + "!"}, nil
}
// Go 客户端代码
func Greet(c pb.GreeterClient, name string) (string, error) {
response, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})
if err != nil {
return "", err
}
return response.Message, nil
}
这两个代码示例展示了如何在Java和Go语言中实现gRPC服务端和客户端。Java服务端实现了RPC接口,Go服务端和客户端使用protobuf定义了序列化的消息格式,并实现了相应的服务调用。这为跨语言的分布式系统通信提供了一个简洁的实践案例。
评论已关闭