Eureka service governance of Spring Cloud

Posted by Gafaddict on Sun, 16 Jan 2022 15:12:06 +0100

1, Eureka overview

Spring Cloud Eureka implements the function of service governance. Eureka provides server and client. The server is Eureka service registry. The client completes the registration and discovery of microservices to Eureka services.

Relationship between server and client

1,Eureka Server It is the server, which is responsible for managing the information and status of each microservice node.

2,Deploy on microservices Eureka Client Program, remote access Eureka Server Register yourself in Eureka Server. 

3,When a microservice needs to call another microservice Eureka Server Get the service call address in and make a remote call.

Role of the registry

1. Due to the large number of microservices, you need to know the ip address and port of the server to make remote calls. The registry can help manage the ip address and port of these services.

2. Microservices will report their status in real time. The registry will uniformly manage the status of these microservices, kick the problematic services out of the service list, and the client will get the available services for invocation.

2, Eureka Server setup

Stand alone environment construction

Add dependency in parent project

 <!-- spring-cloud The version of is named after the London underground station and corresponds to the chronological order of the version according to the alphabetical order -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                 <version>Hoxton.SR8</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>            

Add dependency in Eureka Server project

   <dependencies>
        <!-- Import Eureka Service dependency -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

Configure startup class: use @ EnableEurekaServer on the startup class to identify this service as Eureka service

@EnableEurekaServer
@SpringBootApplication
public class EurekaServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServiceApplication.class,args);
    }
}

Configure application yml

server:
  port: ${PORT:8888} #Service PORT. If no value is specified for PORT, 8888 is used
spring:
  application:
    name: EurekaServiceApplication #Specify the service name
