gRPC HelloWorld java版
程序员文章站
2023-12-25 11:05:57
...
1. 创建一个maven项目
2. 加入依赖
3. 编写proto文件
4. 编写服务端文件, 和客户端文件
package org;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
/**
*
* Created by saxing on 2018/5/30.
*/
public class HelloWorldServer {
private int port = 23333;
private Server server;
private void start() throws IOException{
server = ServerBuilder.forPort(port)
.addService(new GreeterImpl())
.build()
.start();
System.out.println("service start...");
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
HelloWorldServer.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop(){
if (server != null){
server.shutdown();
}
}
public static void main(String[] args) throws InterruptedException, IOException {
final HelloWorldServer server = new HelloWorldServer();
server.start();
server.blockUtilShutdown();
}
private void blockUtilShutdown() throws InterruptedException{
if (server != null){
server.awaitTermination();
}
}
private class GreeterImpl extends GreeterGrpc.GreeterImplBase{
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver){
System.out.println("service: " + req.getName());
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
package org;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.examples.helloworld.GreeterGrpc;
import io.grpc.examples.helloworld.HelloReply;
import io.grpc.examples.helloworld.HelloRequest;
import java.util.concurrent.TimeUnit;
/**
*
* Created by saxing on 2018/5/30.
*/
public class HelloWorldClient {
private final ManagedChannel channel;
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public HelloWorldClient(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext(true)
.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();
HelloReply response = blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
public static void main(String[] args) throws InterruptedException {
HelloWorldClient client = new HelloWorldClient("127.0.0.1", 23333);
for (int i = 0; i < 5; i++) {
client.greet("world: " + i);
}
client.shutdown();
}
}
5. 运行测试结果
更多详细参考:
https://github.com/grpc/grpc-java/tree/master/examples/src/main/java/io/grpc/examples