当前位置:网站首页>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】
边栏推荐
- Chen Yu (Aqua) - Safety - & gt; Cloud Security - & gt; Multicloud security
- 研发效能度量框架解读
- 使用CMD修复和恢复病毒感染文件
- 当主程架构游戏的时候,防止到处调用减少耦合性,怎么开放接口给其他人调用呢?
- GET请求如何传递数组参数
- 队列的基本操作(C语言实现)
- App automation testing Kaiyuan platform appium runner
- 2022 · 让我带你Jetpack架构组件从入门到精通 — Lifecycle
- 【Flask】Flask启程与实现一个基于Flask的最小应用程序
- 洞态在某互联⽹⾦融科技企业的最佳落地实践
猜你喜欢

开源者的自我修养|为 ShardingSphere 贡献了千万行代码的程序员,后来当了 CEO

被裁三個月,面試到處碰壁,心態已經開始崩了

建立自己的网站(21)

【IoT毕设.上】STM32+机智云AIoT+实验室安全监控系统

Admire, Ali female program undercover more than 500 black production groups

This paper introduces an implementation scheme to enhance the favorite transaction code management tool in SAP GUI

Self cultivation of open source programmers who contributed tens of millions of lines of code to shardingsphere and later became CEO

Understand the window query function of tdengine in one article

Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"

04 redis source code data structure dictionary
随机推荐
What class loading mechanisms does the JVM have?
Detailed explanation of leetcode reconstruction binary tree [easy to understand]
【剑指Offer】54. 二叉搜索树的第k大节点
Yan Rong looks at how to formulate a multi cloud strategy in the era of hybrid cloud
Liu Dui (fire line safety) - risk discovery in cloudy environment
Grafana reports an error: error= "failed to send notification to email addresses: [email protected] : 535 Error:
建立自己的网站(21)
2022年PMP项目管理考试敏捷知识点(6)
Spark source code reading outline
Kongsong (Xintong Institute) - cloud security capacity building and trend in the digital era
20个实用的 TypeScript 单行代码汇总
一文读懂TDengine的窗口查询功能
算网融合赋能行业转型,移动云点亮数智未来新路标
Dragon lizard community open source coolbpf, BPF program development efficiency increased 100 times
小程序-小程序图表库(F2图表库)
[安网杯 2021] REV WP
About fossage 2.0 "meta force meta universe system development logic scheme (details)
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
French Data Protection Agency: using Google Analytics or violating gdpr
1.8 new features list