eureka:
  client:
    registerWithEureka: false #Service registration: whether to register yourself with Eureka service. When called by other services, you need to register with Eureka
    fetchRegistry: false #For service discovery, whether to obtain registration information from Eureka needs to be set to true when you need to find the target service to be called from Eureka
    serviceUrl: #The interactive address of Eureka client and Eureka server, the address of the other party in the high availability state, and the self configuration in the stand-alone state (if not configured, the local port 8761 is the default)
      defaultZone: ${EUREKA_SERVER:http://127.0.0.1:8888/eureka/}
  server:
    enable-self-preservation: false #Whether the self-protection mode is enabled, which is generally closed in the development stage
    eviction-interval-timer-in-ms: 60000 #The service registry cleaning interval (unit: ms, default: 60 * 1000) is the interval to clean up invalid nodes. If no report is received from this node within this time period, the node will be removed from the service list.

Start Eureka Server

Description of red prompt:

THE SELF PRESERVATION MODE IS TURNED OFF.THIS MAY NOT PROTECT INSTANCE EXPIRY IN CASE OF NETWORK/OTHER PROBLEMS.
Self protection mode is turned off. In case of network or other problems, it may not protect the instance from failure.

Eureka Server self-protection mode

Eureka server has a self-protection mode. When the micro service no longer reports the status to Eureka server, Eureka server will delete the service from the service list. If there is a network exception (the micro service is normal), Eureka server will enter the self-protection mode and no longer delete the micro service from the service list.

High availability environment construction

Eureka Server high availability environment requires the deployment of two Eureka servers, which register with each other. If you start two Eureka servers locally, you should note that the ports of the two Eureka servers should be set differently.

Process to achieve high availability

1,In actual use Eureka Server Deploy at least two servers to achieve high availability.

2,Two sets Eureka Server Register with each other.

3,Two microservices need to be connected Eureka Server Register when one of them Eureka Death will not affect the registration and discovery of services.

4,Microservices will regularly report to Eureka server Send heartbeat and report your status.

5,The microservice obtains the service address from the registry to RESTful Method to initiate a remote call.

Eureka consists of high availability. The two eurekas register with each other, access each other through the domain name or host name, modify the hosts, and set the host names of the two Eureka services as www.eureka1.com com,www.eureka2.com.

127.0.0.1       www.eureka1.com

127.0.0.1       www.eureka2.com

Configure eureka

server:
  port: ${PORT:8888} #Service port, ${PORT:8888}, which is dynamically set through virtual machine parameters. If not set, it is 8888 by default
spring:
  application:
    name: EurekaServiceApplication #Specify the service name
eureka:
  client:
    registerWithEureka: true #Service registration. Do you want to register yourself with Eureka service
    fetchRegistry: true #Service discovery, whether to obtain registration information from Eureka
    serviceUrl: #The interactive address of Eureka client and Eureka server, the address of the other party in the high availability state, and the self configuration in the stand-alone state (if not configured, the local port 8761 is the default)
      defaultZone: ${EUREKA_SERVER:http://www.eureka2.com:9999/eureka/}

  server:
    enable-self-preservation: false #Whether the self-protection mode is enabled, which is generally closed in the development stage
    eviction-interval-timer-in-ms: 60000 #Service registry cleanup interval (unit: ms, default: 60 * 1000)
  instance:
    hostname: ${EUREKA_DOMAIN:www.eureka1.com}

Eureka Server1

Do nothing with the first Eureka Server1 and use the default value

Eureka Server2

Copy Eureka Server1 to get a copy of Eureka Server2, set virtual machine parameters, and dynamically specify port, registered address, hostname and host name

-DPORT=9999
-DEUREKA_SERVER=http://www.eureka1.com:8888/eureka/
-DEUREKA_DOMAIN:www.eureka2.com


Start two Eureka servers and access them respectively

http://localhost:9999/

http://localhost:8888/

Eureka Server1

Eureka Server2

3, Eureka service registration

Create a eureka client. When the client registers with the server, it will provide some metadata, such as host and port, URL, etc. Eureka server receives heartbeat messages from each client instance. If the heartbeat times out, the instance is usually deleted from the registered server.

Introduce dependency

Introduce Eureka client dependencies into a service

<!‐‐ introduce Eureka Client dependencies ‐‐>
<dependency>
	<groupId>org.springframework.cloud</groupId>
	<artifactId>spring‐cloud‐starter‐netflix‐eureka‐client</artifactId>
</dependency>

Configure application yml

In application YML configuration

server:
  port: ${PORT:8081}
spring:
  application:
    name: eureka-client1
eureka:
  instance:
    hostname: localhost
  client:
    registerWithEureka: true #Service registration switch
    fetchRegistry: true #Service discovery switch
    serviceUrl: #The addresses where Eureka client interacts with Eureka server. Multiple addresses are separated by commas
      defaultZone: ${EUREKA_SERVER:http://www.eureka1.com:8888/eureka/,http://www.eureka2.com:9999/eureka/}
  instance:
    prefer-ip-address:  true  #Register your ip address with Eureka service
    ip-address: ${IP_ADDRESS:127.0.0.1}
    instance-id: ${spring.application.name}:${server.port} #Specify the instance id

Add annotation to startup class

Add the annotation @ EnableDiscoveryClient or @ EnableEurekaClient on the startup class to indicate that it is an Eureka client

Similarities: @ EnableDiscoveryClient or @ EnableEurekaClient annotations are used to discover and register services

Differences: @ EnableEurekaClient is only applicable to Eureka as the registry, and @ EnableDiscoveryClient can be other registries.

@EnableDiscoveryClient
@SpringBootApplication
public class EurekaClientApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaClientApplication.class,args);
    }
}

Provision of services

org.springframework.cloud.client.discovery.DiscoveryClient object, you can get some information about the service.

@RestController
public class TestController {

    @Autowired
    private DiscoveryClient client;

    @GetMapping("/getInfo")
    public String getInfo() {
        List<String> services = client.getServices();
        for (String service : services) {
            System.out.println(service);
        }

        String info = null;
        List<ServiceInstance> instances = client.getInstances("eureka-client1");
        for (ServiceInstance instance : instances) {
            info = "host: " + instance.getHost() + ",service_id: " + instance.getServiceId();
        }
        return info;
    }
}

Start parameter configuration

