gRPC Java、Go、PHP使用例子
由于篇幅所限,以下是每种语言的gRPC客户端和服务端示例代码。
Java:
// 服务端
public class GreeterService extends GreeterGrpc.GreeterImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
HelloResponse response = HelloResponse.newBuilder().setMessage("Hello " + request.getName()).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
// 客户端
public class GreeterClient {
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public GreeterClient(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = GreeterGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void greet(String name) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloResponse response = blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
}
Go:
// 服务端
func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
return &pb.HelloResponse{Message: "Hello " + req.Name}, nil
}
// 客户端
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(time.Second))
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
client := pb.NewGreeterClient(conn)
response, err := client.SayHello(context.Background(), &pb.HelloRequest{Name: "World"})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Greeting: %s", response.Message)
}
PHP:
// 服务端
class GreeterService extends GreeterClient {
public function SayHello(HelloRequest $request): HelloResponse {
$response = new HelloResponse();
$response->setMessage('Hello ' . $request->getName());
return $response;
}
}
// 客户端
$client = new GreeterClient('localhost:50051', [
'credentials' => Grpc\ChannelCredentials::createInsecure(),
]);
$request = new HelloRequest();
$request->setName("World");
$response = $client->SayHello($request);
echo $response->getMessage();
评论已关闭