<dependency> <groupId>io.grpc</groupId> <artifactId>grpc-netty</artifactId> <version>1.41.0</version> </dependency> protobuf syntax = "proto3"; package com.example.grpc; service HelloService { rpc sayHello (HelloRequest) returns (HelloResponse) {} } message HelloRequest { string name = 1; } message HelloResponse { string message = 1; } shell protoc -I src/main/proto/ --java_out=src/main/java/ src/main/proto/hello.proto package com.example.grpc; import io.grpc.stub.StreamObserver; public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase { @Override public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) { String name = request.getName(); String message = "Hello, " + name + "!"; HelloResponse response = HelloResponse.newBuilder().setMessage(message).build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } package com.example.grpc; import io.grpc.Server; import io.grpc.ServerBuilder; import java.io.IOException; public class Server { public static void main(String[] args) throws IOException, InterruptedException { Server server = ServerBuilder.forPort(50051) .addService(new HelloServiceImpl()) .build(); server.start(); server.awaitTermination(); } } package com.example.grpc; import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; public class Client { public static void main(String[] args) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051) .usePlaintext() .build(); HelloServiceGrpc.HelloServiceBlockingStub stub = HelloServiceGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName("Alice").build(); HelloResponse response = stub.sayHello(request); System.out.println("Response: " + response.getMessage()); channel.shutdown(); } }


上一篇:
下一篇:
切换中文