这里案例采用grpc和springboot结合使用的方式,其他框架类似

项目结构分为三部分:grpc、client、server

1、grpc端,这里主要是生成代码

首先,加入maven依赖

<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.12.0</version>
</dependency>

然后,引入build

<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<pluginId>grpc-java</pluginId>
<protocArtifact>com.google.protobuf:protoc:3.0.2:exe:${os.detected.classifier}</protocArtifact>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.2.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>

然后,创建.proto文件,这里采用proto3语法

syntax = "proto3";   // 语法版本

// stub选项
option java_package = "com.shgx.grpc.api";
option java_outer_classname = "RPCDateServiceApi";
option java_multiple_files = true;

// 定义包名
package com.shgx.grpc.api;

// 服务接口定义,服务端和客户端都要遵守该接口进行通信
service RPCDateService {
rpc getDate (RPCDateRequest) returns (RPCDateResponse) {}
}

// 定义消息(请求)
message RPCDateRequest {
string userName = 1;
}

// 定义消息(响应)
message RPCDateResponse {
string serverDate = 1;
}

最后,执行mvn complie命令,idea的快捷方式如下


至此,grpc端的代码已经生成完毕,效果省。

2、server端

首先,添加maven依赖

<dependency>
<groupId>com.tan.rpc</groupId>
<artifactId>grpc</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>

然后,创建RPCDateServiceImpl,这是供调用的模块

public class RPCDateServiceImpl extends RPCDateServiceGrpc.RPCDateServiceImplBase{
@Override
public void getDate(RPCDateRequest request, StreamObserver<RPCDateResponse> responseObserver) {
RPCDateResponse rpcDateResponse = null;
Date now=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("今天是"+"yyyy年MM月dd日 E kk点mm分");
String nowTime = simpleDateFormat.format( now );
try {
rpcDateResponse = RPCDateResponse
.newBuilder()
.setServerDate( "Welcome " + request.getUserName() + ", " + nowTime )
.build();
} catch (Exception e) {
responseObserver.onError(e);
} finally {
responseObserver.onNext( rpcDateResponse );
}
responseObserver.onCompleted();
}
}

最后,创建server的启动方法

public class GRPCServer {
private static final int port = 9999;
public static void main( String[] args ) throws Exception {
Server server = ServerBuilder.
forPort(port)
.addService( new RPCDateServiceImpl() )
.build().start();
System.out.println( "grpc服务端启动成功, 端口=" + port );
server.awaitTermination();
}
}

3、client端

首先,引入maven依赖,这里的依赖同server端,省略。

然后,创建连接的client端

public class GRPCClient {
private static final String host = "127.0.0.1";
private static final int serverPort = 9999;

public static void main( String[] args ) throws Exception {
ManagedChannel managedChannel = ManagedChannelBuilder.forAddress( host, serverPort ).usePlaintext().build();
try {
RPCDateServiceGrpc.RPCDateServiceBlockingStub rpcDateService = RPCDateServiceGrpc.newBlockingStub( managedChannel );
RPCDateRequest rpcDateRequest = RPCDateRequest
.newBuilder()
.setUserName("shgx")
.build();
RPCDateResponse rpcDateResponse = rpcDateService.getDate( rpcDateRequest );
System.out.println( rpcDateResponse.getServerDate() );
} finally {
managedChannel.shutdown();
}
}
}


最后,先开启server的启动方法,然后开启client的连接方法,就会发现client调用了server端的RPCDateServiceImpl模块,并且打印,至此,案例结束。

项目源码已上传到码云,见https://gitee.com/tanweicai/grpc