当前位置:网站首页>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 .
边栏推荐
- Yyds dry goods inventory accelerating vacuum in PG
- 3048. Number of words
- Addition without addition, subtraction, multiplication and division (simple difficulty)
- 2022-2028 global aluminum beverage can coating industry research and trend analysis report
- [Chongqing Guangdong education] Sichuan University concise university chemistry · material structure part introductory reference materials
- [staff] restore mark (Introduction to the use of restore mark | example analysis of Metaphone mark and restore mark)
- Verilog 状态机
- How to create an instance of the control defined in SAP ui5 XML view at runtime?
- IPhone 6 plus is listed in Apple's "retro products" list
- Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field
猜你喜欢

Mmsegmentation series training and reasoning their own data set (3)

Après le mariage

JS <2>

Verilog state machine

Cache processing scheme in high concurrency scenario

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

GB/T-2423. XX environmental test documents, including the latest documents

Docker安装canal、mysql进行简单测试与实现redis和mysql缓存一致性

图扑软件通过 CMMI5 级认证!| 国际软件领域高权威高等级认证

2022-2028 global soft capsule manufacturing machine industry research and trend analysis report
随机推荐
V-model of custom component
寻找重复数[抽象二分/快慢指针/二进制枚举]
Tupu software has passed CMMI5 certification| High authority and high-level certification in the international software field
Baohong industry | what misunderstandings should we pay attention to when diversifying investment
命名块 verilog
el-table的render-header用法
Rotating frame target detection mmrotate v0.3.1 learning model
旋转框目标检测mmrotate v0.3.1 学习模型
3124. Word list
Delphi xe10.4 installing alphacontrols15.12
2022 hoisting machinery command examination paper and summary of hoisting machinery command examination
Jointly developed by nailing, the exclusive functions of glory tablet V7 series were officially launched
Mmsegmentation series training and reasoning their own data set (3)
2022-2028 global wood vacuum coating machine industry research and trend analysis report
2022-2028 global encryption software industry research and trend analysis report
Pychart creates new projects & loads faster & fonts larger & changes appearance
【JVM】创建对象的流程详解
The video number will not be allowed to be put on the shelves of "0 yuan goods" in the live broadcasting room?
使用 useDeferredValue 进行异步渲染
verilog 并行块实现