springboot integrates gprc transfer object

1. Introduction to grpc:

GRPC is a high-performance, cross-language RPC framework open sourced by Google, based on HTTP2 protocol, based on protobuf 3.x, and based on Netty 4.x+. In fact, there is not much difference between GRPC and thrift, avro-rpc, etc. in general principles. In short, GRPC does not have many breakthrough innovations.

    For developers:

    1) You need to use protobuf to define the interface, that is, the .proto file

    2) Then use the compile tool to generate the execution code of a specific language, such as JAVA, C/C++, Python, etc. Similar to thrift, in order to solve cross-language problems.

    3) Start a server side. The server side waits for the Client connection request by listening to the specified port. It is usually built with Netty. GRPC has built-in support for Netty.

    4) Start one or more clients. The client is also based on Netty. The client establishes a TCP constant connection with the server and sends a request; both the request and the response are encapsulated into the stream frame of HTTP2 and interact through the netty channel.

Second, proto3:

 

Protocol Buffers is a cross-language, cross-platform serialization data tool with an extensible mechanism. That is to say, I serialize an object in python language under ubuntu, and transmit it to the android client using java language using http protocol, java uses the code tool to deserialize it, and the corresponding object can also be obtained. It sounds like it's not much different from json. . . Actually there are many differences.

Google says that protobuf is smaller, faster, and simpler. We use the proto protocol definition language specified by Google, and then use the proto tool to "compile" the code to generate the corresponding source code for each platform, and we can use these source codes for work.

 Proto2 and proto3:

There are some differences between Proto2 and proto3, including the specification of the proto language and the generated code. proto3 is easier to use and simpler, so we directly store proto3 to start.

 

三,Grpc Spring Boot Starter

grpc for the Starter packaged by springboot,

Grpc Spring Boot Starter address: https://github.com/yidongnan/grpc-spring-boot-starter

1. Usage:

          a, use proto3 to generate java files:

 

[java] view plain copy

  1. <properties>  
  2.        <jackson.version>2.8.3</jackson.version>  
  3.        <grpc.version>1.6.1</grpc.version>  
  4.        <os.plugin.version>1.5.0.Final</os.plugin.version>  
  5.        <protobuf.plugin.version>0.5.0</protobuf.plugin.version>  
  6.        <protoc.version>3.3.0</protoc.version>  
  7.        <grpc.netty.version>4.1.14.Final</grpc.netty.version>  
  8.  </properties>  
  9.   
  10.  <dependencies>  
  11.   
  12.      <dependency>  
  13.          <groupId>io.grpc</groupId>  
  14.          <artifactId>grpc-netty</artifactId>  
  15.          <version>${grpc.version}</version>  
  16.      </dependency>  
  17.      <dependency>  
  18.          <groupId>io.grpc</groupId>  
  19.          <artifactId>grpc-protobuf</artifactId>  
  20.          <version>${grpc.version}</version>  
  21.      </dependency>  
  22.      <dependency>  
  23.          <groupId>io.grpc</groupId>  
  24.          <artifactId>grpc-stub</artifactId>  
  25.          <version>${grpc.version}</version>  
  26.      </dependency>  
  27.      <dependency>  
  28.          <groupId>io.netty</groupId>  
  29.          <artifactId>netty-common</artifactId>  
  30.          <version>${grpc.netty.version}</version>  
  31.      </dependency>  
  32.   
  33.      <dependency>  
  34.         <groupId>com.fasterxml.jackson.core</groupId>  
  35.         <artifactId>jackson-annotations</artifactId>  
  36.         <version>${jackson.version}</version>  
  37.     </dependency>  
  38.   
  39.   
  40.   
  41.   
  42.      <dependency>  
  43.         <groupId>com.fasterxml.jackson.core</groupId>  
  44.         <artifactId>jackson-core</artifactId>  
  45.         <version>${jackson.version}</version>  
  46.     </dependency>  
  47.   
  48.      <dependency>  
  49.         <groupId>com.fasterxml.jackson.core</groupId>  
  50.         <artifactId>jackson-databind</artifactId>  
  51.         <version>${jackson.version}</version>  
  52.     </dependency>  
  53.  </dependencies>  
  54.   
  55.   
  56.    <build>  
  57.        <extensions>  
  58.            <extension>  
  59.                <groupId>kr.motd.maven</groupId>  
  60.                <artifactId>os-maven-plugin</artifactId>  
  61.                <version>${os.plugin.version}</version>  
  62.            </extension>  
  63.        </extensions>  
  64.        <plugins>  
  65.            <plugin>  
  66.                <groupId>org.xolstice.maven.plugins</groupId>  
  67.                <artifactId>protobuf-maven-plugin</artifactId>  
  68.                <version>${protobuf.plugin.version}</version>  
  69.                <configuration>  
  70.                    <protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}</protocArtifact>  
  71.                    <pluginId>grpc-java</pluginId>  
  72.                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}</pluginArtifact>  
  73.                </configuration>  
  74.                <executions>  
  75.                    <execution>  
  76.                        <goals>  
  77.                            <goal>compile</goal>  
  78.                            <goal>compile-custom</goal>  
  79.                        </goals>  
  80.                    </execution>  
  81.                </executions>  
  82.            </plugin>  
  83.        </plugins>  
  84.    </build>  

