java: grpc之客户端stream

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

    <groupId>cn.edu.tju</groupId>
    <artifactId>grpcclientsidestream</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <grpc-version>1.54.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>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.22.2</version>
        </dependency>
    </dependencies>


    <build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.7.1</version>
            </extension>
        </extensions>
        <plugins>
            <plugin>
                <groupId>org.xolstice.maven.plugins</groupId>
                <artifactId>protobuf-maven-plugin</artifactId>
                <version>0.6.1</version>
                <configuration>
                    <protocArtifact>com.google.protobuf:protoc:3.21.7:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.54.0:exe:${os.detected.classifier}</pluginArtifact>
                </configuration>
                <executions>
                    <execution>
                        <goals>
                            <goal>compile</goal>
                            <goal>compile-custom</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>


</project>

二、再src\main\proto目录编写.proto文件

syntax = "proto3";
option java_package = "cn.edu.tju.test";
option java_multiple_files=true;
package cn.edu.tju.test;

message StudentInfo {
  string name =1;
  int32 age =2;
}
message StatisticInfo {
   string name =1;
   int32 age =2;
}

service StatisticService {
rpc getInfo(stream StudentInfo) returns (StatisticInfo){};
}

三、mvn clean install 生成java代码并拷贝到src目录下
四、编写服务端实现

package cn.edu.tju.test;

import io.grpc.stub.StreamObserver;

public class StatisticServiceImpl extends StatisticServiceGrpc.StatisticServiceImplBase {

    @Override
    public StreamObserver<StudentInfo> getInfo(
            StreamObserver<StatisticInfo> responseObserver) {
        return new StreamObserver<StudentInfo>() {
            private int counter =0;
            private String name="";
            @Override
            public void onNext(StudentInfo studentInfo) {
                counter++;
                name+=studentInfo.getName();
            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onCompleted() {
                responseObserver.onNext(StatisticInfo.newBuilder().setAge(counter).setName(name).build());
                responseObserver.onCompleted();

            }
        };
    }
}

五、编写服务器

package cn.edu.tju.test;

import io.grpc.Server;
import io.grpc.ServerBuilder;

public class MyServer {
    public static void main(String[] args) throws Exception {
        Server s = ServerBuilder.forPort(50063)
                .addService(new StatisticServiceImpl())
                .build();
        s.start();
        System.out.println("server started......");
        s.awaitTermination();
    }
}

六、编写客户端

package cn.edu.tju.test;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

import java.util.Iterator;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class MyClient {
    final static CountDownLatch finishLatch = new CountDownLatch(1);

    public static void main(String[] args) throws Exception {
        ManagedChannel managedChannel = ManagedChannelBuilder.forTarget("localhost:50063").usePlaintext()
                .build();


        StatisticServiceGrpc.StatisticServiceStub stub = StatisticServiceGrpc.newStub(managedChannel);

        StreamObserver<StatisticInfo> streamObserver = new StreamObserver<StatisticInfo>() {

            @Override
            public void onNext(StatisticInfo statisticInfo) {
                System.out.println(statisticInfo.getAge());
                System.out.println(statisticInfo.getName());

            }

            @Override
            public void onError(Throwable throwable) {

            }

            @Override
            public void onCompleted() {
                finishLatch.countDown();
                System.out.println("finished......");
            }
        };


        StreamObserver<StudentInfo> requestObserver = stub.getInfo(streamObserver);
        try {

            for (int i = 0; i < 10; ++i) {
                StudentInfo req = StudentInfo.newBuilder().setName("amadeus"+(20+i)).setAge(20+i).build();
                requestObserver.onNext(req);
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        // Mark the end of requests
        requestObserver.onCompleted();

        finishLatch.await(10, TimeUnit.MINUTES);
    }
}

七、运行服务器和客户端
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值