Spring Cloud:Eureka Service Registry

Posted by danaman on Tue, 10 Dec 2019 13:03:55 +0100

Preface

Service Governance

With the development of business, the application of micro-services also increases. The management and governance of these services will become more and more difficult. Cluster size, service location, service naming will change. Manual maintenance is prone to errors or naming conflicts.To solve this problem, service governance is the most core and basic module in the micro-service architecture, which mainly implements the automatic registration and discovery of individual micro-service instances.

Service Registration

In a service governance framework, one or more service registries are built.

Each service module registers its own services with the registry, informs the registry of additional information such as host, port number, version number, communication protocol, etc. The registry organizes service lists by service name.

The service registry also needs to monitor the availability of services in the list in a heartbeat fashion, and remove services from the list if they are not available to achieve the effect of troubleshooting services.

Service Discovery

Inter-service calls are no longer made by specifying a specific instance address, but by making a request call to the service name.

Service callers need to obtain a list of instances of all services from the service registry before they can access specific service instances.

When a service caller makes a call, it takes out a specific service instance with some policy to make a service call (client load balancing).

In production environments, for performance reasons, services are not acquired from the service registry every time, and different scenarios use different implementation strategies for caching and service culling.

Spring Cloud Eureka

Spring Cloud Eureka is based on Netflix Eureka for service registration and discovery.It mainly consists of two components:

  • Eureka Server: A service registry that supports highly available configurations and provides good service instance availability depending on strong consistency, allowing service registries to replicate each other's state in an asynchronous mode.
  • Eureka Client: Processes the registration and discovery of services. Clients can register and discover services through annotations and parameter configurations. Clients register their services with the registry and periodically send heartbeats to update their service leases. Eureka clients query the currently registered service information from the server and cache them locally and periodicallyRefresh service status.

Eureka Infrastructure

  • Service Registry (Eureka Server): A server that provides service registration and discovery capabilities.
  • Service Provider: An application that provides services registers its own services with Eureka Server for discovery by other applications.
  • Service Consumer: A consumer application obtains a list of services from Eureka Server and invokes the corresponding service (ribbon or feign).

Infrastructure Diagram

Quick Build Service Registry (Eureka Server)

1. Create a Spring Boot project and add dependencies

<properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2. @EnableEurekaServer Comment Start Service Registry

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudEurekaServerApplication {

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

}

3. Profile application.properties

server.port=9999
#eureka
eureka.instance.hostname=127.0.0.1
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false
eureka.client.serviceUrl.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
  • eureka.client.register-with-eureka: The current application is a service registry, so setting it to false means that you do not register yourself with the registry.
  • eureka.client.fetch-registry: The registry is primarily responsible for maintaining service instances, so setting it to false means not retrieving services for the current application.
  • eureka.client.serviceUrl.defaultZone: The address used to interact with Eureka Server, which is required for both registration and discovery services.

4. Start the application and access: http://127.0.0.1:9999/

You can see the information panel for Eureka, where the list in Instances currently registered with Eureka shows No instances available, indicating that the registry has not registered any services.

Service Provider

1. Create a Spring Boot project and add dependencies

<properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
    </properties>

    <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-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

2. @EnableDiscoveryClient annotation Start Eureka Client

@SpringBootApplication
//@EnableEurekaClient This annotation is used when using eureka as the registry and the scene is relatively simple
@EnableDiscoveryClient //Scenes are wider
public class SpringCloudEurekaServiceApplication {

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

}

The @EnableEurekaClient and @EnableDiscoveryClient are used equally well in the current example. The @EnableEurekaClient annotation is used when using eureka as the registry, with a single scene and a wider @EnableDiscoveryClient scene.

3. Profile application.properties

server.port=8888
spring.application.name=spring-cloud-eureka-service
#info application information
info.app.name=spring-cloud-eureka-service
info.app.version=v1.0.0
info.app.description=spring-cloud-eureka-service
#eureka
eureka.instance.hostname=127.0.0.1
#Heart beats every 5s to prove the service is still alive
eureka.instance.lease-renewal-interval-in-seconds=5
#If there is no heartbeat within 10 seconds, remove the service from the server
eureka.instance.lease-expiration-duration-in-seconds=10
eureka.client.serviceUrl.defaultZone=http://127.0.0.1:9999/eureka/
  • eureka.instance.lease-renewal-interval-in-seconds: Set the number of seconds between heartbeats
  • eureka.instance.lease-expiration-duration-in-seconds: set no heartbeat in seconds, then exclude service

4. Start the application and access: http://127.0.0.1:9999/