Pay attention to the version number, if the package version is inconsistent, there may be a classnotFound error

b, write proto3 files,

[java] view plain copy

  1. syntax = "proto3";  
  2.   
  3. option java_multiple_files = true;  
  4. option java_package = "com.aiccms.device.grpc.lib";  
  5. option java_outer_classname = "DeviceFixProto";  
  6. option objc_class_prefix = "HLW";  
  7.   
  8. package device;  
  9.   
  10. // The device service definition.  
  11. service DeviceFixService {  
  12.     // Sends a message  
  13.     rpc insertDeviceFix (deviceFix) returns (booleanReply){}  
  14.     rpc updateDeviceFix (deviceFix) returns (booleanReply){}  
  15.     rpc searchDeviceFix (conditionsRequest) returns (deviceFix){}  
  16.     rpc deleteDeviceFix (conditionsRequest) returns (booleanReply){}  
  17. }  
  18.   
  19.   
  20. // The request message .  
  21. message conditionsRequest {  
  22.      string id = 1;  
  23. }  
  24. message deviceFix {  
  25.      string id=1;  
  26.      string serialNum=2;  
  27.      string userNum = 3;  
  28.      int32  status=4;  
  29.      int32  type=5;  
  30.      string address=6;  
  31.      string createtime=7;  
  32.      string updatetime=8;  
  33. }  
  34.   
  35. // The response message  
  36. message booleanReply {  
  37.     bool reply = 1;  
  38. }  
  39.   
  40. // The response message  
  41. message objectReply {  
  42.     bool reply = 1;  
  43. }  

  Write a proto3 file, and specify the proto3 version in the syntax at the beginning. Other syntaxes are not described in detail here.

c, use the mvn command protobuf:compile and protobuf:compile-custom to compile and generate java files

The generated files are in the target directory 

Note: The proto directory is at the same level as the java directory

d. All of the above are in a public project, because these classes are used by both the client and the server.

e, write grpc server, first add maven dependencies

[html] view plain copy

  1. <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version>  
  2.   
  3.   
  4. <dependency>  
  5.    <groupId>net.devh</groupId>  
  6.    <artifactId>grpc-server-spring-boot-starter</artifactId>  
  7.    <version>${grpc.stater.version}</version>  
  8. </dependency>  
f, server code

