Grpc demo java 实现

环境

JDK8 + Maven3.6.3
我的 Grpc-java demo https://github.com/999bug/grpc-java 记得star😊😊

搭建步骤

1、利用代码编译器创建maven 项目

2、添加依赖坐标

 <dependencies>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-netty-shaded</artifactId>
            <version>1.44.0</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-protobuf</artifactId>
            <version>1.44.0</version>
        </dependency>
        <dependency>
            <groupId>io.grpc</groupId>
            <artifactId>grpc-stub</artifactId>
            <version>1.44.0</version>
        </dependency>
        <dependency> <!-- necessary for Java 9+ -->
            <groupId>org.apache.tomcat</groupId>
            <artifactId>annotations-api</artifactId>
            <version>6.0.53</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

3、添加构建grpc proto插件

<build>
        <extensions>
            <extension>
                <groupId>kr.motd.maven</groupId>
                <artifactId>os-maven-plugin</artifactId>
                <version>1.6.2</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.19.2:exe:${os.detected.classifier}</protocArtifact>
                    <pluginId>grpc-java</pluginId>
                    <pluginArtifact>io.grpc:protoc-gen-grpc-java:1.44.0: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>
        </plugins>
    </build>

注意
<protoSourceRoot>src/main/proto</protoSourceRoot>
protoSourceRoot 设置proto文件的位置,不然插件不能正常编译
在这里插入图片描述

4、在protoSourceRoot 设置的文件夹下面创建helloWord.proto 文件,后缀必须为.proto,文件名无所谓

syntax = "proto3";

option java_multiple_files = true;
//指定该proto文件编译成的java源文件的包名
option java_package = "com.ncst.grpc.protobuf";
// 表示下面的message编译成的java类文件的名字
option java_outer_classname = "GrpcHelloProto";

package Hello;
// 使用的时候此类是所有使用类的前缀,定义rpc方法
如HelloGrpc、HelloBlockingStub、HelloResponse、HelloRequest
service Hello {
  rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloResponse {
  string message = 1;
}

5、利用 Maven 插件,构建grpc 源代码

  • 首先运行compile
  • 然后接着运行compile-custom
    在这里插入图片描述

6、构建完成会发现在 target 包中生成如下代码

在这里插入图片描述

7、将protobuf 包移入项目中

在这里插入图片描述

编写server 端代码

1、远程调用方法实现类 HelloServiceImpl

package client.service;

import client.grpc.HelloGrpc;
import client.grpc.protobuf.HelloRequest;
import client.grpc.protobuf.HelloResponse;
import io.grpc.stub.StreamObserver;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class HelloServiceImpl extends HelloGrpc.HelloImplBase {

    @Override
    public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
        HelloResponse helloResponse = HelloResponse.newBuilder()
                .setMessage("我是业主晓丹,我不喜欢保安,我希望每天都说 宝 早安,而不是早 保安!")
                .build();
        responseObserver.onNext(helloResponse);
        responseObserver.onCompleted();
        System.out.println("message from Grpc-client:" + request.getName());
    }
}

2、ServerService

package client.service;

import io.grpc.ServerBuilder;
import java.io.IOException;

/**
 * @author Lsy
 * @date 2022/2/21
 */
public class ServerService {
    private static final int port = 10086;
    private static io.grpc.Server server;

    public static void start() throws IOException, InterruptedException {
        server = ServerBuilder.forPort(port)
                .addService(new HelloServiceImpl())
                // 设置服务器上允许接收的最大邮件大小。如果未调用,则默认为4 MiB,所以要设置此参数
                .maxInboundMessageSize(Integer.MAX_VALUE)
                .build()

                .start();
        System.out.println("server start port: " + port);
        server.awaitTermination();
    }

}

3、Server 端启动类

package client.stater;

import client.service.ServerService;

import java.io.IOException;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class Server {
    public static void main(String[] args) throws IOException, InterruptedException {
        ServerService.start();
    }
}

Client 端

1、BaseService

package client.service;

import client.grpc.HelloGrpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;

import java.util.concurrent.TimeUnit;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public abstract class BaseService {

    protected final ManagedChannel channel;
    protected final HelloGrpc.HelloBlockingStub blockingStub;

    public BaseService(String host, int port) {
        channel = ManagedChannelBuilder
                .forAddress(host, port)
                .usePlaintext()
                // 传输的数据大于4MB时,需要指定此参数
                .maxInboundMessageSize(Integer.MAX_VALUE)
                .build();
        blockingStub = HelloGrpc.newBlockingStub(channel);
    }

    public void shutdown() {
        try {
            channel.awaitTermination(5, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public abstract void sayHello(String str);
}

2、BaseServiceImpl

package client.service;

import client.grpc.protobuf.HelloRequest;
import client.grpc.protobuf.HelloResponse;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class BaseServiceImpl extends BaseService {

    public BaseServiceImpl(String host, int port) {
        super(host, port);
    }

    @Override
    public void sayHello(String str) {
        HelloRequest request = HelloRequest.newBuilder()
                .setName(str)
                .build();
        HelloResponse response;
        response = blockingStub.sayHello(request);
        System.out.println("message from Grpc-server: " + response.getMessage());
        System.out.println();
    }

}

3、Client 启动类

package client.stater;

import client.service.BaseService;
import client.service.BaseServiceImpl;

/**
 * @author Lsy
 * @date 2022/2/18
 */
public class Client {
    public static void main(String[] args) {
        BaseService client = new BaseServiceImpl("127.0.0.1", 10086);
        client.sayHello("我是一名保安,保卫一方平安,爱吃小熊饼干,喜欢业主晓丹");
        client.shutdown();
    }
}

调用结果

Server 端

在这里插入图片描述

Client 端

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值