Wechat search: science and technology cat, get the first time update

Spring-cloud Euraka is a component in the Spring Cloud collection that integrates Euraka for service registration and discovery. Eureka is an open source framework in Netflix. Like ZooKeeper and Consul, spring-Cloud also integrates with ZooKeeper and Consul.

Set up eureka service registry

Introduce the following dependencies

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <! - the latest version of eureka server package - > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> </dependencies> <! -- SpringCloud dependencies, Play the role of management version - > < dependencyManagement > < dependencies > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR9</version> <type>pom</type> <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code

Version mapping between Spring Cloud and Spring Boot

Release Train Boot Version
X 2020.0. aka Ilford X 2.4.
Hoxton 2.2.x, 2.3.x (Starting with SR5)
Greenwich X 2.1.
Finchley X 2.0.
Edgware X 1.5.
Dalston X 1.5.

Add on the startup class@EnableEurekaServerNote that this is a Eureka server

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudEurekaApplication {

    public static void main(String[] args) { SpringApplication.run(SpringCloudEurekaApplication.class, args); }}Copy the code

Add some configuration in application.properties

server.port=8080Name =Eureka-Server # Specifies the IP address of the Eureka Server Eureka. Instance. hostname=localhost eureka.instance.statusPageUrl=http://${eureka.instance.hostname}:${server.port}/info
eureka.instance.healthCheckUrl=http://${eureka.instance.hostname}:${server.port}/health
eureka.instance.homePageUrl=http://${eureka.instance.hostname}/# indicates whether to register the service with the Eureka serverfalse
# eureka.client.register-with-eureka=false# indicates whether to obtain the service information from the Eureka server. Because only one Eureka server is built here, and the service information does not need to be synchronized from other Eureka servers, set this parameter tofalse
# eureka.client.fetch-registry=falseThe default value is HTTP://localhost:8761/eureka Specifies the IP address of the Eureka server as the IP address of the other EUreka server 8081
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/This is used to define the interval between service renewal tasks, default30Second eureka. Client. ServiceUrl. Registry - fetch - interval - seconds =5
Copy the code

After the configuration is complete, start the service and accesshttp://localhost:8080/

The Instances Currently Registered with Eureka list is empty because no Eureka client has registered the service yet

Set up the provider service provider

Introduce the following dependencies

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> </dependencies> <! -- SpringCloud dependencies, Play the role of management version - > < dependencyManagement > < dependencies > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR9</version> <type>pom</type> <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code

Add to the startup class@EnableDiscoveryClientNote that this is a Eureka client

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudProviderApplication {

    public static void main(String[] args) { SpringApplication.run(SpringCloudProviderApplication.class, args); }}Copy the code

Then write a TestController that provides some REST services externally

@RestController
public class TestController {
    @GetMapping("/hello")
    public String hello(a) {
        return "hello world"; }}Copy the code

Add some configuration in application.properties

# specify the service port as8081
server.port=8082# Server Provider = server-provider The service name spring.application.name= server-provider # will be used by the service consumer to retrieve the interface from the TestController above, although the default values for both configurations aretrue, which makes the functions of the Eureka client more intuitive (registering the service with the server and periodically obtaining the service cache from the server to the local server) eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true# specified Eureka server address, here for the above definition of Eureka server address Eureka. Client. ServiceUrl. DefaultZone = HTTP://localhost:8080/eureka/,http://localhost:8081/eureka/Eureka.instance. prefer-ip-address=true
Copy the code

After the configuration is complete, start Eureka-Client, and you can see the registration success message from the console

Registered Applications size is zero : true
Application version is -1: true
Getting all instance registry info from the eureka server
The response status is 200
Starting heartbeat executor: renew interval is: 30
InstanceInfoReplicator onDemand update allowed rate per min is 4
Discovery Client initialized at timestamp 1611244216061 with initial instances count: 0
Registering application SERVER-PROVIDER with eureka with status UP
Saw local status change event StatusChangeEvent [timestamp=1611244216076, current=UP, previous=STARTING]
DiscoveryClient_SERVER-PROVIDER/DESKTOP-7LUOFJF.lan:Server-Provider:8081: registering service...
Tomcat started on port(s): 8081 (http) with context path ''
Updating port to 8081
DiscoveryClient_SERVER-PROVIDER/DESKTOP-7LUOFJF.lan:Server-Provider:8081 - registration status: 204
Copy the code

To visit againhttp://localhost:8082/, you can see that the list of services has appeared as server-providerde service

UP for the meaning of online (if had the client normally closed, then the state will be DOWN here), click on the back of the link http://192.168.68.233:8081/actuator/info will/info to access this service interface:

{"app": {"name":"Server-Provider"}}
Copy the code

Close the Eureka client and refresh http://localhost:8080/ again

