.proto文件
syntax = "proto3";
package grpc;
option java_package = "com.lenny";
option java_outer_classname = "HelloWorldServiceProto";
option java_multiple_files = true;
//服务端接口类
service Greeter {
//服务端接口方法
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
//请求参数
message HelloRequest {
string name = 1;
string sex = 2;
}
//响应参数
message HelloReply {
string message = 1;
}
服务端文件 HelloWorldServer.java
package com.lenny;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Logger;
public class HelloWorldServer {
private static final Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
/* The port on which the server should run */
private int port = 50051;
private Server server;
public static void main(String[] args) throws IOException, InterruptedException {
final HelloWorldServer server=new HelloWorldServer();
server.start();
server.blockUntilShutDown();
}
private void start() throws IOException, InterruptedException {
final Server server = ServerBuilder.forPort(port)
.addService(GreeterGrpc.bindService(new GreeterImpl()))
.build()
.start();
logger.info("Server started,listening on"+port);
Thread.sleep(5000);
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run(){
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
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();
}
}
private void blockUntilShutDown() throws InterruptedException {
if (server!=null){
server.awaitTermination();
}
}
private class GreeterImpl implements GreeterGrpc.Greeter{
public AtomicInteger count = new AtomicInteger(0);
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
System.out.println("call SayHello");
HelloReply reply = HelloReply.newBuilder().setMessage("Hello" + request.getName() + request.getSex()).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
System.out.println(count.incrementAndGet()+Thread.currentThread().getName());
}
}
}
客户端文件 HelloWorldClient.java
package com.lenny;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HelloWorldClient {
private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
private final ManagedChannel channel;
// On the client side, the client has a local object known as stub
// stub是client端本地的对象
private final GreeterGrpc.GreeterBlockingStub blockingStub;
public HelloWorldClient(String host,int port){
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext(true)
.build();
blockingStub= GreeterGrpc.newBlockingStub(channel);
}
/**
* Greet server. If provided, the first element of {@code args} is the name to use in the
* greeting.
*/
public static void main(String[] args) throws InterruptedException {
HelloWorldClient client = new HelloWorldClient("localhost",50051);
try {
String user="world";
if (args.length>0){
user=args[0];
}
client.greet(user);
}finally {
client.shutdown();
}
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
/** Say hello to server. */
public void greet(String name){
logger.info("Will try to greet "+name+"..." );
final HelloRequest request = HelloRequest.newBuilder().setName(name).setSex("女").build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
}catch (StatusRuntimeException e){
logger.log(Level.WARNING,"RPC failed:{0}",e.getStatus());
return;
}
logger.info("Greeting "+ response.getMessage());
}
}