Eureka Client1, using the default configuration.

Eureka Client2, dynamically setting port and IP

Perform test

Access services provided

Refresh Eureka Server to view registration

Eureka Server1

Eureka Server2

Start another Eureka Client2

4, Service consumption

Eureka client is both a service provider and a service consumer, that is, its own interface may be accessed by other services and may call other service interfaces at the same time.

Ribbon is an open source software to realize service load balancing, and the consumption of services is completed by ribbon

Introduce dependency

    <dependencies>
        <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.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>
    </dependencies>

Configure startup class

Configure a RestTemplate Bean and add the @ LoadBalanced annotation to enable load balancing. RestTemplate is an HTTP request tool that provides templates for common REST request schemes.

@EnableDiscoveryClient//Open discovery service and registration service
@SpringBootApplication
public class DemoApplication {

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

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

Perform test

Inject RestTemplate and use the object to obtain services and consume them in a balanced manner. Use the service name to obtain the service instead of the traditional form of IP and port. As long as the service name remains unchanged, IP and port are not the focus of attention.

@RestController
public class TestController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/getInfo")
    public String getInfo() {
        return this.restTemplate.getForEntity("http://eureka-client1/getInfo", String.class).getBody();
    }
}

5, Eureka server certification

For security reasons, the user authentication function will be added to Eureka server.

Add dependency

Introducing spring security dependency in Eureka server

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>
    </dependencies>

Configure user name and password

security:
  user:
    name: admin
    password: admin

Modify Eureka service address

After the Eureka server is configured with a password, all Eureka client. serviceUrl. The configuration of the defaultzone must also be configured with a user name and password

The format is:

eureka.client.serviceUrl.defaultZone=http://${userName}:${password}@${hosetname}:${port}/eureka/
eureka:
  instance:
    hostname: localhost
  client:
    serviceUrl:
      defaultZone: http://admin:admin123@localhost:8080/eureka/

Perform test

After restarting the project, it is found that no service is registered successfully, and the client console reports an error: com netflix. discovery. shared. transport. TransportException: Cannot execute request on any known server


security enables csrf by default, adds configuration on Eureka server, and closes csrf

@EnableWebSecurity
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Scheme I
        http.csrf().disable(); // Turn off csrf
        http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); // Turn on authentication

        // Scheme II
        //	http.csrf().ignoringAntMatchers("/eureka/**");
        //	super.configure(http);
    }
}

6, Description of Eureka configuration parameters

to configuremeaningDefault value
eureka.client.enabledEnable Eureka Clienttrue
eureka.client.register-with-eurekaIndicates whether to register yourself with Eureka Servertrue
eureka.client.fetch-registryIndicates whether to obtain registered service information from Eureka Servertrue
eureka.client.serviceUrl.defaultZoneConfigure Eureka Server address for registering and obtaining serviceshttp://localhost:8761/eureka
eureka.client.registry-fetch-interval-secondsThe default value is 30 seconds, that is, get the service on Eureka Server and cache it every 30 seconds30
eureka.instance.lease-renewal-interval-in-secondsThe interval between sending heartbeat to Eureka Server, in seconds, for service renewal30
eureka.instance.lease-expiration-duration-in-secondsDefine the service failure time, that is, the number of seconds after Eureka Server detects that Eureka Client has a heartbeat (the client unexpectedly goes offline)90
eureka.server.enable-self-preservationUsed to enable Eureka Server self-protection function. true
eureka.client.instance-info-replication-interval-secondsThe interval between updating instance information and Eureka server, in seconds30
eureka.client.eureka-service-url-poll-interval-secondsThe interval between polling Eureka server address change, in seconds.300
eureka.instance.prefer-ip-addressIndicates that IP is used for configuration instead of domain namefalse
eureka.client.healthcheck.enabledBy default, Erueka Server detects the health status of Eureka Client through heartbeat. Set it to true to change the method of health detection of Eureka server on the client, and use the / health endpoint of Actuator to detect.false

Topics: Spring Boot Spring Cloud eureka