springboot整合gprc 传输对象

https://blog.csdn.net/qq_28423433/article/details/79108976

一,grpc简介:

GRPC是google开源的一个高性能、跨语言的RPC框架,基于HTTP2协议,基于protobuf 3.x,基于Netty 4.x +。GRPC与thrift、avro-rpc等其实在总体原理上并没有太大的区别,简而言之GRPC并没有太多突破性的创新。

    对于开发者而言:

    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进行交互。

二,proto3:

Protocol Buffers是一个跨语言、跨平台的具有可扩展机制的序列化数据工具。也就是说,我在ubuntu下用python语言序列化一个对象,并使用http协议传输到使用java语言的android客户端,java使用对用的代码工具进行反序列化,也可以得到对应的对象。听起来好像跟json没有多大区别。。。其实区别挺多的。

Google说protobuf是smaller,faster,simpler,我们使用google规定的proto协议定义语言,之后使用proto的工具对代码进行“编译”,生成对应的各个平台的源代码,我们可以使用这些源代码进行工作。

 Proto2与proto3:

Proto2和proto3有些区别,包括proto语言的规范,以及生成的代码,proto3更好用,更简便,所以我们直接存proto3开始。

三,Grpc Spring Boot Starter

grpc对于springboot封装的Starter,

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

1,用法:

          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>
注意版本号,如果包版本不一致可能会有classnotFound的error
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;
}
  编写proto3文件,开头syntax中要指定为proto3版本。其他语法这里不做详细介绍。
c,使用mvn命令 protobuf:compile 和protobuf:compile-custom命令编译生成java文件

生成之后的文件在target目录中 

注意:proto目录与java目录同级

d,以上这些都在一个公共的工程当中,因为这些类不管是客户端和服务端都要使用。

e,编写grpc服务端,首先添加maven依赖

<grpc.stater.version>1.3.0-RELEASE</grpc.stater.version>
 
 
<dependency>
   <groupId>net.devh</groupId>
   <artifactId>grpc-server-spring-boot-starter</artifactId>
   <version>${grpc.stater.version}</version>
</dependency>
f,服务端代码
/**
 * User: hmemb
 * Email: 949530857@qq.com
 * Date: 2018/1/9
 */
@Slf4j
@GrpcService(DeviceFixServiceGrpc.class)
public class deviceGrpcService extends DeviceFixServiceGrpc.DeviceFixServiceImplBase{
 
    @Autowired
    private IDevicesFixService deviceService;
    
    @Override
    public void insertDeviceFix(deviceFix request, StreamObserver<booleanReply> 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();
    }
g,在配置文件中添加配置信息
#grpc server config
spring.application.name: device-grpc-server
grpc.server.port:7052

h,编写客户端代码:引入maven依赖

<grpc.stater.version>1.3.0-RELEASE</grpc.stater.version
<dependency>
   <groupId>net.devh</groupId>
   <artifactId>grpc-client-spring-boot-starter</artifactId>
   <version>${grpc.stater.version}</version>
</dependency>
i,编写gprc接口实现,注解@grpcClient 填写grpc接口名称
/**
 * User: hmemb
 * Email: 949530857@qq.com
 * Date: 2018/01/19
 */
@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";
        }
    }
}

j,配置文件中加入接口的服务端地址,grpc.client.[服务器规定的接口名称].post/host
grpc.client.device-grpc-server.host:127.0.0.1
grpc.client.device-grpc-server.port:7052


k,封装成http rest接口测试
/**
 * @Author:Hmemb
 * @Description:
 * @Date:Created in 18:24 2018/1/18
 */
@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;
    }
}

l,接口测试结果

我只实现了proto中的一个接口,其他接口同理。
--------------------- 
作者:Carlos_v 
来源:CSDN 
原文:https://blog.csdn.net/qq_28423433/article/details/79108976?utm_source=copy 
版权声明:本文为博主原创文章,转载请附上博文链接!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 在将gRPC整合Spring Boot中时,首先需要创建一个Spring Boot项目作为父工程,并命名为springboot_grpc。然后,您可以使用proto3版本的协议缓冲与gRPC一起使用,这样可以避免与proto2客户端通信时的兼容性问题,并允许您在全系列gRPC支持的语言中使用。gRPC是一个由Google发起的开源远程过程调用系统,基于HTTP/2协议传输,基于protobuf 3.x,并且基于Netty 4.x。它提供了高性能的跨语言RPC框架。在整合gRPC时,您需要设置跨平台序列化和流式数据传输,并确保操作环境满足要求,包括系统、架构、环境和仓库等。您可以使用Ubuntu 18.04作为操作系统,Linux-x86_64作为架构,JDK 8作为环境,并使用Maven和IntelliJ IDEA作为构建工具和开发环境。在环境准备方面,您需要安装Protobuf以支持gRPC的使用。123 #### 引用[.reference_title] - *1* [Springboot整合gRPC](https://blog.csdn.net/weixin_40395050/article/details/96971708)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *2* [springboot整合gprc 传输对象](https://blog.csdn.net/qq_28423433/article/details/79108976)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] - *3* [SpringBoot整合grpc](https://blog.csdn.net/weixin_44504392/article/details/122230502)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值