It can be seen that although the Eureka client has been closed, the service is still listed in the service list of the Eureka server page, and the red text prompts the page

EMERGENCY! EUREKA MAY BE INCORRECTLY CLAIMING INSTANCES ARE UP WHEN THEY’RE NOT. RENEWALS ARE LESSER THAN THRESHOLD AND HENCE THE INSTANCES ARE NOT BEING EXPIRED JUST TO BE SAFE.
Copy the code

Basically, Eureka has gone into protective mode. After the microserver is deployed, the Eureka client may fail to send heartbeat messages to the Eureka server due to network problems. In this case, the Eureka server determines that the Eureka client has been suspended, although the Eureka client is still running normally. The protected mode is designed to solve this problem. When the Eureka server loses too many Eureka clients simultaneously in a short period of time, the Eureka server enters the protected mode and does not remove these clients. Since we only have one Eureka client service deployed here, shutting down the client satisfies the “too many Eureka clients lost in a short period of time” condition.

In the development process, we can first turn off the protected mode and add a configuration on the Eureka server

eureka.server.enable-self-preservation= false
Copy the code

Enable service monitoring

Introduce the following dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
Copy the code

Add some configuration in application.properties

# # to enable monitoring open all endpoints health, info, metrics, and through the physical / + endpoint names can get the corresponding information. The default open health and info, the metrics is not open to the default management endpoints. Web. Exposure. Include = * # did not open the physical/health, the information we get is {"status":"UP"}, the value of status can also be DOWN. After open print detailed information management. The endpoint. Health. The show - the details = always info. The app. Name = Server - the ProviderCopy the code

Access path

Localhost Specifies the IP address and host name of the deployed server. Info and health are enabled by default. Metrics are disabled by default

  • Heartbeat check http://localhost:8081/actuator/info

  • Health check http://localhost:8081/actuator/health

  • Indicators of http://localhost:8081/actuator/metrics

Eureka cluster

The Ureka server plays an important role as all Eureka clients register their services with the Eureka server and then make them available to all service consumers. If the single-node Eureka server went down, all services would be inaccessible, which would be disastrous. In order to improve the availability of the Eureka server, we usually deploy it in a cluster, that is, multiple Eureka servers are deployed at the same time and the services can be synchronized with each other.

We turned off the following two configurations when setting up the Eureka server

eureka.client.register-with-eureka=false

eureka.client.fetch-registry=false
Copy the code

In fact, in Eureka cluster mode, enabling the current Eureka server to register itself as a service with other Eureka servers and obtain services from other Eureka servers for synchronization. So let’s set these two parameters to true (the default is true) and start building the Eureka server cluster. For simplicity, let’s build a two-node Eureka server cluster.

The two applications. Properties configurations are as follows

  • Eureka server for port 8080
server.port=8080Name =Eureka-Server # Specifies the IP address of the Eureka Server Eureka. Instance. hostname=localhost eureka.instance.statusPageUrl=http://${eureka.instance.hostname}:${server.port}/info
eureka.instance.healthCheckUrl=http://${eureka.instance.hostname}:${server.port}/health
eureka.instance.homePageUrl=http://${eureka.instance.hostname}/# indicates whether to register the service with the Eureka serverfalse
# eureka.client.register-with-eureka=false# indicates whether to obtain the service information from the Eureka server. Because only one Eureka server is built here, and the service information does not need to be synchronized from other Eureka servers, set this parameter tofalse
# eureka.client.fetch-registry=falseThe default value is HTTP://localhost:8761/eureka Specifies the IP address of the Eureka server as the IP address of the other EUreka server 8081
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:8081/eureka/This is used to define the interval between service renewal tasks, default30Second eureka. Client. ServiceUrl. Registry - fetch - interval - seconds =5Eureka.server. enable-self-preservation=false
Copy the code
  • Eureka server for port 8081
server.port=8081Name =Eureka-Server # Specifies the IP address of the Eureka Server Eureka. Instance. hostname=localhost eureka.instance.statusPageUrl=http://${eureka.instance.hostname}:${server.port}/info
eureka.instance.healthCheckUrl=http://${eureka.instance.hostname}:${server.port}/health
eureka.instance.homePageUrl=http://${eureka.instance.hostname}/# indicates whether to register the service with the Eureka serverfalse
# eureka.client.register-with-eureka=false# indicates whether to obtain the service information from the Eureka server. Because only one Eureka server is built here, and the service information does not need to be synchronized from other Eureka servers, set this parameter tofalse
# eureka.client.fetch-registry=falseThe default value is HTTP://localhost:8761/eureka Specifies the IP address of the Eureka server as the IP address of the other EUreka server 8080
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:8080/eureka/This is used to define the interval between service renewal tasks, default30Second eureka. Client. ServiceUrl. Registry - fetch - interval - seconds =5Eureka.server. enable-self-preservation=false
Copy the code

