下载protobuf
(选择适合自己操作系统的)
https://github.com/protocolbuffers/protobuf/releases/latest
在pom
中导入依赖
x
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<protobuf.version>3.19.6</protobuf.version>
<grpc.version>1.55.1</grpc.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>${protobuf.version}</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>${grpc.version}</version>
</dependency>
</dependencies>
使用OS
插件和protobuf
插件(作用:将proto
文件转为Java
代码)
x
<build>
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.4.1.Final</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<pluginId>grpc-java</pluginId>
<protocArtifact>com.google.protobuf:protoc:3.0.2:exe:${os.detected.classifier}</protocArtifact>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.2.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
在src/main
下新建proto
文件message.proto
,内容如下(比较简单)
xxxxxxxxxx
syntax = "proto3";
option java_package = "org.example.grpc";
option java_outer_classname = "RPCDemoService";
option java_multiple_files = true;
package org.example.grpc;
service RPCHelloService {
rpc hello (RPCRequest) returns (RPCResponse) {
}
}
message RPCRequest {
string name = 1;
}
message RPCResponse {
string status = 1;
}
在Maven
插件中选择:
protobuf:compile
protobuf:compile-custom
双击这两项,成功在target
下编译出Java
代码
前往target/generated-sources/protobuf
目录,可以找到
grpc-java 目录
java 目录
将这两个目录的Java
文件都复制到对应的包下即可
重写hello
服务
xxxxxxxxxx
package org.example.grpc.service;
import io.grpc.stub.StreamObserver;
import org.example.grpc.RPCHelloServiceGrpc;
import org.example.grpc.RPCRequest;
import org.example.grpc.RPCResponse;
public class RPCDemoServiceImpl extends RPCHelloServiceGrpc.RPCHelloServiceImplBase {
public void hello(RPCRequest request, StreamObserver<RPCResponse> responseObserver) {
String userName = request.getName();
String data = String.format("你好: %s ", userName);
System.out.println(data);
RPCResponse rpcResponse = RPCResponse
.newBuilder()
.setStatus("ok")
.build();
responseObserver.onNext(rpcResponse);
responseObserver.onCompleted();
}
}
编写GRPC
服务端,在9999
端口启动(为了方便,没有使用TLS)
xxxxxxxxxx
package org.example.grpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.example.grpc.service.RPCDemoServiceImpl;
public class GRPCServer {
private static final int port = 9999;
public static void main(String[] args) throws Exception {
Server server = ServerBuilder.
forPort(port)
.addService(new RPCDemoServiceImpl())
.build().start();
System.out.printf("grpc server start: %d.%n", port);
server.awaitTermination();
}
}
可以先在Java
端写一个客户端测试
xxxxxxxxxx
package org.example.grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GRPCClient {
private static final String host = "127.0.0.1";
private static final int serverPort = 9999;
public static void main(String[] args) {
ManagedChannel managedChannel = ManagedChannelBuilder.forAddress(host, serverPort).usePlaintext().build();
try {
RPCHelloServiceGrpc.RPCHelloServiceBlockingStub rpcService = RPCHelloServiceGrpc.newBlockingStub(managedChannel);
RPCRequest rpcRequest = RPCRequest
.newBuilder()
.setName("4ra1n")
.build();
RPCResponse rpcDateResponse = rpcService.hello(rpcRequest);
System.out.println(rpcDateResponse.getStatus());
} finally {
managedChannel.shutdown();
}
}
}
成功打印
xxxxxxxxxx
rpc server start: 9999.
你好: 4ra1n
在Go
端的proto
文件需要加一行
x
syntax = "proto3";
// ...
option go_package = ".;service";
// ...
下载相关依赖
xxxxxxxxxx
go get google.golang.org/grpc
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
使用protoc.exe
生成go
代码
x
protoc.exe --go_out=. .\message.proto
protoc.exe --go-grpc_out=. .\message.proto
编写go
端的client
(没有采用TLS等加密,直接使用了insecure
)
xxxxxxxxxx
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
pb "grpcdemo/demo/proto"
)
func main() {
c, _ := grpc.Dial("127.0.0.1:9999",
grpc.WithTransportCredentials(insecure.NewCredentials()))
defer func(c *grpc.ClientConn) {
_ = c.Close()
}(c)
client := pb.NewRPCHelloServiceClient(c)
resp, err := client.Hello(context.Background(), &pb.RPCRequest{Name: "4ra1n"})
if err != nil {
fmt.Println(err)
}
fmt.Println(resp.GetStatus())
}
运行后成功打印
xxxxxxxxxx
你好: 4ra1n