go grpc生成server,client
2020-12-02 本文已影响0人
邵红晓
go get -u github.com/golang/protobuf
go get -u github.com/golang/protobuf/protoc-gen-go
Windows64的压缩包
https://github.com/protocolbuffers/protobuf/releases
本人下载最新版本 libprotoc 3.14.0,经过测试和老版本兼容
配置环境变量bin/protoc.exe
生成grpc_service.pb.go文件
protoc --go_out=plugins=grpc:. grpc_service.proto
grpc_service.proto文件
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.jy.grpc";
option java_outer_classname = "RemoteCall";
package com.jy.grpc;
service RemoteCallService {
rpc call (RemoteRequest) returns (RemoteResponse);
}
message RemoteRequest {
string cmdReqStr = 1;
}
message RemoteResponse {
string cmdRespStr = 1;
}
server
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
"net"
pb "xx.com/grpc/service"
)
type server struct{}
func (s *server) Call(ctx context.Context, in *pb.RemoteRequest) (*pb.RemoteResponse, error) {
fmt.Println("request:",in.CmdReqStr)
return &pb.RemoteResponse{CmdRespStr:in.CmdReqStr,}, nil
}
func main() {
// 监听本地的8972端口
listen, err := net.Listen("tcp", ":50051")
if err != nil {
fmt.Printf("failed to listen: %v", err)
return
}
s := grpc.NewServer()// 创建gRPC服务器
pb.RegisterRemoteCallServiceServer(s, &server{}) // 在gRPC服务端注册服务
reflection.Register(s) //在给定的gRPC服务器上注册服务器反射服务
// Serve方法在lis上接受传入连接,为每个连接创建一个ServerTransport和server的goroutine。
// 该goroutine读取gRPC请求,然后调用已注册的处理程序来响应它们。
err = s.Serve(listen)
if err != nil {
fmt.Printf("failed to serve: %v", err)
return
}
}
client
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
pb "xx.com/grpc/service"
)
func main() {
// 连接服务器
conn, err := grpc.Dial(":50051", grpc.WithInsecure())
if err != nil {
fmt.Printf("faild to connect: %v", err)
}
defer conn.Close()
client := pb.NewRemoteCallServiceClient(conn)
// 调用服务端的SayHello
r, err := client.Call(context.Background(), &pb.RemoteRequest{CmdReqStr: "mkdir -p /home/xx/HadoopCommit28/statistics/xx_ana/script/xxtj_job/sys_run"})
if err != nil {
fmt.Printf("could not greet: %v", err)
}
fmt.Printf("Greeting: %s !\n", r.CmdRespStr)
}
java代码生成,利用maven插件生成
pom.xml
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-protobuf</artifactId>
<version>1.23.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-stub</artifactId>
<version>1.23.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-netty-shaded</artifactId>
<version>1.23.1</version>
</dependency>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.1</version>
<configuration>
<!--proto编译器 os.detected.classifier,获取操作系统,这个属性是由
${os.detected.name}-${os.detected.arch}一起得来的-->
<protocArtifact>
com.google.protobuf:protoc:3.7.1:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<!--grpc-java代码生成工具-->
<pluginArtifact>
io.grpc:protoc-gen-grpc-java:1.23.1:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
<!--用于根据.proto 文件生成 protobuf 文件-->
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.5.0.Final</version>
</extension>
</extensions>
将proto文件放入和resources同一级目录
image.png生成代码
image.pngimage.png
拷贝到目标目录
image.png调用 GrpcClient.java
package com.jy.grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* grpc客户端
*/
public class GrpcClient {
private static Logger logger = LoggerFactory.getLogger(GrpcClient.class);
private static ManagedChannel channel;
private static RemoteCallServiceGrpc.RemoteCallServiceBlockingStub blockingStub;
private static String host;
private static Integer port;
static {
host = "localhost";
port = Integer.valueOf("50052");
createManagedChannel();
}
private synchronized static void createManagedChannel(){
if(channel == null ||channel.isShutdown()){
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext(true).build();
}
}
/**
* grpc 调用远程客户端
* @param cmd
*/
public static void grpcCall(String cmd){
if(channel.isShutdown()){
createManagedChannel();
}
blockingStub = RemoteCallServiceGrpc.newBlockingStub(channel);
RemoteRequest request = RemoteRequest.newBuilder().setCmdReqStr(cmd).build();
RemoteResponse response = blockingStub.call(request);
logger.info("grpcCall cmd print:{}",response.getCmdRespStr());
}
public static void main(String[] args) {
grpcCall("echo hello world");
}
}