GRPC是google开源的一个高性能、跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x +。
对于开发者而言:
1)需要使用protobuf定义接口,即.proto文件
2)然后使用compile工具生成特定语言的执行代码,比如JAVA、C/C++、Python等。类似于thrift,为了解决跨语言问题。
3)启动一个Server端,server端通过侦听指定的port,来等待Client链接请求,通常使用Netty来构建,GRPC内置了Netty的支持。
4)启动一个或者多个Client端,Client也是基于Netty,Client通过与Server建立TCP常链接,并发送请求;Request与Response均被封装成HTTP2的stream Frame,通过Netty Channel进行交互。
Protocol Buffers是一个跨语言、跨平台的具有可扩展机制的序列化数据工具。也就是说,我在ubuntu下用python语言序列化一个对象,并使用http协议传输到使用java语言的android客户端,java使用对用的代码工具进行反序列化,也可以得到对应的对象。听起来好像跟json没有多大区别。。。其实区别挺多的。
Google说protobuf是smaller,faster,simpler,我们使用google规定的proto协议定义语言,之后使用proto的工具对代码进行“编译”,生成对应的各个平台的源代码,我们可以使用这些源代码进行工作。
Proto2与proto3:
Proto2和proto3有些区别,包括proto语言的规范,以及生成的代码,proto3更好用,更简便,所以我们直接存proto3开始。
a.使用proto3生成java文件(相关依赖)
<properties>
<jackson.version>2.8.3</jackson.version>
<grpc.version>1.6.1</grpc.version>
<os.plugin.version>1.5.0.Final</os.plugin.version>
<protobuf.plugin.version>0.5.0</protobuf.plugin.version>
<protoc.version>3.3.0</protoc.version>
<grpc.netty.version>4.1.14.Final</grpc.netty.version>
</properties>
<dependencies>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>${grpc.version}</version>
</dependency>
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-common</artifactId>
<version>${grpc.netty.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os.plugin.version}</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf.plugin.version}</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
b.编写proto3文件
syntax = "proto3";//版本
option java_multiple_files = true;
option java_package = "com.aiccms.device.grpc.lib";
option java_outer_classname = "DeviceFixProto";
option objc_class_prefix = "HLW";
package device;
// The device service definition.
service DeviceFixService {
// Sends a message
rpc insertDeviceFix (deviceFix) returns (booleanReply){}
rpc updateDeviceFix (deviceFix) returns (booleanReply){}
rpc searchDeviceFix (conditionsRequest) returns (deviceFix){}
rpc deleteDeviceFix (conditionsRequest) returns (booleanReply){}
}
// The request message .
message conditionsRequest {
string id = 1;
}
message deviceFix {
string id=1;
string serialNum=2;
string userNum=3;
int32 status=4;
int32 type=5;
string address=6;
string createtime=7;
string updatetime=8;
}
// The response message
message booleanReply {
bool reply = 1;
}
// The response message
message objectReply {
bool reply = 1;
}
c.使用mvn命令 protobuf:compile 和protobuf:compile-custom命令编译生成java文件!
生成之后的文件在target目录中
注意:proto目录与java目录同级,以上
内容都应放到公共模块,因为这些类不管是客户端和服务端都要使用。
d.编写grpc服务端,首先添加maven依赖
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-server-spring-boot-starter</artifactId>
<version>1.3.0-RELEASE</version>
</dependency>
e.服务端代码
@Slf4j
@GrpcService(DeviceFixServiceGrpc.class)
public class deviceGrpcService extends DeviceFixServiceGrpc.DeviceFixServiceImplBase{
@Autowired
private IDevicesFixService deviceService;
@Override
public void insertDeviceFix(deviceFix request, StreamObserver responseObserver) {
DevicesFix deviceFix = DevicesFix.builder().id(request.getId())
.serialNum(request.getSerialNum())
.address(request.getAddress())
.createtime(DateUtil.toDate(request.getCreatetime(), DatePattern.TIMESTAMP))
.updatetime(DateUtil.toDate(request.getUpdatetime(), DatePattern.TIMESTAMP))
.userNum(request.getUserNum())
.status(request.getStatus())
.type(request.getType())
.build();
log.info(deviceFix.toString());
boolean replyTag = deviceService.insert(deviceFix);
booleanReply reply = booleanReply.newBuilder().setReply(replyTag).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
f.在配置文件中添加配置信息
#grpc server config
spring.application.name: grpc-server
grpc.server.port:7052
g.编写客户端代码:引入maven依赖
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-client-spring-boot-starter</artifactId>
<version>1.3.0-RELEASE</version>
</dependency>
h.编写gprc接口实现,注解@grpcClient 填写grpc接口名称
@Service
@Slf4j
public class DeviceGrpcService {
@GrpcClient("device-grpc-server")
private Channel serverChannel;
public String insertDeviceFix( ){
DeviceFixServiceGrpc.DeviceFixServiceBlockingStub stub = DeviceFixServiceGrpc.newBlockingStub(serverChannel);
booleanReply response = stub.insertDeviceFix(
deviceFix.newBuilder()
.setId("UUID-O1")
.setSerialNum("AUCCMA-01")
.setAddress("SHENZHEN")
.setCreatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))
.setUpdatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))
.setStatus(1)
.setType(1)
.build());
log.info("grpc消费者收到:--》"+response.getReply());
if(response.getReply()){
return "success";
}else{
return "fail";
}
}
}
i.配置文件中加入接口的服务端地址,grpc.client.[服务器规定的接口名称].post/host
grpc.client.grpc-server.host:127.0.0.1
grpc.client.grpc-server.port:7052
j.接口测试
@RestController
@Api(value = "Testcontroller", description = "测试swagger")
public class Testcontroller {
@Autowired
private DeviceGrpcService deviceGrpcService;
@RequestMapping("/testInsertDeviceFix")
@ApiOperation(value = "test", httpMethod = "GET", notes = "测试grpc插入")
public String printMessage3(@RequestParam(defaultValue = "Hmemb") String name) {
return deviceGrpcService.insertDeviceFix();
}
@RequestMapping("/TEST1")
@ApiOperation(value = "test", httpMethod = "GET", notes = "测试1")
public String printMessage(@RequestParam(defaultValue = "Michael") String name) {
return name;
}
}
然后就ok啦!