当前位置:网站首页>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 .
边栏推荐
- Batch detect whether there is CDN in URL - high accuracy
- Discussion on related configuration of thread pool
- MongoDB非關系型數據庫
- Just a few simple steps - start playing wechat applet
- ORA-01547、ORA-01194、ORA-01110
- What are the common proxy servers and what are the differences?
- Start a business
- Form custom verification rules
- How to develop digital collections? How to develop your own digital collections
- Framing in data transmission
猜你喜欢
Xiaomi, a young engineer, was just going to make soy sauce
Baohong industry | what misunderstandings should we pay attention to when diversifying investment
2022-2028 global deep sea generator controller industry research and trend analysis report
AcWing 245. Can you answer these questions (line segment tree)
Jointly developed by nailing, the exclusive functions of glory tablet V7 series were officially launched
How to develop digital collections? How to develop your own digital collections
OSPF LSA message parsing (under update)
Remote connection to MySQL under windows and Linux system
Verilog parallel block implementation
Pychart creates new projects & loads faster & fonts larger & changes appearance
随机推荐
[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
Mmsegmentation series training and reasoning their own data set (3)
Principle of computer composition - interview questions for postgraduate entrance examination (review outline, key points and reference)
2022-2028 global aluminum beverage can coating industry research and trend analysis report
Stack - es - official documents - filter search results
Soul app released the annual report on generation Z behavior: nearly 20% of young people love shopping in the vegetable market
QT environment generates dump to solve abnormal crash
Redis cluster
IPhone 6 plus is listed in Apple's "retro products" list
tarjan2
Apple added the first iPad with lightning interface to the list of retro products
The video number will not be allowed to be put on the shelves of "0 yuan goods" in the live broadcasting room?
Ten minutes will take you in-depth understanding of multithreading - multithreaded teamwork: synchronous control
How does proxy IP participate in the direct battle between web crawlers and anti crawlers
Use blocking or non blocking for streamline
GSE104154_scRNA-seq_fibrotic MC_bleomycin/normalized AM3
Remote connection to MySQL under windows and Linux system
ORA-01547、ORA-01194、ORA-01110
Addition without addition, subtraction, multiplication and division (simple difficulty)
Grpc快速实践