Spring Cloud is a cloud application development tool based on Spring Boot. It provides a simple development method for configuration management, service discovery, circuit breakers, intelligent routing, micro-agents, control bus, global locks, decision-making campaigns, distributed sessions and cluster state management involved in the development of JVM-based cloud application. Repackaging and shielding complex configurations and implementation principles through Spring Boot style, ultimately leaving developers with a simple, easy to understand, easy to deploy and easy to maintain distributed system development toolkit.
Spring Cloud includes multiple subprojects (for multiple different open source products involved in distributed systems), such as Spring Cloud Config, Spring Cloud Netflix, Spring Cloud CloudFoundry, Spring Cloud AWS, Spring Cloud Security, Spring Cloud Commons, Spring Cloud Zookeeper, Spring Cloud CLI and other projects.
Project address: https://github.com/yuezhongxin/spring-cloud-consul-sample
Implementation of ASP.NET Core 2.0 & Docker & Consul: https://github.com/yuezhongxin/HelloDocker.Sample
The current test site uses ASP.NET Core to combine Conusl and Fabio to build a microservice cluster. Because the communication between each service is based on the HTTP REST protocol, the service implementation can be cross-language. Let's develop a Spring Boot service and then use Spring Cloud Consul to register the service to the existing cluster.
The Java development tool I chose IntelliJ IDEA (MacOS installation tutorial), which is currently used very well (Color Scheme uses the system's Darcula, font size 14), and the Java SDK needs additional download and installation (version 10 I installed).
Because I used IntelliJ IDEA for the first time, I will post the process of creating a project in detail below.
First, create a project (select "Spring Initializr", Spring Boot project), and select Java SDK 10 by default:
Then fill in the basic information of the project (Artifact is "spring-cloud-consul-sample", others are the default):
Note: Maven is a project management and construction tool that contains three key components: the project object model (POM), the dependency management model, the build lifecycle, and the stage.
The difference between Group ID and Artifact ID. If Group ID is regarded as a company, Artifact ID can be regarded as a company department, which is somewhat similar to the relationship between solutions and class libraries in .NET. For example, the Group ID of a Spring Cloud project is org.springframework.cloud , and the Artifact ID of Spring Cloud Consul is spring-cloud-starter-consul-discovery .
The following is the Create Spring Boot project type (select the Web dependencies):
Then fill in the project name and project directory:
Then click "Finish" and it's done.
Like developing an ASP.NET Core application, we need to reference various packages first, and the same is true for Spring Boot projects. Because we use Maven for dependency management, we need to configure the dependencies in pom.xml , and configure them as follows:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> <relativePath/> <!-- lookup parent from repository --></parent><properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version></properties><dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> <scope>compile</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency></dependencies><dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-consul-dependencies</artifactId> <version>2.0.0.M7</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies></dependencyManagement>
The reference spring-cloud-starter-consul-discovery corresponds to Spring Cloud Consul, and the reference spring-boot-starter-actuator is used as a health check (address /actuator/health ). In addition, Actuator also supports project monitoring and management.
Let’s talk about the role of nodes here:
parent : The parent reference configuration will inherit the parent reference configuration.dependencies : The current reference configuration. If the parent reference is configured, the child project will be automatically referenced.dependencyManagement : Of course, reference configuration. If the parent reference is configured, the child project will not be automatically referenced. The child project only needs to be referenced when used, and the version number is not required. Then post the code of SpringCloudConsulSampleApplication.java :
package com.example.springcloudconsulsample;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;import org.springframework.cloud.client.discovery.EnableDiscoveryClient;import org.springframework.cloud.client.discovery.DiscoveryClient;@EnableDiscoveryClient@RestController@SpringBootApplicationpublic class SpringCloudConsulSampleApplication { @Autowired private DiscoveryClient discoveryClient; /** * Get all services*/ @RequestMapping("/services") public Object services() { return discoveryClient.getServices(); } @RequestMapping("/home") public String home() { return "Hello World"; } public static void main(String[] args) { SpringApplication.run(SpringCloudConsulSampleApplication.class, args); }} Add the @EnableDiscoveryClient annotation. When the project starts, the current Spring Boot service will be registered.
When registering a service using ASP.NET Core, the configuration information will be filled in the code (such as service name and port, etc., and of course it can also be in the configuration file), and then the service will be registered using the Consul component (called Consul HTTP REST).
If you register a service with Spring Cloud Consul, you need to add a configuration file (Spring Boot project resource file is in the resources directory).
Add configuration in application.properties :
spring.application.name=spring-boot-service
Then add the application.yml configuration file:
Then add the application.yml configuration file: debug: trueserver: port: 24543spring: cloud: consult: host: 127.0.0.1 port: 8500 discovery: register: true hostname: 10.9.10.215 serviceName: ${spring.application.name} healthCheckPath: /actuator/health healthCheckInterval: 15s tags: urlprefix-/${spring.application.name} instanceId: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}The above configuration needs to be explained in detail:
debug configuration is whether to debug mode, and if packaged and published, it needs to be set to false .server.port configures the port of the Spring Boot service.spring.cloud.consul.host/port configures the address and port of the local Consul (both Server node and Client node can be used). Spring Cloud Consul will call the Consul HTTP REST interface to register the service.spring.cloud.consul.discovery.true configures whether to register a service when starting,spring.cloud.consul.discovery.hostname configures the host address of the Spring Boot service, or it can be configured without the configuration, and the default local address is.spring.cloud.consul.discovery.serviceName configures the service name of Consul registered. The ${spring.application.name} variable is the configuration we added in the application.properties configuration file above.spring.cloud.consul.discovery.healthCheckPath configures the Consul health check address. The Actuator component helps us implement it, so we do not need additional implementation. The address can be seen in the printing information when the service is started.spring.cloud.consul.discovery.healthCheckInterval configures Consul health check frequency, that is, heartbeat frequency.spring.cloud.consul.discovery.tags configures the Tags of the Consul registration service, set to the format of urlprefix-/serviceName , and is automatically registered in the Fabio cluster.spring.cloud.consul.discovery.instanceId configures Consul registration service ID.After the above work is completed, we also need to start Consul and Fabio locally
Then we can directly debug the project using IntelliJ IDEA and press Shift + F9 to debug.
The above mentioned the printing information of Actuator:
2018-03-28 10:09:54.645 INFO 63482 --- [ main] sbaewsWebMvcEndpointHandlerMapping : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-03-28 10:09:54.646 INFO 63482 --- [ main] sbaewsWebMvcEndpointHandlerMapping : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto public java.lang.Object org.springframework.boot.actuate.endpoint.web.servlet.AbstractWebMvcEndpointHandlerMapping$OperationHandler.handle(javax.servlet.http.HttpServletRequest,java.util.Map<java.lang.String, java.lang.String>)
2018-03-28 10:09:54.647 INFO 63482 --- [ main] sbaewsWebMvcEndpointHandlerMapping : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring-boot.actuator.v2+json || application/json]}" onto protected java.util.Map<java.lang.String, java.util.Map<java.lang.String, org.springframework.boot.actuate.endpoint.web.Link>> org.springframework.boot.actuate.endpoint.web.servlet.WebMvcEndpointHandlerMapping.links(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
Or we can use Maven to package the release and start the service with the command. You can use Maven in IntelliJ IDEA to package it, or use the Maven command to package it. Here we use the Maven command to package it.
When we installed IntelliJ IDEA, Maven was automatically installed, but directly hitting mvn -v will find that the command cannot be found, so we need to configure the environment variables.
My own Maven file directory is /Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3 , which can be found in the configuration settings of IntelliJ IDEA, and then we execute the following command:
$ export M2_HOME="/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3" && export PATH=$PATH:$M2_HOME/bin && chmod a+x "/Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3/bin/mvn"
Then check whether the Maven command takes effect:
$ mvn -vApache Maven 3.3.9 (bb52d8502b132ec0a5a3f4c09453c07478323dc5; 2015-11-11T00:41:47+08:00)Maven home: /Applications/IntelliJ IDEA.app/Contents/plugins/maven/lib/maven3Java version: 10, vendor: Oracle CorporationJava home: /Library/Java/JavaVirtualMachines/jdk-10.jdk/Contents/HomeDefault locale: zh_CN_#Hans, platform encoding: UTF-8OS name: "mac os x", version: "10.13.2", arch: "x86_64", family: "mac"
Then we modify debug:false in application.yml and use Maven to package it (switch the directory to pom.xml level):
$ mvn clean package -Dmaven.test.skip=true[INFO] Scanning for projects...[INFO][INFO] -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- spring-cloud-consul-sample ---[INFO] Deleting /Users/xishuai/Documents/Project Files/Test Project/spring-cloud-consul-sample/target[INFO][INFO] --- maven-resources-plugin:3.0.1:resources (default-resources) @ spring-cloud-consul-sample ---[INFO] Using 'UTF-8' encoding to copy filtered resources.[INFO] Copying 2 resources[INFO] Copying 0 resource[INFO][INFO] --- maven-compiler-plugin:3.7.0:compile (default-compile) @ spring-cloud-consul-sample ---[INFO] Changes detected - recompiling the module![INFO] Compiling 1 source file to /Users/xishuai/Documents/Project file/test project/spring-cloud-consul-sample/target/classes[INFO][INFO] --- maven-resources-plugin:3.0.1:testResources (default-testResources) @ spring-cloud-consul-sample ---[INFO] Not copying test resources[INFO][INFO] --- maven-compiler-plugin:3.7.0:testCompile (default-testCompile) @ spring-cloud-consul-sample ---[INFO] Not compiling test sources[INFO][INFO] --- maven-surefire-plugin:2.20.1:test (default-test) @ spring-cloud-consul-sample ---[INFO] Tests are skipped.[INFO][INFO] --- maven-jar-plugin:3.0.2:jar (default-jar) @ spring-cloud-consul-sample ---[INFO] Building jar: /Users/xishuai/Documents/Project files/test projects/spring-cloud-consul-sample/target/spring-cloud-consul-sample-0.0.1-SNAPSHOT.jar[INFO][INFO] --- spring-boot-maven-plugin:2.0.0.RELEASE:repackage (default) @ spring-cloud-consul-sample ---[INFO] ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- BUILD SUCCESS[INFO] --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
The generated jar package will be in the target directory, with the file spring-cloud-consul-sample-0.0.1-SNAPSHOT.jar (format is项目名+ 版本号), and then we can start the service directly:
$ java -jar target/spring-cloud-consul-sample-0.0.1-SNAPSHOT.jar2018-03-28 10:33:31.750 INFO 63875 --- [ main] scaAnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@2b662a77: startup date [Wed Mar 28 10:33:31 CST 2018]; root of context hierarchyWARNING: An illegal reflective access operation has occurredWARNING: Illegal reflective access by org.springframework.cglib.core.ReflectUtils$1 (jar:file:/Users/xishuai/Documents/Project File/Test Project/spring-cloud-consul-sample/target/spring-cloud-consul-sample-0.0.1-SNAPSHOT.jar!/BOOT-INF/lib/spring-core-5.0.4.RELEASE.jar!/) to method java.lang.ClassLoader.defineClass(java.lang.String,byte[],int,int,java.security.ProtectionDomain)WARNING: Please consider reporting this to the maintainers of org.springframework.cglib.core.ReflectUtils$1WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operationsWARNING: All illegal access operations will be denied in a future release2018-03-28 10:33:31.971 INFO 63875 --- [ main] faAutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring2018-03-28 10:33:32.015 INFO 63875 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'configurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$4d45e598] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) . ____ __ _ /// ___'_ __ _ _(_)_ __ __ _ / / / // ( ( )/___ | '_ | '_ | / // // // ___)| |_)| | | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_/__, | / / / / =====================================___/=/_/_/ :: Spring Boot :: (v2.0.0.RELEASE)
Check if the health check is successful:
Check whether Consul service registration is successful:
Check whether the Fabio cluster contains services:
After the service registration is successful, we can manually discover the service, or discover it through the Spring Cloud Ribbon/Feign component, and provide load balancing functions (similar to the Fabio function), and then study it later.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.