Welcome to my GitHub
Github.com/zq2599/blog…
Content: all original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOPS, etc.;
This paper gives an overview of
- This article is the “Java version of gRPC actual combat” series of the second article, the previous article “with proto generation code” will be the parent project, dependent library version, HelloWorld. Proto corresponding Java code are ready, today’s task is the actual gRPC service development and call, the effect is as follows:
- The specific operation of this article is as follows:
- Develop a Springboot application named local-server to provide gRPC service defined in HelloWorld. Proto;
- Develop a Springboot application named Local-client to invoke the gRPP service provided by the Local-server.
- Verify whether the gRPC service can be invoked normally.
Download the source code
- The full source code for this article can be downloaded at GitHub with the following address and link information (github.com/zq2599/blog…
The name of the | link | note |
---|---|---|
Project home page | Github.com/zq2599/blog… | The project’s home page on GitHub |
Git repository address (HTTPS) | Github.com/zq2599/blog… | The project source warehouse address, HTTPS protocol |
Git repository address (SSH) | [email protected]:zq2599/blog_demos.git | The project source warehouse address, SSH protocol |
- The git project has several folders. The source code for the gRPC Java Series is in the grPC-tutorials folder, as shown in the red box below:
- There are multiple directories under the grPC-tutorials folder. The code for this article is in local-server and local-client, as shown in the red box below:
Develop gRPC server
- The service named Simple provides an interface named SayHello to the outside world. This is our next task. Create a SpringBoot application. This should be used to provide the SayHello interface as a gRPC for other applications to call remotely:
service Simple {
// Interface definition
rpc SayHello (HelloRequest) returns (HelloReply) {
}
}
Copy the code
- There are five steps to develop a common gRPC server application based on the Springboot framework, as shown in the following figure. Next, we will develop it in the sequence of the following figure:
- Is credited with creating a module called local-server in the parent project grpc-turtorials, which is called build.gradle:
// Use the Springboot plugin
plugins {
id 'org.springframework.boot'
}
dependencies {
implementation 'org.projectlombok:lombok'
implementation 'org.springframework.boot:spring-boot-starter'
// As a gRPC service provider, you need this library
implementation 'net.devh:grpc-server-spring-boot-starter'
// a project that relies on automatically generated source code
implementation project(':grpc-lib')}Copy the code
- This is a SpringBoot application with the following configuration file:
spring:
application:
name: local-server
# gRPC configuration, here only need to configure the service port number
grpc:
server:
port: 9898
Copy the code
- Java class loggrPCInterceptor.java. This class will be executed first when a gRPC request comes in. The method name is printed in the log.
package com.bolingcavalry.grpctutorials;
import io.grpc.Metadata;
import io.grpc.ServerCall;
import io.grpc.ServerCallHandler;
import io.grpc.ServerInterceptor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class LogGrpcInterceptor implements ServerInterceptor {
@Override
public <ReqT, RespT> ServerCall.Listener<ReqT> interceptCall(ServerCall
serverCall, Metadata metadata, ServerCallHandler
serverCallHandler)
,>
,> {
log.info(serverCall.getMethodDescriptor().getFullMethodName());
returnserverCallHandler.startCall(serverCall, metadata); }}Copy the code
- In order for the LogGrpcInterceptor to be available when a gRPC request comes in, you need to configure the LogGrpcInterceptor as follows:
package com.bolingcavalry.grpctutorials;
import io.grpc.ServerInterceptor;
import net.devh.boot.grpc.server.interceptor.GrpcGlobalServerInterceptor;
import org.springframework.context.annotation.Configuration;
@Configuration(proxyBeanMethods = false)
public class GlobalInterceptorConfiguration {
@GrpcGlobalServerInterceptor
ServerInterceptor logServerInterceptor(a) {
return newLogGrpcInterceptor(); }}Copy the code
- The application startup class is simple:
package com.bolingcavalry.grpctutorials;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LocalServerApplication {
public static void main(String[] args) { SpringApplication.run(LocalServerApplication.class, args); }}Copy the code
- Next comes the most important service class, where the gRPC service is exposed. The complete code is as follows, with a few caveats mentioned later:
package com.bolingcavalry.grpctutorials;
import com.bolingcavalry.grpctutorials.lib.HelloReply;
import com.bolingcavalry.grpctutorials.lib.SimpleGrpc;
import net.devh.boot.grpc.server.service.GrpcService;
import java.util.Date;
@GrpcService
public class GrpcServerService extends SimpleGrpc.SimpleImplBase {
@Override
public void sayHello(com.bolingcavalry.grpctutorials.lib.HelloRequest request, io.grpc.stub.StreamObserver
responseObserver)
{
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + request.getName() + "," + newDate()).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); }}Copy the code
- There are a few things to note in the above grpcServerService.java:
- SayHello can be exposed as a GRPC service with the grPC-server-spring-boot-starter library.
- SimpleImplBase is automatically generated Java code from Proto in the grPC-lib module.
- After processing the business logic in the sayHello method, call the helloReply. onNext method to fill in the returned content;
- Call the helloReply. onCompleted method to indicate that the gRPC service is complete.
- At this point, gRPC server coding is completed, we then start client development;
Call gRPC
- Torials are credited with creating a module called local-client in the parent project grpc-turtorials, whose build.gradle is described as follows, using spingboot and relying on the grpc-client-spring-boot-starter library:
plugins {
id 'org.springframework.boot'
}
dependencies {
implementation 'org.projectlombok:lombok'
implementation 'org.springframework.boot:spring-boot-starter'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'net.devh:grpc-client-spring-boot-starter'
implementation project(':grpc-lib')}Copy the code
- The application configuration file GRPC – tutorials/local client/SRC/main/resources/application. Yml, pay attention to the value is the GRPC information from the server address, In my case, local-server and local-client are running on the same computer. Please set them according to your own situation:
server:
port: 8080
spring:
application:
name: local-grpc-client
grpc:
client:
The name of the gRPC configuration used by the GrpcClient annotation
local-grpc-server:
# gRPC server address
address: 'static: / / 127.0.0.1:9898'
enableKeepAlive: true
keepAliveWithoutCalls: true
negotiationType: plaintext
Copy the code
– Next create the class shown below, in order of number:
- The first is the LogGrpcInterceptor class, which is similar to the server interceptor class, but implements a different interface: LogGrpcInterceptor
package com.bolingcavalry.grpctutorials;
import io.grpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LogGrpcInterceptor implements ClientInterceptor {
private static final Logger log = LoggerFactory.getLogger(LogGrpcInterceptor.class);
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor
method, CallOptions callOptions, Channel next)
,> {
log.info(method.getFullMethodName());
returnnext.newCall(method, callOptions); }}Copy the code
- In order for the interceptor class to work properly, i.e. to be executed when gRPC requests are made, a new configuration class needs to be added:
package com.bolingcavalry.grpctutorials;
import io.grpc.ClientInterceptor;
import net.devh.boot.grpc.client.interceptor.GrpcGlobalClientInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
@Order(Ordered.LOWEST_PRECEDENCE)
@Configuration(proxyBeanMethods = false)
public class GlobalClientInterceptorConfiguration {
@GrpcGlobalClientInterceptor
ClientInterceptor logClientInterceptor(a) {
return newLogGrpcInterceptor(); }}Copy the code
- Start the class:
package com.bolingcavalry.grpctutorials;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class LocalGrpcClientApplication {
public static void main(String[] args) { SpringApplication.run(LocalGrpcClientApplication.class, args); }}Copy the code
- Next comes the most important service class, GrpcClientService, with several caveats that will be mentioned later:
package com.bolingcavalry.grpctutorials;
import com.bolingcavalry.grpctutorials.lib.HelloReply;
import com.bolingcavalry.grpctutorials.lib.HelloRequest;
import com.bolingcavalry.grpctutorials.lib.SimpleGrpc;
import io.grpc.StatusRuntimeException;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Service;
@Service
public class GrpcClientService {
@GrpcClient("local-grpc-server")
private SimpleGrpc.SimpleBlockingStub simpleStub;
public String sendMessage(final String name) {
try {
final HelloReply response = this.simpleStub.sayHello(HelloRequest.newBuilder().setName(name).build());
return response.getMessage();
} catch (final StatusRuntimeException e) {
return "FAILED with "+ e.getStatus().getCode().name(); }}}Copy the code
- The GrpcClientService class above has a few caveats:
- Register GrpcClientService as a spring plain bean instance with @service;
- The SimpleBlockingStub can be modified with @grpcclient so that a GRPC call can be made from the GRPC-client-spring-boot-starter library. The called server information comes from a configuration named local-grpc-server.
- SimpleBlockingStub comes from the Java code generated from helloWorld.proto in the previous article;
- SimpleBlockingStub. SayHello method can remote call local – server application gRPC service;
- In order to verify the gRPC service call success, adding a web interface, the interface internal calls GrpcClientService. SendMessage, so let’s through the browser can verify whether gRPC service call succeeds the:
package com.bolingcavalry.grpctutorials;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GrpcClientController {
@Autowired
private GrpcClientService grpcClientService;
@RequestMapping("/")
public String printMessage(@RequestParam(defaultValue = "will") String name) {
returngrpcClientService.sendMessage(name); }}Copy the code
- After coding, start both services to verify whether the gRPC service is normal.
Verify the gRPC service
- Local-server and local-client are common Springboot applications that can be started in IDEA. Click the position in the red box below and select Run ‘LocalServerApplication’ from the pop-up menu to start local-server:
- After the local-server is started, the console prompts that gRPC Server has started and is listening to port 9898, as shown in the following figure:
- After the local-client command is executed, enter http://localhost:8080/? Name =Tom, you can see that the content of the response is from the local-server grpcServerservice.java:
- The key node information from the Web server to the gRPC server is as follows:
- You can see the local-server interception log:
- There is also the local-client interception log:
- At this point, the most simple Java version of gRPC service release and call verification, this task is completed, the next article, we will continue to study the Java version of gRPC related technology;
You are not alone, Xinchen original accompany all the way
- Java series
- Spring series
- The Docker series
- Kubernetes series
- Database + middleware series
- The conversation series
Welcome to pay attention to the public number: programmer Xin Chen
Wechat search “programmer Xin Chen”, I am Xin Chen, looking forward to enjoying the Java world with you…
Github.com/zq2599/blog…