欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

gRPC 小记

程序员文章站 2022-05-12 23:09:05
...
  1. 创建一个maven项目demo-grpc 包含三个子模块:
    grpc-common:公共模块定义proto及生成java代码;
    grpc-server:grpc 服务端;
    grpc-client:grpc客户端。
    其中grpc-server、grpc-client 为spring-boot项目
    gRPC 小记
  2. 在grcp-common的pom.xml文件中引入依赖jar,定义proto,生成java代码
    pom.xml:
    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>demo-grpc</artifactId>
            <groupId>com.cherrish</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>grpc-common</artifactId>
    
        <properties>
            <jackson.version>2.9.6</jackson.version>
            <grpc.version>1.14.0</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>
            <netty-common.version>4.1.29.Final</netty-common.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>${netty-common.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>
    
    </project>


    在java同目录下创建proto文件夹,并创建.proto文件
    gRPC 小记
    user.proto:
     

    syntax = "proto3";
    
    option java_multiple_files = true;
    option java_package = "com.cherrish";
    option java_outer_classname = "UserProto";
    option objc_class_prefix = "CHL";
    
    package user;
    
    service UserService{
        rpc addUser (User) returns (BooleanReply){}
        rpc updateUser (User) returns (BooleanReply){}
        rpc removeUser (ConditionsRequest) returns (BooleanReply){}
        rpc findUser (ConditionsRequest) returns (User){}
    }
    
    message ConditionsRequest{
        string id = 1;
    }
    
    message User {
        string id = 1;
        string username = 2;
        string address = 3;
        int32 age = 4;
        int32 sex = 5;
        string createtime = 6;
        string updatetime = 7;
    }
    
    message BooleanReply{
        bool reply = 1;
    }
    
    message ObjectReply{
        bool reply = 1;
    }


    使用maven命令生成java文件:
    mvn protobuf:compile
    mvn protobuf:compile-custom
    gRPC 小记

  3. 编写grpc-server 和 grpc-client代码
    grpc-server 添加maven依赖:

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>demo-grpc</artifactId>
            <groupId>com.cherrish</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>grpc-server</artifactId>
    
        <properties>
            <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version>
        </properties>
        <dependencies>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>net.devh</groupId>
                <artifactId>grpc-server-spring-boot-starter</artifactId>
                <version>2.0.1.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>com.cherrish</groupId>
                <artifactId>grpc-common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
        </dependencies>
    </project>

    grpc-server端代码:

    /*********************************UserGrpcService.java*****************************************/
    package com.cherrish;
    
    import io.grpc.stub.StreamObserver;
    import net.devh.springboot.autoconfigure.grpc.server.GrpcService;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    /**
     * @author cherrish
     * @time 2018-09-03 15:55
     * @name UserGrpcService
     * @desc:
     */
    @GrpcService(UserServiceGrpc.class)
    public class UserGrpcService extends UserServiceGrpc.UserServiceImplBase {
    
        private Logger logger = LoggerFactory.getLogger(UserGrpcService.class);
    
        @Override
        public void addUser(User request, StreamObserver<BooleanReply> responseObserver) {
            logger.info("User={id={}, username={}, address={}, age={}, sex={}, createtime={}, updatetime={}}",
                    request.getId(), request.getUsername(), request.getAddress(), request.getAge(), request.getSex(), request.getCreatetime(), request.getUpdatetime());
    
            //TODO 可以自定义实现
            BooleanReply replay = BooleanReply.newBuilder().setReply(true).build();
            responseObserver.onNext(replay);
            responseObserver.onCompleted();
        }
    }
    /*********************************GrpcServerApp.java*****************************************/
    package com.cherrish;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author cherrish
     * @time 2018-09-04 10:16
     * @name GrpcServerApp
     * @desc:
     */
    @SpringBootApplication
    public class GrpcServerApp {
        public static void main(String[] args) {
            SpringApplication.run(GrpcServerApp.class, args);
        }
    }
    

    grpc-server.properties

    spring.application.name=grpc-server
    server.port=8080
    grpc.server.port=7070

    ################################
    grpc-client 添加maven依赖:
     

    <?xml version="1.0" encoding="UTF-8"?>
    <project xmlns="http://maven.apache.org/POM/4.0.0"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <parent>
            <artifactId>demo-grpc</artifactId>
            <groupId>com.cherrish</groupId>
            <version>1.0-SNAPSHOT</version>
        </parent>
        <modelVersion>4.0.0</modelVersion>
    
        <artifactId>grpc-client</artifactId>
    
    
    
        <properties>
            <grpc.stater.version>1.3.0-RELEASE</grpc.stater.version>
        </properties>
        <dependencies>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
    
            <dependency>
                <groupId>net.devh</groupId>
                <artifactId>grpc-client-spring-boot-starter</artifactId>
                <version>2.0.1.RELEASE</version>
            </dependency>
    
            <dependency>
                <groupId>com.cherrish</groupId>
                <artifactId>grpc-common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
    
        </dependencies>
    </project>

    grpc-client端代码:
     

    /***************************UserGrpcService.java**********************************/
    package com.cherrish;
    
    import io.grpc.Channel;
    import net.devh.springboot.autoconfigure.grpc.client.GrpcClient;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    
    /**
     * @author cherrish
     * @time 2018-09-03 17:10
     * @name UserGrpcService
     * @desc:
     */
    @Service
    public class UserGrpcService {
        private Logger logger = LoggerFactory.getLogger(UserGrpcService.class);
        @GrpcClient("user-grpc-server")//名称须在配置文件中注明
        private Channel serverChannel;
    
        public String addUser( ){
            UserServiceGrpc.UserServiceBlockingStub stub = UserServiceGrpc.newBlockingStub(serverChannel);
            BooleanReply response = stub.addUser(
                    User.newBuilder()
                            .setId("10001")
                            .setUsername("grpc-test-user")
                            .setAddress("SHENZHEN")
                            .setAge(18)
                            .setSex(1)
                            .setCreatetime(System.currentTimeMillis() + "")
                            .setUpdatetime(System.currentTimeMillis() + "")
                            .build());
            logger.info("grpc-client received: ---> "+response.getReply());
            if(response.getReply()){
                return "success";
            }else{
                return "fail";
            }
        }
    }
    
    /***************************TestController.java**********************************/
    package com.cherrish;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    /**
     * @author cherrish
     * @time 2018-09-04 10:12
     * @name TestController
     * @desc:
     */
    @RestController
    public class TestController {
        @Autowired
        private UserGrpcService userGrpcService;
    
        @GetMapping(value = "/add")
        public String add(){
            return userGrpcService.addUser();
        }
    
        @GetMapping(value = "/test")
        public String test(String name){
            return name;
        }
    }
    
    
    /***************************GrpcClientApp.java**********************************/
    package com.cherrish;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author cherrish
     * @time 2018-09-04 10:17
     * @name GrpcClientApp
     * @desc:
     */
    @SpringBootApplication
    public class GrpcClientApp {
        public static void main(String[] args) {
            SpringApplication.run(GrpcClientApp.class, args);
        }
    }
    

    grpc-client application.properties
     

    spring.application.name=grpc-client
    
    server.port=8081
    
    grpc.client.user-grpc-server.host=127.0.0.1
    grpc.client.user-grpc-server.port=7070

     

  4. 测试 

转载于:https://my.oschina.net/u/574036/blog/1942113