Brief introduction
In micro-service, service registration and discovery play a key role in the management of each sub-service subsystem. As the system expands more and more, and the number of systems split into microservices increases correspondingly, the URL to manage and access these microservices becomes tricky, and if we add a micro-service every new one, manually add its URL address or other communication protocol address to the other place where the microservices are used, This often makes mistakes, and the workload is huge, once the address of a microservices has changed, it is necessary to manually modify all the configuration files that reference its microservices. So Spring-cloud Eureka Server is to solve such problems, and after a simple configuration, you can automatically register and discover MicroServices.
Basic Environment
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
Project Source
Gitee Code Cloud
Building Eureka Server
On the previous blog we introduced how to build Spring-cloud configuration Center, there is a test of the Web client to access it, this time we build a Eureka server on the basis of the previous, and read the configuration center configuration, and then the Web Client registers with the Eureka service as Discovery client. Start by creating a new Maven project under IntelliJ:
- GroupId:cn.zxuqian
- Artifactid:registry
Then add the following code in the Pom.xml:
<?xml version= "1.0" encoding= "UTF-8"? ><project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "http: Www.w3.org/2001/XMLSchema-instance "xsi:schemalocation=" http://maven.apache.org/POM/4.0.0/http Maven.apache.org/xsd/maven-4.0.0.xsd "> <modelVersion>4.0.0</modelVersion> <groupId> Cn.zxuqian</groupid> <artifactId>registry</artifactId> <version>1.0-snapshot</version > <packaging>jar</packaging> <parent> <groupid>org.springframework.boot</groupi D> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.1.release</versi on> <relativePath/> </parent> <properties> <project.build.sourceencoding>ut f-8</project.build.sourceencoding> <java.version>1.8</java.version> </properties> < ;d ependencies> <dependency><groupId>org.springframework.cloud</groupId> <artifactid>spring-cloud-starter-netflix-eureka- server</artifactid> </dependency> <dependency> <groupid>org.springframewo Rk.cloud</groupid> <artifactId>spring-cloud-starter-config</artifactId> </dependenc y> <dependency> <groupId>org.springframework.boot</groupId> <artifact Id>spring-boot-starter-test</artifactid> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactid>spring-cloud-dependencies& Lt;/artifactid> <version>Finchley.M9</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> &L t;build> <plugins> <plugin> <groupid>org.springframework.boot</gr Oupid> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> & lt;/plugins> </build> <repositories> <repository> <id>spring-milestones </id> <name>spring milestones</name> <url>https://repo.spring.io/libs-milest one</url> <snapshots> <enabled>false</enabled> </snapshots > </repository> </repositories></project>
spring-cloud-starter-netflix-eureka-server
This eureka-server core dependency is used here, and there are client components that access the Configuration Center service spring-cloud-starter-config
.
Then src/main/resources
create the bootstrap.yml
file below and add the following configuration:
spring: application: name: eureka-server cloud: config: uri: http://localhost:8888
This file configures the name of the application to read the configuration file, that is spring.application.name
, its name corresponds to the file name of the service center. In addition, the automatic registration and discovery of Eureka is based on this parameter. The URI that configures the service center is then configured.
To create a new Java class, cn.zxuqian.Application
use the following code:
package cn.zxuqian;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;@EnableEurekaServer@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
@EnableEurekaServer
This application is configured as Eureka Server with only one annotation. Then create the file in the Git repository in the configuration Center eureka-server.yml
and add the following configuration:
server: port: 8761eureka: client: register-with-eureka: false fetch-registry: false
This file configures the port of Eureka-server, and turns off Eureka Self-registration and discovery, because if it does not close, Eureka will try to register itself during the boot process, however, the discovery service will not start to error. Here, Eureka Server is configured.
Update Web Client
Now we want to update the Web client so that it can be automatically registered and discovered by Eureka. Home in Pom.xml add Eureka client dependency:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId></dependency>
Then Application
add annotations to the class @EnableDiscoveryClient
:
@EnableDiscoveryClient@SpringBootApplicationpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
Finally we create a class to test whether the service has been successfully registered and discovered. Create a new Java class cn.zxuqian.controllers.ServiceInstanceController
and add the following code:
package cn.zxuqian.controllers;import Org.springframework.beans.factory.annotation.autowired;import org.springframework.cloud.client.ServiceInstance; Import Org.springframework.cloud.client.discovery.discoveryclient;import Org.springframework.web.bind.annotation.pathvariable;import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.restcontroller;import java.util.List; @RestControllerpublic class Serviceinstancecontroller {@Autowired private discoveryclient discoveryclient; @RequestMapping ("/service-instances/{applicationname}") Public list<serviceinstance> Serviceinstancesbyapplicationname (@PathVariable String ApplicationName) {return THIS.DISCOVERYCLIENT.G Etinstances (applicationname); }}
This is a common restcontroller that defines a DiscoveryClient
type of variable and adds @Autowire
annotations. This annotation is a dependency injection feature provided by the spring framework, which, under spring context, automatically looks for DiscoveryClient
an implementation class, here is the Eureka client. Some of the features and principles of spring will be described in a later blog post.
This class also defines a serviceInstancesByApplicationName
method to handle the /service-instances/{applicationName}
request. This {applicationName}
matches the next part of the URL path /service-instances/
, and then @PathVariable
assigns the annotation to the parameter of the method applicationName
. such as Access http://localhost:8080/service-instances/web-client
, then applicationName
the value is web-client
. The function of the method is to spring.application.name
remove the corresponding instance information from the value according to the Discoveryclient, and return a list, which is automatically converted to a JSON array and returned to the browser.
Test
Because both the Eureka server and the Web client need to read the configuration from the Configuration service, start Config-server, then start Eureka-server, and finally start web-client, It may take a few more than 10 seconds for Eureka-server to discover and register web-client after a successful startup. After the completion http://localhost:8080/service-instances/web-client
of the visit, the following results will be obtained:
[{"Host": "Xuqians-imac", "Port": 8080, "Instanceinfo": {"instanceId": "Xuqians-imac:web-client", "app": "Web-client", "Appgroupname": null, "ipaddr": "192.168.72.31", "Sid": "NA", "Homepageurl": "http://xuqians-imac:8080/", " Statuspageurl ":" Http://xuqians-imac:8080/actuator/info "," Healthcheckurl ":" http://xuqians-imac:8080/actuator/ Health "," Securehealthcheckurl ": null," vipaddress ":" Web-client "," securevipaddress ":" Web-client "," Countryid ": 1," Datacenterinfo ": {" @class ":" Com.netflix.appinfo.instanceinfo$defaultdatacenterinfo "," name ":" Myown "}," HostName ": "Xuqians-imac", "status": "Up", "Leaseinfo": {"renewalintervalinsecs": +, "durationinsecs": 90, " Registrationtimestamp ": 1525319124967," Lastrenewaltimestamp ": 1525319124967," Evictiontimestamp ": 0," Serviceuptimestamp ": 1525319124363}," Iscoordinatingdiscoveryserver ": false," metadata ": {" Management.port ":" 8080 "} , "Lastupdatedtimestamp": 1525319124967, "Lastdirtytimestamp": 1525319124297, "ActionType": "ADDED", "asgname": null, " Overriddenstatus ":" UNKNOWN "}," metadata ": {" Management.port":" 8080 "}," uri ":" http://xuqians-imac:8080 "," serviceId ":" Web-client "," secure ": false," scheme ": null}]
Note that the Configuration Center service is not set up to be registered and discovered by Eureka server because the configuration files are placed in Config-server, and Eureka Server has chicken eggs, eggs and chickens, So if you want Config-server to be automatically registered and discovered, then you need to configure Eureka Server separately, and then configure the URI for Eureka in config server and set it spring.cloud.config.discovery.enabled
to true. Specific later need to use the time to elaborate.
Summarize
Configuring Eureka server is fairly straightforward, just add a @EnableEurekaServer
note and turn off self-registration and discovery in the configuration. You can then add annotations to the application class of the client application @EnableDiscoveryClient
.
Welcome to visit my blog
Spring Cloud Getting Started Tutorial-Eureka Service Registration and Discovery