Welcome to my GitHub


Content: all the original article classification summary and supporting source code, involving Java, Docker, Kubernetes, DevOps and so on;

About the Java version of GRPC in action series

  • “Java version GRPC actual combat” is Xin Chen’s original GRPC development notes for Java programmers, and readers together through actual combat to learn to master GRPC each knowledge points;

“Java version of GRPC combat” full series of links

  1. Generate code with proto
  2. Service publication and invocation
  3. The service side flow
  4. Client stream
  5. Two-way flow
  6. The client gets the server address dynamically
  7. Eureka-based registration discovery

About gRPC

  1. GRPC is a high-performance, open source, and versatile RPC framework designed for mobile and HTTP/2. Available in C, Java and Go languages: GRPC, GRPC-Java, GRPC-Go. The C version supports C, C++, Node.js, Python, Ruby, Objective-C, PHP and C# support.
  2. GRPC is designed based on the HTTP/2 standard and brings features such as two-way streaming, flow control, header compression, and multiplexing requests over a single TCP connection. These features allow it to perform better on mobile devices, save power and space.
  3. Each process can call each other through GRPC, as shown in the figure below:

The core technology

  • To publish GRPC services in Java, I use the open source library net.devh:grpc-server-spring-boot-starter
  • net.devh:grpc-client-spring-boot-starter when calling other GRPC services
  • Thanks to the author of the open source library, Michael a great god, and your wisdom simplifies Java programmer gRPC development work, the project address: https://github.com/yidongnan/…

This paper gives an overview of

As the beginning of this series, here’s what I’m going to do:

  1. Clear dependencies on libraries and development environments
  2. GRPC-Tutorials > will be the tutorials for all the source code of the GRPC series
  3. Actual use proto file automatic generation of Java code

Clear dependencies on libraries and development environments

The dependency libraries and development environments covered throughout the series are as follows:

  1. The JDK: 1.8.0 comes with _281
  2. Gradle: 6.7.1
  3. Springboot: 2.3.8. RELEASE
  4. GRPC: 1.35.0
  5. Protobuf: 3.14.0
  6. GRPC – server – spring – the boot – starter: 2.11.0. RELEASE
  7. GRPC – the client – spring – the boot – starter: 2.11.0. RELEASE
  8. Operating system: Win10 Pro
  9. IDEA: 2021.1 (Ultimate Edition)

