由于篇幅限制,我将提供每种语言(Java, Go, Python)使用gRPC的简单示例。
Java
首先,确保你有protoc
编译器和相应的gRPC Java库。
// GreeterService.proto
syntax = "proto3";
package example;
service Greeter {
rpc Greet(GreetRequest) returns (GreetResponse) {}
}
message GreetRequest {
string name = 1;
}
message GreetResponse {
string message = 1;
}
然后使用protoc
编译器生成Java代码:
protoc --java_out=. GreeterService.proto
生成的Java代码可以在Java gRPC应用中用来实现服务端和客户端。
服务端示例:
public class GreeterServiceImpl extends GreeterGrpc.GreeterImplBase {
@Override
public void greet(GreetRequest req, StreamObserver<GreetResponse> responseObserver) {
GreetResponse response = GreetResponse.newBuilder().setMessage("Hello, " + req.getName()).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
客户端示例:
ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build();
GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel);
GreetRequest request = GreetRequest.newBuilder().setName("gRPC").build();
GreetResponse response = stub.greet(request);
System.out.println(response.getMessage());
channel.shutdown();
Go
首先,安装protoc
编译器和protoc-gen-go
和protoc-gen-go-grpc
插件。
// greeter.proto
syntax = "proto3";
package pb;
service Greeter {
rpc Greet (GreetRequest) returns (GreetResponse) {}
}
message GreetRequest {
string name = 1;
}
message GreetResponse {
string message = 1;
}
使用protoc
编译器生成Go代码:
protoc --go_out=. --go_opt=paths=source_relative --go-grpc_out=. --go-grpc_opt=paths=source_relative greeter.proto
生成的Go代码可以在Go gRPC应用中用来实现服务端和客户端。
服务端示例:
func (s *server) Greet(ctx context.Context, req *pb.GreetRequest) (*pb.GreetResponse, error) {
return &pb.GreetResponse{Message: "Hello, " + req.Name}, nil
}
客户端示例:
conn, err := grpc.DialContext(context