当前位置:网站首页>Grpc quick practice
Grpc quick practice
2022-07-02 03:11:00 【Understanding the initial state】
Record Grpc Use , from grpc maven Compile the plug-in to the client server implementation .
proto and Service Definition
src/main/proto/AgentModel.proto
Model definition 2 Entity , Parameter and return value .
syntax = "proto3";
option java_package = "com.jimo.grpc";
message AgentInfo {
string name = 1;
sint32 index = 2;
}
message ReportResponse {
bool ok = 1;
string msg = 2;
}
src/main/proto/AgentService.proto
Define one on the service side report Method .
syntax = "proto3";
option java_package = "com.jimo.grpc";
import "AgentModel.proto";
service Agent {
rpc report(AgentInfo) returns (ReportResponse) {
}
}
compile
Join in maven plug-in unit , Compile at the same time proto Document and grpc.
<extensions>
<extension>
<groupId>kr.motd.maven</groupId>
<artifactId>os-maven-plugin</artifactId>
<version>1.6.2</version>
</extension>
</extensions>
<plugins>
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocArtifact>com.google.protobuf:protoc:${protoc.version}:exe:${os.detected.classifier}
</protocArtifact>
<pluginId>grpc-java</pluginId>
<pluginArtifact>io.grpc:protoc-gen-grpc-java:${grpc.version}:exe:${os.detected.classifier}
</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
If you want to use offline proto Executable files , You can change to a local path :
<plugin>
<groupId>org.xolstice.maven.plugins</groupId>
<artifactId>protobuf-maven-plugin</artifactId>
<version>0.6.1</version>
<configuration>
<protocExecutable>D:\software\protoc.exe</protocExecutable>
<pluginId>grpc-java</pluginId>
<pluginExecutable>D:\software\protoc-gen-grpc-java.exe</pluginExecutable>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
Run on the command line mvn compile Can compile protobuf and grpc Class , The structure is as follows :
└─target
├─generated-sources
│ ├─annotations
│ └─protobuf
│ ├─grpc-java
│ │ └─com
│ │ └─jimo
│ │ └─grpc
│ │ AgentGrpc.java
│ │
│ └─java
│ └─com
│ └─jimo
│ └─grpc
│ AgentModel.java
│ AgentService.java
Server implementation
First implement the processing logic of the service : AgentServiceImpl Inherit GRPC Generated abstract classes .
import com.jimo.grpc.AgentGrpc;
import com.jimo.grpc.AgentModel;
import io.grpc.stub.StreamObserver;
public class AgentServiceImpl extends AgentGrpc.AgentImplBase {
@Override
public void report(AgentModel.AgentInfo request, StreamObserver<AgentModel.ReportResponse> responseObserver) {
AgentModel.ReportResponse response = AgentModel.ReportResponse.newBuilder().setOk(true).setMsg(request.getName()).build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
Then start a service :
public static void main(String[] args) throws IOException, InterruptedException {
Server server = ServerBuilder.forPort(8000)
.addService(new AgentServiceImpl())
.build().start();
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
server.shutdown().awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}));
System.out.println("Listening on 8000...");
server.awaitTermination();
}
Client implementation
Clients generally share one Channel, So it came in . And then through Stub call .
import com.jimo.grpc.AgentGrpc;
import com.jimo.grpc.AgentModel;
import io.grpc.Channel;
public class AgentClient {
private final AgentGrpc.AgentBlockingStub stub;
public AgentClient(Channel channel) {
stub = AgentGrpc.newBlockingStub(channel);
}
public void report() {
AgentModel.ReportResponse res = stub.report(AgentModel.AgentInfo.newBuilder().setName("app01").setIndex(98).build());
System.out.println(" Reply received :" + res);
}
}
Clients share one Channel Creation and invocation of :
public static void main(String[] args) throws InterruptedException {
// channel It's better to create one , Can share , It's thread safe
ManagedChannel channel = ManagedChannelBuilder
.forAddress("localhost", 8000)
// The default is SSL/TLS, Here there is no
.usePlaintext()
.build();
AgentClient agentClient = new AgentClient(channel);
agentClient.report();
agentClient.report();
// channel By default, it will wait for a period of time to close , If you don't use it, you'd better close it in time , Otherwise it will take up TCP Connect
channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
}
More questions
1、 We need to intercept the request , Do some AOP How to deal with things ?—- use ClientInterceptor
2、 On the above client side AgentGrpc.newBlockingStub(channel), There are several more Stub, What's the difference? , How do you use it? ?
3、 How to realize the network and protocol of communication between client and server ? Why is the client Channel It will automatically turn off ?
Bury the pit first .
边栏推荐
- QT implementation interface jump
- 结婚后
- GSE104154_ scRNA-seq_ fibrotic MC_ bleomycin/normalized AM3
- [JSON] gson use and step on the pit
- Remote connection to MySQL under windows and Linux system
- venn圖取交集
- [staff] pitch representation (bass clef | C1 36 note pitch representation | C2 48 note pitch representation | C3 60 note pitch representation)
- 結婚後
- 批量检测url是否存在cdn—高准确率
- SAML2.0 notes (I)
猜你喜欢

JS introduction < 1 >

el-table的render-header用法

Delphi xe10.4 installing alphacontrols15.12

Baohong industry | 6 financial management models at different stages of life

halcon图像矫正

buu_ re_ crackMe
![[staff] the direction of the symbol stem and the connecting line (the symbol stem faces | the symbol stem below the third line faces upward | the symbol stem above the third line faces downward | the](/img/fe/d97b25f702bbc05f941d08147259e0.jpg)
[staff] the direction of the symbol stem and the connecting line (the symbol stem faces | the symbol stem below the third line faces upward | the symbol stem above the third line faces downward | the

Render header usage of El table

Special symbols in SAP ui5 data binding syntax, and detailed explanation of absolute binding and relative binding concepts

A list of job levels and salaries in common Internet companies. Those who have conditions must enter big factories. The salary is really high
随机推荐
数据传输中的成帧
The capacity is upgraded again, and the new 256gb large capacity specification of Lexar rexa 2000x memory card is added
Just a few simple steps - start playing wechat applet
2022-2028 global nano abrasive industry research and trend analysis report
Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market
Baohong industry | four basic knowledge necessary for personal finance
halcon图像矫正
JS <2>
verilog 并行块实现
Pychart creates new projects & loads faster & fonts larger & changes appearance
Common means of modeling: aggregation
[JS reverse series] analysis of a customs publicity platform
Verilog avoid latch
Qualcomm platform wifi-- WPA_ supplicant issue
Mongodb base de données non relationnelle
About DNS
What are the characteristics of common web proxy IP
The video number will not be allowed to be put on the shelves of "0 yuan goods" in the live broadcasting room?
MMSegmentation系列之训练与推理自己的数据集(三)
Redis set command line operation (intersection, union and difference, random reading, etc.)