server端创建
创建项目
创建一个基础的spring boot项目
修改pom文件
第三方依赖版本
<properties>
<java.version>1.8</java.version>
<os-maven-plugin.version>1.6.1</os-maven-plugin.version>
<protobuf-maven-plugin.version>0.6.1</protobuf-maven-plugin.version>
<grpc-spring-boot-starter>2.4.0.RELEASE</grpc-spring-boot-starter>
</properties>
导入第三方依赖
<dependencies>
<!--grpc 框架-->
<dependency>
<groupId>net.devh</groupId>
<artifactId>grpc-spring-boot-starter</artifactId>
<version>${grpc-spring-boot-starter}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
更改bulid
<build>
<!--grpc proto文件编译插件-->
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>${os-maven-plugin.version}</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<!--grpc proto文件编译插件-->
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>${protobuf-maven-plugin.version}</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.5.1-1:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.16.1:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
修改配置文件
grpc:
server:
in-process-name: grpc-server
# 修改服务端默认入参最大大小,默认值为4M ,这里修改为20M 20*1024*1024
max-inbound-message-size: 20971520
# grpc 端口号
port: 8989
创建proto
创建proto文件夹
在main文件夹下创建proto文件。
创建.proto文件
syntax = "proto3";
package com.example.grpc;
option java_multiple_files = true;
option java_package = "com.example.grpc.lib";
option java_outer_classname = "HelloWorldProto";
// The greeting service definition.
service MyService {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {
}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
编译
如果出现编译异常问题。有可能是yaml文件编码问题,更改成utf-8编码就可以了。
使用
继承extends MyServiceGrpc.MyServiceImplBase 就可以使用了。 其中Mysercie是你.proto中的service 。
这里需要注意 使用@GrpcService注解,不要使用@Service注解!!!!
/**
* @author dzp
* @date 2022/5/29
*/
@GrpcService
public class MyServiceServerRPC extends MyServiceGrpc.MyServiceImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
HelloReply reply = HelloReply.newBuilder()
.setMessage("Hello ==> " + request.getName())
.build();
//将数据放入到流中
responseObserver.onNext(reply);
//接收流成功完成的通知。
responseObserver.onCompleted();
}
}
验证
启动成功,后面我们搭建grpc client后再进行验证。