当前位置:   article > 正文

Java使用Grpc进行服务端和客户端交互_grpc服务端跟客户端都在后端,怎么实现和页面交互

grpc服务端跟客户端都在后端,怎么实现和页面交互

前言

nacos 2.0以后,客户端服务端交互由HTTP改为GRPC,所以看了下grpc,grpc的简介就不写了,网上一搜都能看到,这里用java写一个grpc的小demo

1 创建一个maven项目

创建一个空的maven项目,名字叫:grpc-java

2 idea安装protobuf插件

protobuf support插件

3 修改pom文件

添加protobuf相关依赖

<?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">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.my</groupId>
    <artifactId>grpc-java</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
        <grpc-version>1.20.0</grpc-version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-core</artifactId>
            <version>${grpc-version}</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</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>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <optional>true</optional>
        </dependency>
    </dependencies>

    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.5.0.Final</version>
            </extension>
        </extensions>

        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.5.0</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.9.1:exe:${os.detected.classifier}</pluginArtifact>
                    <protoSourceRoot>src/main/proto</protoSourceRoot>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.6.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87

4 生成代码

4.1 编写proto文件

syntax = "proto3";

option java_package = "com.my.grpc.protobuf";
option java_multiple_files = false;

/***
service处理类
 */
service BaseService
{
  //返回的data是对象
  rpc method(Request) returns (Response){}

  //返回的data是集合
  rpc listMethod(Request) returns (ListResponse){}
}


//请求类
message Request{
  //请求类型
  string type = 1;
  //参数
  string name = 2;
}

//用户信息
message User{
  int64 id=1;
  string name=2;
  string password=3;
  string address=4;
}


message GirFriend{
  string name=1;
  string age=2;
  string address=3;
}

//返回数据
message Response {
  string code = 1;
  string message = 2;
  bytes data=3;
}

