proto文件
syntax = "proto3";
option java_multiple_files = true;
//指定该proto文件编译成的java源文件的包名
option java_package = "com.protobuf";
// 表示下面的message编译成的java类文件的名字
option java_outer_classname = "HelloProto";
package Hello;
service HelloService {
rpc hello (HelloRequest) returns (HelloResponse) {}
}
me.
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
server代码
package com.server;
import com.client.HelloServiceImpl;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class GrpcServer {
public static void main(String[] args) {
ServerBuilder serverBuilder = ServerBuilder.forPort(9000);
serverBuilder.addService(new HelloServiceImpl());
Server server = serverBuilder.build();
try {
server.start();
server.awaitTermination();
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
HelloServiceImpl代码
package com.client;
import com.protobuf.HelloRequest;
import com.protobuf.HelloResponse;
import com.protobuf.HelloServiceGrpc;
import io.grpc.stub.StreamObserver;
public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void hello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
String name = request.getName();
//业务处理
System.out.println("name = " + name);
//封装响应
HelloResponse.Builder builder = HelloResponse.newBuilder();
builder.setMessage("hello method invoke ok");
HelloResponse response = builder.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
GrpcClient代码
package com.client;
import com.protobuf.HelloRequest;
import com.protobuf.HelloResponse;
import com.protobuf.HelloServiceGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
public static void main(String[] args) {
//创建通信的通道
ManagedChannel channel = ManagedChannelBuilder.forAddress("127.0.0.1", 9000).usePlaintext().build();
try {
//获取代理对象 stub
HelloServiceGrpc.HelloServiceBlockingStub helloService = HelloServiceGrpc.newBlockingStub(channel);
//完成rpc调用
HelloRequest.Builder builder = HelloRequest.newBuilder();
builder.setName("zhangsan");
HelloRequest build = builder.build();
//进行功能rpc调用,获取相应内容
HelloResponse response = helloService.hello(build);
String result = response.getMessage();
System.out.println("result = " + result);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
channel.shutdown();
}
}
}