In the console of the Service Registry, we can see the following output indicating that the service was successfully registered.

 c.n.e.registry.AbstractInstanceRegistry  : Registered instance SPRING-CLOUD-EUREKA-SERVICE/192.168.101.201:spring-cloud-eureka-service:8888 with status UP (replication=false)

On the information panel of Eureka, you can also see the registration information for services in the Instances currently registered with Eureka list.As follows:

High Availability Registry (Cluster)

The service registry with single-node mode is described above, but it is not typically used in real-world production environments.In a distributed system, the service registry is a very important component, and failures can be devastating if they occur in a single-node mode.Cluster solutions are often used to maintain high availability of services.

In Eureka's service governance design, all nodes are both service providers and service consumers, and service registries are no exception.Eureka synchronizes service lists with each other by registering services with each other to achieve highly available results.

Dual Node Registry

  1. Set up Service Registry A with the following configuration files:
server.port=9991
spring.application.name=eureka-server
spring.profiles.active=nodea
#eureka
eureka.instance.hostname=nodea
#Set the microservice call address to IP first (default is false)
#eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://nodeb:9992/eureka/
  1. Set up Service Registry B with the following configuration files:
server.port=9992
spring.application.name=eureka-server
spring.profiles.active=nodeb
#eureka
eureka.instance.hostname=nodeb
#Set the microservice call address to IP first (default is false)
#eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/
  1. Add nodea and nodeb transformations to the /etc/hosts (windows system path is C:WindowsSystem32 driversetchosts) file as follows:
127.0.0.1 nodea
127.0.0.1 nodeb
  1. Start two projects and visit http://nodea:9991/and http://nodeb:9992/, respectively. We can see that both nodes have been registered, as shown in the following figure:

  1. After setting up a multi-node service registry, service providers also need to make some simple configurations, which can be modified as follows:
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/

After starting the project, visit the two service registries and we see that the service is registered in both nodes.

  1. When we close Service Registry Node A, we can see that Service Registry Node B still provides services and Node A changes from available-replicas to unavailable-replicas.

Service Consumer

Calling services using Ribbon

1. pom-related dependency configuration
<properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.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-netflix-ribbon</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
2. Profile application.properties
spring.application.name=spring-cloud-ribbon-consumer
server.port=8081
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/
3. Start Class Configuration

Register the application as an Eureka client through the @EnableDiscoveryClient annotation to gain service discovery capabilities.

Create a Spring Bean instance of RestTemplate to invoke the service.

Open load balancing on the client through the @LoadBalanced annotation.

@SpringBootApplication
@EnableDiscoveryClient
public class SpringCloudRibbonConsumerApplication {

    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }
    
    public static void main(String[] args) {
        SpringApplication.run(SpringCloudRibbonConsumerApplication.class, args);
    }

}
4. ConsumerController to implement service calls
@RestController
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;
    
    @RequestMapping("/test")
    public String test() {
        return restTemplate.getForEntity("http://spring-cloud-eureka-service/test", String.class).getBody();
    }
}

spring-cloud-eureka-service is the application name of the service registry in both case and case.

Calling services using Feign

1. pom-related dependency configuration
<properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.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-openfeign</artifactId>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
2. Profile application.properties
spring.application.name=spring-cloud-feign-consumer
server.port=8080
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/
3. Start Class Configuration

Register the application as an Eureka client through the @EnableDiscoveryClient annotation to gain service discovery capabilities.

Enable feign for remote calls through the @EnableFeignClients annotation.

@SpringBootApplication
@EnableDiscoveryClient//Enable service registration and discovery
@EnableFeignClients//Enable feign for remote calls
public class SpringCloudFeignConsumerApplication {

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

}
4. Implement Service Call Interface
@FeignClient(name = "spring-cloud-eureka-service")
public interface TestService {

    @RequestMapping("/test")
    public String test();
}

spring-cloud-eureka-service is the application name of the service registry in both case and case.

Method names and parameters in this interface and contoller in remote services need to be consistent.

5. ConsumerController to implement service calls
@RestController
public class ConsumerController {

    @Autowired
    private TestService testService;
    
    @RequestMapping("/test")
    public String test() {
        return testService.test();
    }
}

Sample Code

github

Code cloud

No special instructions, copyright in this article Cold and fog All, please indicate the source for reprinting.

Original Title: Spring Cloud (2): Eureka Service Registry

Original address: https://www.zwqh.top/article/info/28

If there are any deficiencies in the article, please make some suggestions, which will be improved in the future.

If the article is helpful, please give me a compliment.

Keep an eye on my Public Number, articles are continually updated...

Topics: Java Spring Junit Windows