Spring Cloud (two): Eureka service registry

Foreword

Service Management

With the business development, micro-service applications have increased, management and governance will become increasingly difficult for these services, and the cluster size, location services, the service name will change, manual maintenance mode error prone or name conflict and so on. The service management in order to solve this problem, a service management is a micro-service architecture and the most basic core modules, which mainly serve to implement various micro instance automated registration and discovery .

Service Registration

In the service management framework, will build one or more service registries.

Each service module registered with the registry services they provide, some additional information will host host, port number, version number, communication protocol to inform the registry, the registry service organizations by service name classification list.

Service registry also needs to be a way to monitor the heartbeat list of services is available, can be used if need be removed from the list of services, achieve troubleshooting services.

Service Discovery

Room service invocation no longer be achieved by specifying a specific instance address, but calling achieved by initiating a request to the service name.

Examples of service the caller needs to obtain a list of all the services to start service registry to enable access to specific service instances.

Caller to the service when initiating calls, will be taken out of service a specific instance of a service call (client load balancing) to a strategy.

In a production environment in order to consider factors such as performance, not by way of access to services to every service registry, and different scenarios in the cache and the service will eliminate the use of mechanisms such as different implementation strategies.

Spring Cloud Eureka

Spring Cloud Eureka is to implement the service registration and discovery-based Netflix Eureka. It consists of two main components:

  • Eureka Server (server) : service registry, support high availability configuration, relying on the availability of good examples of strong consistency of services provided, you can copy each other's status via asynchronous mode between the service registry.
  • Eureka Client (client) : registration and found that the client processing services can be achieved by way of annotations and configuration parameters registration and found that the client registers its own service provided to the registry and periodically sends a heartbeat to update its service lease, Eureka client queries the currently registered service information from the server and cache them locally and periodically refresh the service status.

Eureka Infrastructure

  • Registration Service Center (Eureka Server) : server, service registration and discovery.
  • Service provider (Service Provider) : application service delivery, service will provide their own registration to Eureka Server, other applications for discovery.
  • Consumer Services (Service Consumer) : consumer applications get the list of services from Eureka Server, to invoke the corresponding service (ribbon or feign).

Infrastructure Figure

Quickly build service registry (Eureka Server)

1. Create a Spring Boot project, 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 annotations begin service registry

@SpringBootApplication
@EnableEurekaServer
public class SpringCloudEurekaServerApplication {

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

}

3. Profiles 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 for the registration service center, it is set to false, the representative does not register itself with the registry.
  • eureka.client.fetch-registry: registry duties are mainly maintenance service instances, it is set to false, do not search services on behalf of the current application.
  • eureka.client.serviceUrl.defaultZone: Address for interacting with Eureka Server, registration services and discovery services need to rely on this address.

4. Start the application, visit: http: //127.0.0.1: 9999 /

可以看到 Eureka 的信息面板,其中 Instances currently registered with Eureka 中列表显示 No instances available,说明该注册中心还没有注册任何服务。

服务提供者(Service Provider)

1. 创建 Spring Boot 项目,添加依赖

<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 注解启动 Eureka 客户端

@SpringBootApplication
//@EnableEurekaClient  该注解在采用eureka作为注册中心时使用,场景较为单一
@EnableDiscoveryClient //场景更为广泛
public class SpringCloudEurekaServiceApplication {

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

}

@EnableEurekaClient@EnableDiscoveryClient 在当前示例中使用效果好是一样的,@EnableEurekaClient 注解在采用eureka作为注册中心时使用,场景较为单一,@EnableDiscoveryClient 场景更为广泛。

3. 配置文件 application.properties

server.port=8888
spring.application.name=spring-cloud-eureka-service
#info 应用信息
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
#每隔5s心跳一次,证明本服务还活着
eureka.instance.lease-renewal-interval-in-seconds=5
#本服务10s内没有心跳,就将该服务从服务端剔除
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:设置心跳间隔秒数
  • eureka.instance.lease-expiration-duration-in-seconds:设置秒数内无心跳,则剔除服务

4. 启动应用,访问:http://127.0.0.1:9999/