[html] view plain copy

  1. /**  
  2.  * User: hmemb  
  3.  * Email: [email protected]  
  4.  * Date: 2018/1/9  
  5.  */  
  6. @ Slf4j  
  7. @GrpcService(DeviceFixServiceGrpc.class)  
  8. public class deviceGrpcService extends DeviceFixServiceGrpc.DeviceFixServiceImplBase{  
  9.   
  10.     @Autowired  
  11.     private IDevicesFixService deviceService;  
  12.       
  13.     @Override  
  14.     public void insertDeviceFix(deviceFix request, StreamObserver<booleanReply> responseObserver) {  
  15.          DevicesFix deviceFix = DevicesFix.builder().id(request.getId())  
  16.                                                     .serialNum(request.getSerialNum())  
  17.                                                     .address(request.getAddress())  
  18.                                                     .createtime(DateUtil.toDate(request.getCreatetime(), DatePattern.TIMESTAMP))  
  19.                                                     .updatetime(DateUtil.toDate(request.getUpdatetime(), DatePattern.TIMESTAMP))  
  20.                                                     .userNum (request.getUserNum ())  
  21.                                                     .status(request.getStatus())  
  22.                                                     .type(request.getType())  
  23.                                                     .build();  
  24.          log.info(deviceFix.toString());  
  25.          boolean replyTag = deviceService.insert(deviceFix);  
  26.          booleanReply reply = booleanReply.newBuilder().setReply(replyTag).build();  
  27.          responseObserver.onNext(reply);  
  28.          responseObserver.onCompleted();  
  29.     }  

g, add configuration information to the configuration file

 

[html] view plain copy

  1. #grpc server config  
  2. spring.application.name: device-grpc-server  
  3. grpc.server.port:7052  

 

h, write client code: introduce maven dependencies

 

[html] view plain copy

  1. <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version  

 

 

[html] view plain copy

  1. <dependency>  
  2.    <groupId>net.devh</groupId>  
  3.    <artifactId>grpc-client-spring-boot-starter</artifactId>  
  4.    <version>${grpc.stater.version}</version>  
  5. </dependency>  
i, write the gprc interface implementation, annotate @grpcClient and fill in the grpc interface name
 

[java] view plain copy

  1. /** 
  2.  * User: hmemb 
  3.  * Email: [email protected] 
  4.  * Date: 2018/01/19 
  5.  */  
  6. @Service  
  7. @ Slf4j  
  8. public class DeviceGrpcService {  
  9.   
  10.     @GrpcClient("device-grpc-server")  
  11.     private Channel serverChannel;  
  12.   
  13.     public String insertDeviceFix( ){  
  14.         DeviceFixServiceGrpc.DeviceFixServiceBlockingStub stub = DeviceFixServiceGrpc.newBlockingStub(serverChannel);  
  15.         booleanReply response = stub.insertDeviceFix(  
  16.                 deviceFix.newBuilder()  
  17.                                 .setId("UUID-O1")  
  18.                                 .setSerialNum("AUCCMA-01")  
  19.                                 .setAddress("SHENZHEN")  
  20.                                 .setCreatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))  
  21.                                 .setUpdatetime(DateUtil.toString(new Date(), DatePattern.TIMESTAMP))  
  22.                                 .setStatus(1)  
  23.                                 .setType(1)  
  24.                 .build());  
  25.         log.info("grpc consumer received: --""+response.getReply());  
  26.         if (response.getReply ()) {  
  27.         return "success";  
  28.         }else{  
  29.         return "fail";  
  30.         }  
  31.     }  
  32. }  


j, add the server address of the interface to the configuration file, grpc.client.[name of the interface specified by the server].post/host

 
 

[html] view plain copy

  1. grpc.client.device-grpc-server.host:127.0.0.1  
  2. grpc.client.device-grpc-server.port:7052  



k, encapsulated into http rest interface test

 

[java] view plain copy

  1. /** 
  2.  * @Author:Hmemb 
  3.  * @Description: 
  4.  * @Date:Created in 18:24 2018/1/18 
  5.  */  
  6. @RestController  
  7. @Api(value = "Testcontroller", description = "测试swagger")  
  8. public class Testcontroller {  
  9.   
  10.   
  11.     @Autowired  
  12.     private DeviceGrpcService deviceGrpcService;  
  13.   
  14.   
  15.     @RequestMapping("/testInsertDeviceFix")  
  16.     @ApiOperation(value = "test", httpMethod = "GET", notes = "测试grpc插入")  
  17.     public String printMessage3(@RequestParam(defaultValue = "Hmemb") String name) {  
  18.         return deviceGrpcService.insertDeviceFix();  
  19.     }  
  20.     @RequestMapping("/TEST1")  
  21.     @ApiOperation(value = "test", httpMethod = "GET", notes = "测试1")  
  22.     public String printMessage(@RequestParam(defaultValue = "Michael") String name) {  
  23.         return name;  
  24.     }  
  25. }  

 

l, interface test results

 

 

 

 
I only implemented one interface in proto, the same for other interfaces.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324961897&siteId=291194637