当前位置:网站首页>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】
边栏推荐
- Arthas use
- [241. Design priority for operation expression]
- Logic is a good thing
- How will the surging tide of digitalization overturn the future?
- How much money do novices prepare to play futures? Is agricultural products OK?
- C语言课程设计题目
- 1.8 new features list
- leetcode 322. Coin Change 零钱兑换(中等)
- Etcd summary mechanism and usage scenarios
- 我们该如何保护自己的密码?
猜你喜欢

Après avoir été licencié pendant trois mois, l'entrevue s'est effondrée et l'état d'esprit a commencé à s'effondrer.

Six years of technology iteration, challenges and exploration of Alibaba's globalization and compliance

Explain IO multiplexing, select, poll, epoll in detail

Several models of IO blocking, non blocking, IO multiplexing, signal driven and asynchronous IO
![[anwangbei 2021] Rev WP](/img/98/ea5c241e2b8f3ae4c76e1c75c9e0d1.png)
[anwangbei 2021] Rev WP

【NLP】预训练模型——GPT1

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

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

After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse

用栈实现队列、用队列实现栈(C语言_leetcode_232+225)
随机推荐
Anti fraud, refusing to gamble, safe payment | there are many online investment scams, so it's impossible to make money like this
el-form-item 正则验证
Dragon lizard community open source coolbpf, BPF program development efficiency increased 100 times
奔涌而来的数字化浪潮,将怎样颠覆未来?
[IOT design. Part I] stm32+ smart cloud aiot+ laboratory security monitoring system
Use lambda function URL + cloudfront to realize S3 image back to source
Spark source code (V) how does dagscheduler taskscheduler cooperate with submitting tasks, and what is the corresponding relationship between application, job, stage, taskset, and task?
C语言基础知识
2022年PMP项目管理考试敏捷知识点(6)
Several models of IO blocking, non blocking, IO multiplexing, signal driven and asynchronous IO
1.8 new features list
开源实习经验分享:openEuler软件包加固测试
【241. 为运算表达式设计优先级】
IO的几种模型 阻塞,非阻塞,io多路复用,信号驱动和异步io
About fossage 2.0 "meta force meta universe system development logic scheme (details)
队列的基本操作(C语言实现)
TexStudio使用教程
SWT/ANR问题--当发送ANR/SWT时候如何打开binder trace(BinderTraces)
After being laid off for three months, the interview ran into a wall everywhere, and the mentality has begun to collapse
Understand the window query function of tdengine in one article