下载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,内容如下(比较简单)
xxxxxxxxxxsyntax = "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服务
xxxxxxxxxxpackage 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)
xxxxxxxxxxpackage 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端写一个客户端测试
xxxxxxxxxxpackage 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(); } }}
成功打印
xxxxxxxxxxrpc server start: 9999.你好: 4ra1n
在Go端的proto文件需要加一行
x
syntax = "proto3";// ...option go_package = ".;service";// ...
下载相关依赖
xxxxxxxxxxgo get google.golang.org/grpcgo install google.golang.org/protobuf/cmd/protoc-gen-go@latestgo install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
使用protoc.exe生成go代码
x
protoc.exe --go_out=. .\message.protoprotoc.exe --go-grpc_out=. .\message.proto
编写go端的client(没有采用TLS等加密,直接使用了insecure)
xxxxxxxxxxpackage 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