Download the source code

  • This may be downloaded in making to combat the full source code, address and link information shown in the following table (https://github.com/zq2599/blo… :
The name of the link note
Project home page https://github.com/zq2599/blo… The project’s home page on GitHub
Git repository address (HTTPS) https://github.com/zq2599/blo… The project source warehouse address, HTTPS protocol
Git repository address (SSH) mailto:[email protected]:zq2599/blog_demos.git The project source warehouse address, SSH protocol
  • “grpc-tutorials”

Create “Java version of GRPC combat” series of father project

  • Create a new gradle project with the name GRPC – Tutorials > and complete the library and its versions with the following contents:
import java.time.OffsetDateTime import java.time.format.DateTimeFormatter buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/'} / / if you have private servers in this configuration, If not, please comment out maven {url ''} / / ali cloud maven {url 'http://maven.aliyun.com/nexus/content/groups/public/'} mavenCentral ext ()} {/ / project version projectVersion = '1.0 - the SNAPSHOT' / / rely on library version grpcSpringBootStarterVersion = '2.11.0. RELEASE' / / GRPC version of https://github.com/grpc/grpc-java/releases GrpcVersion = '1.35.0 / / https://github.com/protocolbuffers/protobuf/releases protobufVersion protobuf version =' 3.14.0 '/ / Protobuf gradle plug-in version protobufGradlePluginVersion = '0.8.12 / / sprignboot version https://github.com/spring-projects/spring-boot/releases springBootVersion = '2.3.8. RELEASE / / springcloud version https://github.com/spring-cloud/spring-cloud-release/releases springCloudVersion = 'Hoxton. SR9 / / nacos version https://github.com/alibaba/spring-cloud-alibaba/releases springCloudAlibabaNacosVersion = '2.2.3. RELEASE / / security version https://github.com/spring-projects/spring-security-oauth/releases springSecurityOAuthVersion = '2.5.0. RELEASE'}} plugins { id 'java' id 'java-library' id 'org.springframework.boot' version "${springBootVersion}" apply false id 'IO. Spring. Dependency - Management' version '1.0.11. Release 'id 'net.nemerosa.versioning' version '2.14.0' id 'com.google.protobuf' version '0.8.14' id 'IO. Franzbecker. gradle-lombok' version '4.0.0' apply false id 'com.github. Ben-manes.versions' version '0.36.0' // Gradle dependencyUpdates} // If you attempt to build without the '-- Scan' parameter in 'gradle 6.0+' it will cause a build error that it can't find. This avoids that problem. if (hasProperty('buildScan')) { buildScan { termsOfServiceUrl = 'https://gradle.com/terms-of-service' TermSofServiceAgree = 'Yes'}} wrapper {GradLeversion = '6.7.1'} def BuildTimeAndDate = offsetDateTime.now () ext {buildDate = offsetDateTime.now () ext DateTimeFormatter.ISO_LOCAL_DATE.format(buildTimeAndDate) buildTime = DateTimeFormatter.ofPattern('HH:mm:ss.SSSZ').format(buildTimeAndDate) buildRevision = versioning.info.commit } allprojects { apply plugin: 'java' apply plugin: 'idea' apply plugin: 'eclipse' apply plugin: 'io.spring.dependency-management' apply plugin: 'io.franzbecker.gradle-lombok' compileJava { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 options.encoding = 'UTF-8' } compileJava.options*.compilerArgs = [ '-Xlint:all', '-Xlint:-processing' ] // Copy LICENSE tasks.withType(Jar) { from(project.rootDir) { include 'LICENSE' into 'META-INF' } } // Write the contents to MANIFEST.MF jar {MANIFEST {attributes(' create-by ') : "${System.properties['java.version']} (${System.properties['java.vendor']} ${System.properties['java.vm.version']})".toString(), 'Built-By': 'travis', 'Build-Date': buildDate, 'Build-Time': buildTime, 'Built-OS': "${System.properties['os.name']}", 'Build-Revision': buildRevision, 'Specification-Title': project.name, 'Specification-Version': projectVersion, 'Specification-Vendor': 'Will Zhao', 'Implementation-Title': project.name, 'Implementation-Version': projectVersion, 'Implementation-Vendor': 'Will Zhao')} Repositories {Mavencentral () // If not, please comment out maven {url ''} / / ali cloud maven {url 'http://maven.aliyun.com/nexus/content/groups/public/' } jcenter() } buildscript { repositories { maven { url 'https://plugins.gradle.org/m2/' } } } } allprojects { project -> buildscript { dependencyManagement { imports { mavenBom "org.springframework.boot:spring-boot-starter-parent:${springBootVersion}" mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}" mavenBom "com.google.protobuf:protobuf-bom:${protobufVersion}" mavenBom "io.grpc:grpc-bom:${grpcVersion}" mavenBom "Org. Junit: junit - bom: 5.7.0"} dependencies {the dependency 'org. Projectlombok: lombok: 1.16.16' dependency 'org.apache.com mons: the Commons - lang3:3.11 the dependency' Commons - collections: Commons - collections: 3.2.2 'dependency "net.devh:grpc-server-spring-boot-starter:${grpcSpringBootStarterVersion}" dependency "net.devh:grpc-client-spring-boot-starter:${grpcSpringBootStarterVersion}" } } ext { micrometerVersion = dependencyManagement.importedProperties['micrometer.version'] springFrameworkVersion = dependencyManagement.importedProperties['spring-framework.version'] springSecurityVersion = dependencyManagement.importedProperties['spring-security.version'] springCloudCommonsVersion = dependencyManagement.importedProperties['spring-cloud-commons.version'] } } } group = 'com.bolingcavalry' version = projectVersion
  • The parent project for the entire series is complete, and now you can start coding.

Actual use proto file automatic generation of Java code

  • GRPC services can be written in different languages, the key is that the Proto file defining the service can be generated in various languages of code, Java is no exception, the following experience;
  • grpc-lib “Tutorials” You can see that the ProtoBuf plugin is configured and how the generated Java code can be added to the source path by the IDE tool:
// Gradle plugins {id 'com.google.protobuf'} dependencies {implementation 'io.grpc:grpc-netty-shaded' implementation 'io.grpc:grpc-protobuf' implementation 'io.grpc:grpc-stub' if (JavaVersion.current().isJava9Compatible()) { // Workaround for @javax.annotation.Generated // see: https://github.com/grpc/grpc-java/issues/3633 implementation 'jakarta.annotation:jakarta.annotation-api' } } protobuf { Protoc {an artifact = "com. Google. Protobuf: protoc:" ${protobufVersion}} / / here generatedFilesBaseDir = automatically generated code "$ProjectDir/SRC /generated" clean {Delete GeneratedFilesBaseDir} // Generate plugins {GRPC {artifact = Artifact 'io.grpc:protoc-gen-grpc-java'}} generateProtoTasks {all()*.plugins {GRPC {}}}} // For Eclipse, The generated code can be added to the source path with the following script, Eclipse {classpath {file.beforemerged {cp-> def GeneratedGRpcFolder = new org.gradle.plugins.ide.eclipse.model.SourceFolder('src/generated/main/grpc', null); generatedGrpcFolder.entryAttributes['ignore_optional_problems'] = 'true'; cp.entries.add( generatedGrpcFolder ); def generatedJavaFolder = new org.gradle.plugins.ide.eclipse.model.SourceFolder('src/generated/main/java', null); generatedJavaFolder.entryAttributes['ignore_optional_problems'] = 'true'; cp.entries.add( generatedJavaFolder ); }}} // For IDEA, you can add the generated code to the source path with the following script, Idea {module {sourceDirs += file(' SRC /generated/main/ Java ') sourceDirs += file(' SRC /generated/main/ GRPC ') generatedSourceDirs += file('src/generated/main/java') generatedSourceDirs += file('src/generated/main/grpc') } }
  • SRC /main/protohelloworld.proto” Contains an interface with a definition of the interface’s input and return parameters:
syntax = "proto3"; option java_multiple_files = true; / / to generate Java code package option java_package = "com. Bolingcavalry. Grpctutorials. Lib"; option java_outer_classname = "HelloWorldProto"; // RPC SayHello (HelloRequest) Returns (HelloReply) {}} // RPC SayHello (HelloRequest) Returns (HelloReply) {} HelloRequest { string name = 1; } // return the result of the data structure message HelloReply {string message = 1; }
  • Now that the proto file is ready, it’s time to generate the Java code from this file, grpc-tutorials gradle grpc-lib:generateProto, Java code can be generated from the HelloWorld.proto file. Upon successful execution, it will produce the contents of the red box below, which is the Java code:

  • In this article, I’ll talk about how to generate this code, but I’ll leave it to the next article. I’ll just mention that SimpleImplBase is an abstract class in SimpleGRPC that you need to inherit when creating GRPC services. In addition, if you want to remotely call GRPC’s SayHello interface, The SimpleHub class from the SimpleGRPC class is used, and the rest of the HelloReply, HelloRequest, and so on are the data structure definitions for entering and returning arguments.
  • At this point, the Java version of GRPC combat preparation work is completed, according to the Proto file generation of Java code method is also mastered, the next chapter we try to release and call the service;

You are not alone, Xin Chen original all the way

  1. Java series
  2. Spring series
  3. The Docker series
  4. Kubernetes series
  5. Database + middleware series
  6. 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 traveling with you in the JAVA world…