在服务注册中心的控制台中我们可以看到如下输出,说明服务被注册成功了。

 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)

而在 Eureka 的信息面板上,在 Instances currently registered with Eureka 列表中同样可以看到服务的注册信息。如下图:

高可用注册中心(集群)

上面介绍了单节点模式的服务注册中心,不过在实际生产环境中,通常不会采用这种模式。在分布式系统中,服务注册中心是非常重要的组成部分,如果是单节点模式,发生故障的话将会是毁灭性的灾害。所以为了维护服务的高可用性,通常采用集群的解决方案。

Eureka 的服务治理设计中,所有的节点既是服务提供方,也是服务消费方,服务注册中心也不例外。Eureka 通过互相注册服务的方式,以实现服务清单的互相同步,达到高可用的效果。

双节点注册中心

  1. 搭建服务注册中心 A,配置文件如下:
server.port=9991
spring.application.name=eureka-server
spring.profiles.active=nodea
#eureka
eureka.instance.hostname=nodea
#设置微服务调用地址为IP优先(缺省为false)
#eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://nodeb:9992/eureka/
  1. 搭建服务注册中心 B,配置文件如下:
server.port=9992
spring.application.name=eureka-server
spring.profiles.active=nodeb
#eureka
eureka.instance.hostname=nodeb
#设置微服务调用地址为IP优先(缺省为false)
#eureka.instance.prefer-ip-address=true
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/
  1. 在 /etc/hosts(windows系统路径为 C:\Windows\System32\drivers\etc\hosts) 文件中添加 nodea 和 nodeb 的转换,如下:
127.0.0.1 nodea
127.0.0.1 nodeb
  1. 启动两个项目,分别访问http://nodea:9991/http://nodeb:9992/,我们可以看到两个节点都已经被注册,如下图所示:

  1. 搭建完多节点服务注册中心之后,服务提供者也需要做一些简单的配置,以上面的服务提供者为例,修改如下:
eureka.client.serviceUrl.defaultZone=http://nodea:9991/eureka/,http://nodeb:9992/eureka/

启动项目后,访问两个服务注册中心,我们看到服务被注册到这两个节点内。

  1. 这时我们关闭服务注册中心节点 A,我们可以看到服务注册中心节点 B 依然可以提供服务,而节点 A 从 available-replicas(可以分片) 变为 unavailable-replicas(不可用分片)。

服务消费者(Service Consumer)

使用 Ribbon 调用服务

1. pom 相关依赖配置
<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. 配置文件 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. 启动类配置

通过 @EnableDiscoveryClient 注解将应用注册为 Eureka 客户端,获得服务发现能力。

创建 RestTemplate 的 Spring Bean 实例用来调用服务。

通过 @LoadBalanced 注解来开启客户端的负载均衡。

@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 来实现服务调用
@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 为服务注册中心的应用名称,大小写均可。

使用 Feign 调用服务

1. pom 相关依赖配置
<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. 配置文件 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. 启动类配置

通过 @EnableDiscoveryClient 注解将应用注册为 Eureka 客户端,获得服务发现能力。

通过 @EnableFeignClients 注解来启用feign进行远程调用。

@SpringBootApplication
@EnableDiscoveryClient//启用服务注册与发现
@EnableFeignClients//启用feign进行远程调用
public class SpringCloudFeignConsumerApplication {

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

}
4. 实现服务调用接口
@FeignClient(name = "spring-cloud-eureka-service")
public interface TestService {

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

spring-cloud-eureka-service 为服务注册中心的应用名称,大小写均可。

此接口中的方法和远程服务中contoller中的方法名和参数需保持一致。

5. ConsumerController 来实现服务调用
@RestController
public class ConsumerController {

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

示例代码

github

码云

非特殊说明,本文版权归 朝雾轻寒 所有,转载请注明出处.

原文标题:Spring Cloud(二):Eureka 服务注册中心

原文地址:https://www.zwqh.top/article/info/28

如果文章有不足的地方,欢迎提点建议,后续会完善~

如果文章对您有帮助,请给我点个赞哦~

关注下我的公众号,文章持续更新中...

Guess you like

Origin www.cnblogs.com/zwqh/p/12008993.html