当前位置:网站首页>Play with grpc - communication between different programming languages
Play with grpc - communication between different programming languages
2022-07-01 13:56:00 【Barry Yan】
1 brief introduction gRPC How to connect between different languages

2 install Protoc buffer
Download link :https://github.com/protocolbuffers/protobuf/releases
Windows I suggest downloading the executable file directly :
Put it into the specified directory after downloading , Configure environment variables :
verification :
If the following exception occurs :
Solution :
hold protoc.exe copy to C:\Windows\System32
3 Go Use gRPC Conduct Go Communication between programs
Project structure :
Download dependency :
go get google.golang.org/protobuf/runtime/[email protected]
go get google.golang.org/grpc
go get google.golang.org/protobuf
go.mod file :
module grpc_go
go 1.16
require (
google.golang.org/grpc v1.43.0 // indirect
google.golang.org/protobuf v1.26.0 // indirect
)
protoc file :
syntax = "proto3"; // Specify the syntax format
package proto; // Specify the generated package name
option java_package = "org.ymx.proto";
option go_package = "/";
// Definition gRPC Service interface
service HelloService {
// Specific methods of interface
rpc SayHello(HelloRequest) returns (HelloReply) {}
}
// The request parameter type of the interface
message HelloRequest {
string name = 1;
}
// The response parameter type of the interface
message HelloReply {
string message = 1;
}
To proto Compile under directory , After compilation, the specified go file :
C:\Users\17122\Desktop\grpc_demo\grpc_go\protoc> protoc -I . --go_out=plugins=grpc:. hello.proto
If there is an anomaly :
'protoc-gen-go' Not an internal or external command , It's not a runnable program
Or batch files .
--go_out: protoc-gen-go: Plugin failed with status code 1.
Solution :
Download this project , To protoc-gen-go Under the table of contents ,go build -o protoc-gen-go.exe main.go , Generate protoc-gen-go.exe file
then protoc-gen-go.exe copy to C:\Windows\System32
grpc client ,main.go
package main
import (
"context"
"fmt"
"google.golang.org/grpc"
_ "grpc_go/proto"
__ "grpc_go/proto"
"log"
)
func main() {
//1 To configure grpc The port of the server is used as the listening port of the client
conn, err := grpc.Dial(":6666", grpc.WithInsecure())
if err != nil {
log.Fatalf(" Monitoring the server : %v\n", err)
}
defer conn.Close()
//2 Instantiation UserInfoService Client of service
client := __.NewHelloServiceClient(conn)
//3 call grpc service
req := new (__.HelloRequest)
req.Name = "YMX"
resp, err := client.SayHello(context.Background(), req)
if err != nil {
log.Fatalf(" Request error : %v\n", err)
}
fmt.Printf(" Response content : %v\n", resp)
}
grpc Server side ,main.go
import (
"context"
"fmt"
"google.golang.org/grpc"
__ "grpc_go/proto"
"log"
"net"
)
// Define the server Realization Agreed interface
type HelloServiceServer struct{
}
var u = HelloServiceServer{
}
// Realization interface
func (s *HelloServiceServer) SayHello(ctx context.Context, req *__.HelloRequest) (resp *__.HelloReply, err error) {
name := req.Name
if name == "YMX" {
resp = &__.HelloReply{
Message: "Hello YMX"}
} else {
resp = &__.HelloReply{
Message: "Hi NoYMX"}
}
err = nil
return resp, nil
}
// Start the service
func main() {
//1 Add listening port
port := ":6666"
l, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf(" Port listening error : %v\n", err)
}
fmt.Printf(" Monitoring : %s port \n", port)
//2 start-up grpc service
s := grpc.NewServer()
//3 take UserInfoService Service registered to gRPC in , Note that the second parameter is a variable of interface type , You need to take the address to pass the parameter
__.RegisterHelloServiceServer(s, &u)
s.Serve(l)
}
Start the server and client , To test :
4 Java Use gRPC Conduct Java Communication between programs
Project structure :
pom rely on
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.ymx</groupId>
<artifactId>grpc_java</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>io.grpc</groupId>
<artifactId>grpc-all</artifactId>
<version>1.43.0</version>
</dependency>
</dependencies>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<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.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.5.0</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:3.0.0:exe:${os.detected.classifier}</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:1.0.0:exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
protoc The contents of the document :
syntax = "proto3"; // Specify the syntax format
package proto; // Specify the generated package name ;
option java_multiple_files = true;
option java_package = "org.ymx.proto";
option go_package = "/";
option java_outer_classname = "Hello";
option objc_class_prefix = "YMX";
service HelloService {
rpc SayHello(HelloRequest) returns (HelloReply) {}
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
Compile , The first use of protobuf Compile :
And then reuse it maven Compile :
grpc Server code :
package org.ymx;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;
import org.ymx.proto.HelloReply;
import org.ymx.proto.HelloRequest;
import org.ymx.proto.HelloServiceGrpc;
import java.io.IOException;
/** * @desc: grpc Server side * @author: YanMingXin * @create: 2021/12/18-14:52 **/
public class Server {
private final static int port = 5555;
private io.grpc.Server server;
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new HelloServiceImpl())
.build()
.start();
System.out.println("service start...");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
Server.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final Server server = new Server();
server.start();
server.blockUntilShutdown();
}
/** * Realization Define a class that implements the service interface */
private class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
System.out.println("service:" + req.getName());
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
grpc Client code :
package org.ymx;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import org.ymx.proto.HelloReply;
import org.ymx.proto.HelloRequest;
import org.ymx.proto.HelloServiceGrpc;
import java.util.concurrent.TimeUnit;
/** * @desc: grpc client * @author: YanMingXin * @create: 2021/12/18-14:52 **/
public class Client {
private final ManagedChannel channel;
private final HelloServiceGrpc.HelloServiceBlockingStub blockingStub;
public Client(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = HelloServiceGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void hello(String name) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response = blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
public static void main(String[] args) {
Client client = new Client("127.0.0.1", 5555);
for (int i = 0; i < 5; i++) {
if (i < 3) {
client.hello("ZS");
} else {
client.hello("YMX");
}
}
}
}
Start the test :
5 Use gRPC Conduct Go and Java Communication between programs
5.1 Use Java As a server ,Go As a client
Modify the client port :
Java Server code , The rest of the code doesn't change :
/** * @desc: grpc Server side * @author: YanMingXin * @create: 2021/12/18-14:52 **/
public class Server {
private final static int port = 5555;
private io.grpc.Server server;
private void start() throws IOException {
server = ServerBuilder.forPort(port)
.addService(new HelloServiceImpl())
.build()
.start();
System.out.println("service start...");
Runtime.getRuntime().addShutdownHook(new Thread() {
@Override
public void run() {
System.err.println("*** shutting down gRPC server since JVM is shutting down");
Server.this.stop();
System.err.println("*** server shut down");
}
});
}
private void stop() {
if (server != null) {
server.shutdown();
}
}
private void blockUntilShutdown() throws InterruptedException {
if (server != null) {
server.awaitTermination();
}
}
public static void main(String[] args) throws IOException, InterruptedException {
final Server server = new Server();
server.start();
server.blockUntilShutdown();
}
/** * Realization Define a class that implements the service interface */
private class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase {
@Override
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
System.out.println("service:" + req.getName());
HelloReply reply = HelloReply.newBuilder().setMessage(("Hello: " + req.getName())).build();
responseObserver.onNext(reply);
responseObserver.onCompleted();
}
}
}
Go Client code , The rest of the code doesn't change :
import (
"context"
"fmt"
"google.golang.org/grpc"
_ "grpc_go/proto"
__ "grpc_go/proto"
"log"
)
func main() {
//1 To configure grpc The port of the server is used as the listening port of the client
conn, err := grpc.Dial(":5555", grpc.WithInsecure())
if err != nil {
log.Fatalf(" Monitoring the server : %v\n", err)
}
defer conn.Close()
//2 Instantiation UserInfoService Client of service
client := __.NewHelloServiceClient(conn)
//3 call grpc service
req := new (__.HelloRequest)
req.Name = "YMX"
resp, err := client.SayHello(context.Background(), req)
if err != nil {
log.Fatalf(" Request error : %v\n", err)
}
fmt.Printf(" Response content : %v\n", resp)
}
test :
5.2 Use Go As a server ,Java As a client
Modify the client port :
Go Server code , The rest of the code doesn't change :
import (
"context"
"fmt"
"google.golang.org/grpc"
__ "grpc_go/proto"
"log"
"net"
)
// Define the server Realization Agreed interface
type HelloServiceServer struct{
}
var u = HelloServiceServer{
}
// Realization interface
func (s *HelloServiceServer) SayHello(ctx context.Context, req *__.HelloRequest) (resp *__.HelloReply, err error) {
name := req.Name
if name == "YMX" {
resp = &__.HelloReply{
Message: "Hello YMX"}
} else {
resp = &__.HelloReply{
Message: "Hi NoYMX"}
}
err = nil
return resp, nil
}
// Start the service
func main() {
//1 Add listening port
port := ":6666"
l, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf(" Port listening error : %v\n", err)
}
fmt.Printf(" Monitoring : %s port \n", port)
//2 start-up grpc service
s := grpc.NewServer()
//3 take UserInfoService Service registered to gRPC in , Note that the second parameter is a variable of interface type , You need to take the address to pass the parameter
__.RegisterHelloServiceServer(s, &u)
s.Serve(l)
}
Java Client code , The rest of the code doesn't change :
/** * @desc: grpc client * @author: YanMingXin * @create: 2021/12/18-14:52 **/
public class Client {
private final ManagedChannel channel;
private final HelloServiceGrpc.HelloServiceBlockingStub blockingStub;
public Client(String host, int port) {
channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
blockingStub = HelloServiceGrpc.newBlockingStub(channel);
}
public void shutdown() throws InterruptedException {
channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
}
public void hello(String name) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response = blockingStub.sayHello(request);
System.out.println(response.getMessage());
}
public static void main(String[] args) {
Client client = new Client("127.0.0.1", 6666);
for (int i = 0; i < 5; i++) {
if (i < 3) {
client.hello("ZS");
} else {
client.hello("YMX");
}
}
}
}
test :
6 summary
- Deposit protoc Try to use proto name
Source code acquisition method : Pay attention to the official account below. , reply 【0701】
边栏推荐
- ArrayList capacity expansion mechanism and thread safety
- The integration of computing and Internet enables the transformation of the industry, and the mobile cloud lights up a new roadmap for the future of digital intelligence
- Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its
- SWT/ANR问题--当发送ANR/SWT时候如何打开binder trace(BinderTraces)
- 【Flask】Flask启程与实现一个基于Flask的最小应用程序
- Blind box NFT digital collection platform system development (build source code)
- [IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system
- 3.4 《数据库系统概论》之数据查询—SELECT(单表查询、连接查询、嵌套查询、集合查询、多表查询)
- 进入前六!博云在中国云管理软件市场销量排行持续上升
- Basic operation of queue (implemented in C language)
猜你喜欢

逻辑是个好东西

Error:Kotlin: Module was compiled with an incompatible version of Kotlin. The binary version of its
![[anwangbei 2021] Rev WP](/img/98/ea5c241e2b8f3ae4c76e1c75c9e0d1.png)
[anwangbei 2021] Rev WP

【NLP】预训练模型——GPT1

Dragon lizard community open source coolbpf, BPF program development efficiency increased 100 times

刘对(火线安全)-多云环境的风险发现

详细讲解面试的 IO多路复用,select,poll,epoll

Fiori applications are shared through the enhancement of adaptation project

2022. Let me take you from getting started to mastering jetpack architecture components - lifecycle

Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
随机推荐
[IOT design. Part I] stm32+ smart cloud aiot+ laboratory security monitoring system
【 剑指 Offer】55 - I. 二叉树的深度
Collation and review of knowledge points of Microcomputer Principle and interface technology - pure manual
SAP 智能机器人流程自动化(iRPA)解决方案分享
Solution to 0xc000007b error when running the game [easy to understand]
C语言订餐管理系统
基于算力驱动、数据与功能协同的分布式动态(协同)渲染/功能运行时
盲盒NFT数字藏品平台系统开发(搭建源码)
[machine learning] VAE variational self encoder learning notes
陈宇(Aqua)-安全-&gt;云安全-&gt;多云安全
IO的几种模型 阻塞,非阻塞,io多路复用,信号驱动和异步io
App自动化测试开元平台Appium-runner
程序设计的基本概念
清华章毓晋老师新书:2D视觉系统和图像技术(文末送5本)
Several models of IO blocking, non blocking, IO multiplexing, signal driven and asynchronous IO
Go整合Logrus实现日志打印
用命令行 给 apk 签名
进入前六!博云在中国云管理软件市场销量排行持续上升
洞态在某互联⽹⾦融科技企业的最佳落地实践
[IOT completion. Part 2] stm32+ smart cloud aiot+ laboratory security monitoring system