//集合返回数据
message ListResponse {
  string code = 1;
  string message = 2;
  repeated bytes data=3;
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54

4.2 生成实体类

在这里插入图片描述

4.3 生成service

在这里插入图片描述

4.4 将生成代码移动到项目中

生成目录如下,移动到项目中
在这里插入图片描述

5编写代码

5.1 服务端

5.1.1 service类

添加GrpcService类,继承BaseServiceImplBase
重写method与listMethod

public class GrpcService extends  BaseServiceGrpc.BaseServiceImplBase{

    @Override
    public void method(Data.Request request,
                       io.grpc.stub.StreamObserver<Data.Response> responseObserver) {
        Data.Response response=null;
        if(request.getType().equals("user")){
             response=getUser(request);
        }
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    @Override
    public void listMethod(Data.Request request,
                       io.grpc.stub.StreamObserver<Data.ListResponse> responseObserver) {
        Data.ListResponse response=null;
        response=getGirlFriends(request);
        responseObserver.onNext(response);
        responseObserver.onCompleted();
    }

    public Data.Response getUser(Data.Request request){
        if("张三".equals(request.getName())){
            Data.User user= Data.User.newBuilder()
                    .setId(1L)
                    .setName("张三")
                    .setAddress("北京市东城区南竹杆胡同2号银河SOHO")
                    .setPassword("123456")
                    .build();
            return Data.Response.newBuilder()
                    .setCode("200")
                    .setMessage("成功")
                    .setData(user.toByteString())
                    .build();
        }else{
            return Data.Response.newBuilder()
                    .setCode("404")
                    .setMessage("无此用户")
                    .build();
        }
    }

    public Data.ListResponse getGirlFriends(Data.Request request){
        if("张三".equals(request.getName())){
            List<ByteString> list=new ArrayList<>();
            Data.GirFriend girFriend= Data.GirFriend.newBuilder()
                    .setName("迪丽热巴")
                    .setAge("25")
                    .setAddress("新疆维吾尔自治区乌鲁木齐市")
                    .build();
            list.add(girFriend.toByteString());

            girFriend= Data.GirFriend.newBuilder()
                    .setName("杨幂")
                    .setAge("30")
                    .setAddress("北京市宣武区")
                    .build();
            list.add(girFriend.toByteString());

            girFriend= Data.GirFriend.newBuilder()
                    .setName("项思醒")
                    .setAge("24")
                    .setAddress("杭州")
                    .build();

            list.add(girFriend.toByteString());

            Data.ListResponse.Builder builder = Data.ListResponse.newBuilder()
                    .setCode("200")
                    .setMessage("成功");
            for (int i = 0; i < list.size(); i++) {
                builder.addData(list.get(i));
            }
            return builder.build();
        }else{
            return Data.ListResponse.newBuilder()
                    .setCode("404")
                    .setMessage("无此用户")
                    .build();
        }
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83

5.1.2 启动类

public class GrpcServer {

    static CountDownLatch cd=new CountDownLatch(1);
    static Server server;

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("grpc server start .......");
        //绑定端口
        //设置处理服务的类
        server = ServerBuilder.forPort(8901)
                .addService(new GrpcService())
                .build();
        server.start();
        System.out.println("grpc server started .......");
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            //项目被关闭触发
            stop();
            System.out.println("grpc server shutdown .......");
        }));
        cd.await();
    }

    public static void stop(){
        if(server!=null){
            server.shutdownNow();
        }
        cd.countDown();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

5.2 客户端

5.2.1 启动类

public class GrpcClient {
    ManagedChannel channel;
    public BaseServiceGrpc.BaseServiceBlockingStub blockingStub;

    final  ThreadPoolExecutor  grpcExecutor ;

    public GrpcClient() {
        grpcExecutor = new ThreadPoolExecutor(Runtime.getRuntime()
                .availableProcessors() * 8,
                Runtime.getRuntime().availableProcessors() * 8, 10L, TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10000),
                new ThreadFactoryBuilder()
                        .setDaemon(true)
                        .setNameFormat("my-grpc-client-executor-%d")
                        .build());
    }

    public void connectToServer(String serverIp, int serverPort){
        ManagedChannelBuilder<?> o = ManagedChannelBuilder.forAddress(serverIp, serverPort)
                .executor(grpcExecutor)
                .compressorRegistry(CompressorRegistry.getDefaultInstance())
                .decompressorRegistry(DecompressorRegistry.getDefaultInstance())
                .maxInboundMessageSize(10 * 1024 * 1024)
                .keepAliveTime(6 * 60 * 1000, TimeUnit.MILLISECONDS)
                .usePlaintext();
        ManagedChannelBuilder builder = ManagedChannelBuilder.forAddress(serverIp, serverPort).
                maxInboundMessageSize(2147483647).
                usePlaintext();
        this.channel = builder.intercept(new ClientInterceptor[]{}).build();
        blockingStub = BaseServiceGrpc.newBlockingStub(channel);

    }

    public Data.User getUser(String userName) throws InvalidProtocolBufferException {
        Data.Request request= Data.Request.newBuilder()
                .setType("user")
                .setName(userName)
                .build();
        Data.Response response = this.blockingStub.method(request);
        System.out.println(String.format("code:%s,message:%s",response.getCode(),response.getMessage()));
        Data.User user =null;
        if("200".equals(response.getCode())) {
            user = Data.User.parseFrom(response.getData());
            System.out.println(String.format("姓名:%s,地址:%s", user.getName(), user.getAddress()));
        }
        return user;
    }

    public List<Data.GirFriend> getFriends(String userName) throws InvalidProtocolBufferException {
        Data.Request request= Data.Request.newBuilder()
                .setType("friends")
                .setName(userName)
                .build();
        Data.ListResponse listResponse = this.blockingStub.listMethod(request);
        System.out.println(String.format("code:%s,message:%s",listResponse.getCode(),listResponse.getMessage()));
        List<Data.GirFriend> girFriends =new ArrayList<>();
        if("200".equals(listResponse.getCode())) {
            for (ByteString bytes : listResponse.getDataList()) {
                Data.GirFriend girFriend = Data.GirFriend.parseFrom(bytes);
                girFriends.add(girFriend);
            }
        }
        return girFriends;
    }


    public static void main(String[] args) throws InvalidProtocolBufferException {
        GrpcClient grpcClient = new GrpcClient();
        grpcClient.connectToServer("127.0.0.1", 8901);
        Data.User user = grpcClient.getUser("张三");
        List<Data.GirFriend> friends = grpcClient.getFriends("张三");
        for (int i = 0; i <friends.size() ; i++) {
            System.out.println(String.format("第%s个女朋友:%s,住址:%s",i+1, friends.get(i).getName(),friends.get(i).getAddress()));
        }
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77

6 demo下载地址

demo下载地址

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/145947
推荐阅读
相关标签
  

闽ICP备14008679号