Build consumer services for consumers

The Eureka client is both a service provider and a service consumer, that is, its interface may be accessed by other services, and it may also invoke other service interfaces

Introduce a dependency

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> <! -- SpringCloud dependencies, Play the role of management version - > < dependencyManagement > < dependencies > < the dependency > < groupId > org. Springframework. Cloud < / groupId > <artifactId>spring-cloud-dependencies</artifactId> <version>Hoxton.SR9</version> <type>pom</type> <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code

Add to the entry class@EnableDiscoveryClientAnnotations are used to discover and register services and configure oneRestTemplate BeanAnd then add@LoadBalancedAnnotations to enable load balancing

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudConsumerApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(a) {
        return new RestTemplate();
    }

    public static void main(String[] args) { SpringApplication.run(SpringCloudConsumerApplication.class, args); }}Copy the code

Write a TestController to consume the service

@RestController
public class TestController {
    @Autowired
    private RestTemplate restTemplate;

    /** * the RestTemplate object is injected into getInfo to get the service and consume it. * You can see that we use server-provider to get the service instead of using the traditional IP and port format. * This shows the benefits of using Eureka to get the service, as long as we keep the service name unchanged, IP and port are not our concerns * *@return* /
    @GetMapping("/info")
    public String getInfo(a) {
        return this.restTemplate.getForEntity("http://Server-Provider/hello", String.class).getBody(); }}Copy the code

Add some configuration in application.properties

# specify the service port as8083
server.port=8083Set Server name to server-consumer The service name spring.application.name= server-consumer # will be used by the service Consumer to retrieve the interface from the TestController above, although the default values for both configurations aretrue, which makes the functions of the Eureka client more intuitive (registering the service with the server and periodically obtaining the service cache from the server to the local server) eureka.client.register-with-eureka=true
eureka.client.fetch-registry=true# specified Eureka server address, here for the above definition of Eureka server address Eureka. Client. ServiceUrl. DefaultZone = HTTP://localhost:8080/eureka/,http://localhost:8081/eureka/Eureka.instance. prefer-ip-address=true
Copy the code

To start the project, visithttp://localhost:8083/info

Eureka adds authentication

For security reasons, we may add user authentication to the Eureka server. We introduced a Spring-Security dependency in Eureka-Server

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
Copy the code

Then configure the user name and password in application.yml

spring.security.user.name=admin
spring.security.user.password=123456
Copy the code

Eureka server configured with a password, after all the Eureka. Client. ServiceUrl. DefaultZone configuration must also be configured on the user name and password, format for: Eureka. Client. ServiceUrl. DefaultZone = http://${userName} : ${password} @ ${hosetname} : ${port} / had been /, such as:

eureka.client.serviceUrl.defaultZone=http://admin:123456@${eureka.instance.hostname}:8080/eureka/
Copy the code

After repackaging and deploying, visit http://localhost:8080/, and the verification window is displayed. Enter your user name and password to access the system

Eureka configuration

Common configuration options in Eureka and their meanings

configuration meaning The default value
eureka.client.enabled Whether to enable Eureka Client true
eureka.client.register-with-eureka Indicates whether to register yourself with Eureka Server true
eureka.client.fetch-registry Indicates whether to obtain registered service information from Eureka Server true
eureka.client.serviceUrl.defaultZone Configure the Eureka Server address for registering and obtaining services http://localhost:8761/eureka
eureka.client.registry-fetch-interval-seconds The default value is 30 seconds. That is, the Eureka Server obtains and caches services every 30 seconds 30
eureka.instance.lease-renewal-interval-in-seconds Interval for sending heartbeat messages to Eureka Server, in seconds, for service renewal 30
eureka.instance.lease-expiration-duration-in-seconds Define the service failure time, that is, the number of seconds after the Eureka Server detects that the Eureka Client has no heartbeat (the Client goes offline unexpectedly) to reject it 90
eureka.server.enable-self-preservation Used to enable the Eureka Server self-protection function true
eureka.client.instance-info-replication-interval-seconds Interval (in seconds) between updated instance information changes to the Eureka server 30
eureka.client.eureka-service-url-poll-interval-seconds Interval for polling Eureka server address changes, in seconds. 300
eureka.instance.prefer-ip-address Indicates that the IP address is not the domain name false
eureka.client.healthcheck.enabled By default, the Erueka Server detects the health status of the Eureka Client using the heartbeat. By setting this parameter to true, the Eeureka Server can use the/Health endpoints of the Eeureka Server to detect the health status of the Client. false

There are many other configurations for Eureka. For details, see the source code of the EurekaClientConfigBean, EurekaServerConfigBean, and EurekaInstanceConfigBean configuration classes.

References

[1] Netflix: Cloud.spring. IO/Spring -clou…