An overview of the
GRPC is Google’s open source general high-performance RPC framework. It supports the use of Protocol Buffers to write Service definitions, supports many languages and platforms, and has a powerful binary serialization tool set. With the article “RPC Framework Practice: Similarly, gRPC can automatically generate Service stubs for the Server and Client. We only need a command to quickly set up the RPC running environment.
The gRPC framework is implemented as follows: The Client invokes the Server’s interface to obtain the Server time through remote RPC, so as to obtain the Server time locally and display it.
Similar to the previous practical steps for RPC framework: Thrift, the following are described.
Note: This article was published on My public account CodeSheep. You can subscribe by holding down or scanning the heart below ↓ ↓ ↓
Develop gRPC – API
-
Start by creating a Maven-based project: GrpcAPI
-
Add GRPC-related dependencies to POM
<dependency> <groupId> IO. GRPC </groupId> <artifactId> GRPC -all</artifactId> <version>1.12.0</version> </dependency>Copy the code
Grpc-all contains many GRPC-related components: GRPC-netty, GRPC-Protobuf, GRPC-Stub, and so on
- Add grPC-related build plug-ins to POM
Two Maven plugins have been added so that they will be needed later to run the Protocol Buffers command, which will automatically generate Stub code:
Protobuf-maven-plugin: Run the Protocol Buffers command and generate the Stub code base
<build> <extensions> <extension> <groupId>kr.motd.maven</groupId> <artifactId>os-maven-plugin</artifactId> <version>1.4.1.Final</version> </extension> </extensions> <plugins> . < the groupId > org. Xolstice. Maven plugins < / groupId > < artifactId > protobuf - maven - plugin < / artifactId > < version > 0.5.0 < / version > < configuration > < pluginId > GRPC - Java < / pluginId > < protocArtifact > com. Google. Protobuf: protoc: 3.0.2: exe:${os.detected.classifier}< / protocArtifact > < pluginArtifact > IO. GRPC: protoc - gen - GRPC - Java: 1.2.0: exe:${os.detected.classifier}</pluginArtifact>
</configuration>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>compile-custom</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
Copy the code
- Prepare. Proto service definition file
Here, the proto file has its own syntax requirements as described in my previous article “RPC Framework Practices: Apache Thrift”.
syntax = "Proto3"; // Stub option java_package ="Com. Hansonwang99. GRPC. API "; Option java_outer_classname = "RPCDateServiceApi"; option java_multiple_files =true; / / define a package name, similar to my article "RPC framework of practice: Apache Thrift" Thrift namespace in the package. Com hansonwang99. GRPC. API. // Service interface definition, Service RPCDateService {RPC getDate (RPCDateRequest) returns (RPCDateResponse) {}} // Define a message (request) message RPCDateRequest { string userName = 1; } // Define message (response) message RPCDateResponse {string serverDate = 1; }Copy the code
- perform
mvn compile
Command to automatically generate code stubs
After compiling the MVN, you can see the Java code Stub generated from the. Proto file in the target/generated-sources directory
The code generation results are shown below
Ok, now that grPC-API is in place, you can write the server side and the client side separately
Develop gRPC server
-
Create a Maven-based project: Server
-
Add GrpcAPI dependency to POM
< the dependency > < groupId > com. Hansonwang99 < / groupId > < artifactId > GrpcAPI < / artifactId > < version > 1.0 - the SNAPSHOT < / version > <scope>compile</scope> </dependency>Copy the code
The next step is crucial
- Realize gRPC service interface
public class RPCDateServiceImpl extends RPCDateServiceGrpc.RPCDateServiceImplBase{
@Override
public void getDate(RPCDateRequest request, StreamObserver<RPCDateResponse> responseObserver) {
RPCDateResponse rpcDateResponse = null;
Date now=new Date();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("Today is"+"Yyyy MM month DD day E Kk point MM"); String nowTime = simpleDateFormat.format( now ); try { rpcDateResponse = RPCDateResponse .newBuilder() .setServerDate( "Welcome " + request.getUserName() + "." + nowTime ) .build(); } catch (Exception e) { responseObserver.onError(e); } finally { responseObserver.onNext( rpcDateResponse ); } responseObserver.onCompleted(); }}Copy the code
The getDate() method overridden here is familiar, as is the Service interface defined in the.proto file above. The logic here is simple: get the current time, concatenate it with the userName field extracted from the request RPCDateRequest, and return it to the caller! Form a closed loop
- Create a gRPC server startup class
public class GRPCServer {
private static final int port = 9999;
public static void main( String[] args ) throws Exception {
Server server = ServerBuilder.
forPort(port)
.addService( new RPCDateServiceImpl() )
.build().start();
System.out.println( "GRPC server started successfully, port ="+ port ); server.awaitTermination(); }}Copy the code
Port custom 9999, that is, listen on this port. You can now run GRPCServer immediately to start the server
Develop gRPC client
-
Create a Maven-based project: Client
-
GrpcAPI dependencies still need to be added to the POM
< the dependency > < groupId > com. Hansonwang99 < / groupId > < artifactId > GrpcAPI < / artifactId > < version > 1.0 - the SNAPSHOT < / version > <scope>compile</scope> </dependency>Copy the code
- Create a gRPC client startup class
Public class GRPCClient {private static final String host = "localhost"; private static final int serverPort = 9999; public static void main( String[] args ) throws Exception { ManagedChannel managedChannel = ManagedChannelBuilder.forAddress( host, serverPort ).usePlaintext().build(); try { RPCDateServiceGrpc.RPCDateServiceBlockingStub rpcDateService = RPCDateServiceGrpc.newBlockingStub( managedChannel ); RPCDateRequest RPCDateRequest = rpcDaterequest.newBuilder ().setUsername (" hansonwang99 ").build(); RPCDateRequest = rpcDaterequest.newBuilder ().setUsername (" hansonwang99 ").build(); RPCDateResponse rpcDateResponse = rpcDateService.getDate( rpcDateRequest ); System.out.println( rpcDateResponse.getServerDate() ); } finally { managedChannel.shutdown(); }}}Copy the code
Start GRPCClient now!
C-s communication experiment
Remember our goal?
RPC performs remote procedure calls. In this case, the client can call the server’s getDate() procedure remotely and fetch the results to the client to display!
Afterword.
This article experiment code in this → need to self
-
The author’s more original articles are here, welcome to watch
-
My Personal Blog
The author has more SpringBt practice articles here:
- Spring Boot application monitoring actual combat
- The SpringBoot application is deployed in an external Tomcat container
- ElasticSearch in SpringBt practice
- A preliminary study on Kotlin+SpringBoot joint programming
- Spring Boot Logging framework practices
- SpringBoot elegant coding: Lombok plus
If you are interested, take some time to read some of the author’s articles on containerization and microservitization:
- Use K8S technology stack to create personal private cloud serial articles
- Nginx server configuration from a detailed configuration list
- Docker container visual monitoring center was built
- Use ELK to build Docker containerized application log center
- RPC framework practice: Apache Thrift
- RPC framework practice: Google gRPC
- Establishment of microservice call chain tracking center
- Docker containers communicate across hosts
- Preliminary study on Docker Swarm cluster
- Several guidelines for writing dockerFiles efficiently