1. 说明
grpc基于protobuf来定义接口。分为server端和client端。其中server端提供接口实现,client通过调用server端接口从而获取期望数据。
2. 公共部分
2.1 添加依赖
net.devh grpc-spring-boot-starter 2.12.0.RELEASE javax.annotation javax.annotation-api
添加插件(注意:如果wagon-provider-api无法自动引入,可以现在依赖中引入,以便于依赖的下载,然后在删除依赖坐标即可)
org.xolstice.maven.plugins protobuf-maven-plugin 0.6.1 com.google.protobuf:protoc:3.17.3:exe:${os.detected.classifier} grpc-java io.grpc:protoc-gen-grpc-java:1.39.0:exe:${os.detected.classifier} ${project.basedir}/src/main/proto ${project.basedir}/src/main/java false compile compile-custom
2.2 添加proto依赖文件
添加目录src/main/proto,并将目录设置为Source Root,然后在目录src/main/proto下添加文件hello.proto,内容如下
syntax = "proto3"; //指定proto版本
package com.server;
// 生成的Java代码的包名
option java_package = "com.grpc.server";
// 请求参数
message HelloReq{
string name = 1;
}
// 返回参数
message HelloResp{
string ret = 1;
}
// rpc service
service HelloService{
// service中需要进行调用的具体方法
rpc hello(HelloReq) returns (HelloResp){}
}2.3 通过protobuf生成Java代码
插件导入成功后,点击下图选中的protobuf:compile和protbuf:compile-custom 依次生成对应的Java代码(也就是接口依赖代码)

ECSHOP仿梦芭莎模板整站源码,适合女性,化妆品等网站商城使用。 安装方法:1. 下载程序后,删除data目录下的install.lock文件。2.访问:域名/install 按照提示进行安装.3.安装完成后,登陆网站后台---还原数据库4.清空缓存5.修改管理员密码.,删除install和demo目录还原数据后,后台信息:用户名:admin密码:www.shopex5.com
3. server端接口具体实现
service代码如下
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.server.service.GrpcService;
@GrpcService
public class HelloService extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void hello(Hello.HelloReq request, StreamObserver responseObserver) {
Hello.HelloResp resp = Hello.HelloResp.newBuilder().setRet("你好-->"+request.getName()).build();
responseObserver.onNext(resp);
responseObserver.onCompleted();
}
} 4 client端接口具体实现
client端测试调用代码如下
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class GrpcTest {
@Autowired
private HelloSerivce helloSerivce;
@Test
public void test1() throws Exception{
helloSerivce.haha("牛哈哈");
}
}









