Introduction
In microservices, service registration and discovery play a key role in managing each microservice subsystem. As the system expands more and more horizontally, the number of system splits into microservices will also increase accordingly, so it will become very difficult to manage and obtain the URLs of these microservices. If we add a new microservice, we will It is necessary to manually add its URL address or the address of other communication protocols in other places where the microservice is used, which will cause frequent errors and a huge workload. Once the address of a microservice changes, it is necessary to manually modify all The configuration file of the microservice that references it. Therefore, spring-cloud eureka server appears to solve such problems. After simple configuration, microservices can be automatically registered and discovered.
basic environment
- JDK 1.8
- Maven 3.3.9
- IntelliJ 2018.1
- Git
Project source code
Build Eureka Server
In the last blog, we introduced how to build the configuration center of spring-cloud, and a test web client to access it. This time we build a eureka server on the basis of the previous one, read the configuration of the configuration center, and then put the web The client registers with the eureka service as a Discovery Client. First create a new Maven project under IntelliJ:
- groupId: cn.zxuqian
- artifactId: registry
Then add the following code to 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</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</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-dependencies</artifactId>
<version>Finchley.M9</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
This eureka-server core dependency is used here spring-cloud-starter-netflix-eureka-server
, as well as the client component that accesses the configuration center service spring-cloud-starter-config
. Then
create a file below and add the following configuration:src/main/resources
bootstrap.yml
spring:
application:
name: eureka-server
cloud:
config:
uri: http://localhost:8888
This file is configured with the application name to read the configuration file, that is spring.application.name
, its name corresponds to the file name of the service center. In addition, Eureka's automatic registration and discovery are also based on this parameter. Then configure the uri of the configuration service center.
Create a new Java class, cn.zxuqian.Application
, and 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
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Here only @EnableEurekaServer
one annotation is used to configure the application as Eureka Server. Then create a file in the git repository of the configuration center eureka-server.yml
and add the following configuration:
server:
port: 8761
eureka:
client:
register-with-eureka: false
fetch-registry: false
This file configures the port of eureka-server, and closes eureka self-registration and discovery, because if it is not closed, eureka will try to register itself during the startup process, but it will report an error if the service is not started. At this point, the eureka server is configured.
Update Web Client
Now we need to update the web client so that it can be automatically registered and discovered by eureka. The home page adds the dependency of eureka client in pom.xml:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
Then Application
add the @EnableDiscoveryClient
annotation to the class:
@EnableDiscoveryClient
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Finally we create a class to test if 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;
@RestController
public class ServiceInstanceController {
@Autowired
private DiscoveryClient discoveryClient;
@RequestMapping("/service-instances/{applicationName}")
public List<ServiceInstance> serviceInstancesByApplicationName(
@PathVariable String applicationName) {
return this.discoveryClient.getInstances(applicationName);
}
}
This is a normal RestController, with a DiscoveryClient
variable of type defined and @Autowire
annotated. This annotation is the dependency injection function provided by the Spring framework. In the context of Spring, it will automatically find DiscoveryClient
the implementation class, here is the eureka client. Some features and principles of Spring will be discussed in future blog posts.
This class also defines serviceInstancesByApplicationName
methods for handling /service-instances/{applicationName}
requests. Here, {applicationName}
match the /service-instances/
later part of the url path, and then use the @PathVariable
annotation to assign it to the method's applicationName
parameter. For example access http://localhost:8080/service-instances/web-client
, then applicationName
the value of web-client
. The function of the method is to extract the corresponding instance information from the value in the discoveryClient spring.application.name
, and return a list, which will be automatically converted into 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, first start the config-server, then start the eureka-server, and finally start the web-client. The server discovers and registers the web-client. After accessing http://localhost:8080/service-instances/web-client
, you will get the following results:
[{"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":30,"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 to be registered and discovered by the eureka server, because the configuration files are all placed in the config-server, which has a chicken-and-egg problem with the eureka server, so if For config-server to be automatically registered and discovered, you need to configure eureka server separately, then configure eureka's uri in config server, and set spring.cloud.config.discovery.enabled
it to true. Details will be explained later when needed.
Summarize
Configuring eureka server is quite simple, just add an @EnableEurekaServer
annotation and turn off self-registration and discovery in the configuration. @EnableDiscoveryClient
Then add annotations to the Application class of the client application .
Welcome to my blog