Spring Cloud 入门教程 - Eureka服务注册与发现

简介

在微服务中,服务注册与发现对管理各个微服务子系统起着关键作用。随着系统水平扩展的越来越多,系统拆分为微服务的数量也会相应增加,那么管理和获取这些微服务的URL就会变得十分棘手,如果我们每新加一个微服务,就要在其它用到此微服务的地方手动加上它的URL地址或者其他通信协议的地址,这样会经常出错,而且工作量巨大,一旦某个微服务的地址发生了变化,就要手动修改所有引用它的微服务的配置文件。所以spring-cloud eureka server就是为了解决这样的问题而出现,经过简单的配置,即可自动注册和发现微服务。

基础环境

  • JDK 1.8
  • Maven 3.3.9
  • IntelliJ 2018.1
  • Git

项目源码

Gitee码云

搭建Eureka Server

上篇博客我们介绍了如何搭建spring-cloud的配置中心,还有一个测试的web client去访问它,这次我们在之前的基础上搭建一个eureka server,并且读取配置中心的配置,然后把web client作为Discovery Client注册到eureka服务。首先在IntelliJ下新建一个Maven项目:

  • groupId: cn.zxuqian
  • artifactId: registry

然后在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>

这里用到了spring-cloud-starter-netflix-eureka-server这个eureka-server核心依赖,还有访问配置中心服务的客户端组件spring-cloud-starter-config
然后在src/main/resources下创建bootstrap.yml文件,添加如下配置:

spring:
  application:
    name: eureka-server
  cloud:
    config:
      uri: http://localhost:8888

此文件配置了用以读取配置文件的应用名,即spring.application.name,它的名字对应于服务中心的文件名。另外Eureka的自动注册和发现也是基于这个参数的。然后配置了配置服务中心的uri。
新建一个Java类,cn.zxuqian.Application,使用如下代码:

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);
    }
}

这里只用@EnableEurekaServer一条注解即把该应用配置为Eureka Server。然后在配置中心的git仓库中创建eureka-server.yml文件,添加如下配置:

server:
  port: 8761

eureka:
 client:
  register-with-eureka: false
  fetch-registry: false

此文件配置了eureka-server的端口,以及关闭eureka自我注册和发现,因为如果不关闭的话,eureka在启动过程中就会去尝试注册自己,然而发现服务并没有启动就会报错。到此,eureka server就配置完了。

更新Web Client

现在我们要更新web client,使之可以被eureka自动注册和发现。首页在pom.xml中添加eureka client的依赖:

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

然后在Application类中加上@EnableDiscoveryClient注解:

@EnableDiscoveryClient
@SpringBootApplication
public class Application {

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

最后我们创建一个类用以测试服务是不是已成功注册和发现。新建一个Java类cn.zxuqian.controllers.ServiceInstanceController,添加如下代码:

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);
    }

}

这是一个普通的RestController, 定义了一个DiscoveryClient类型的变量并添加了@Autowire注解。此注解是Spring框架提供的依赖注入功能,在Spring的context下,它会自动寻找DiscoveryClient的实现类,此处是eureka client。关于Spring的一些特性和原理,将在以后的博文中讲到。
此类还定义了serviceInstancesByApplicationName方法,用以处理/service-instances/{applicationName}请求。这里的{applicationName}匹配url路径中/service-instances/以后的部分,然后用@PathVariable注解赋值给方法的applicationName参数。例如访问http://localhost:8080/service-instances/web-client,那么applicationName的值就是web-client。方法的作用是从discoveryClient中根据spring.application.name的值来取出对应的实例信息,返回的是一个list,会自动转换为json数组的形式返回给浏览器。

测试

因为eureka server和web client都需要从配置服务中读取配置,所以先启动config-server,然后再启动eureka-server,最后启动web-client,在启动成功后可能需要稍等十几秒让eureka-server发现和注册web-client。完成之后访问http://localhost:8080/service-instances/web-client,会得到如下结果:

[{"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}]

注意一下,这里并没有把配置中心服务设置为可以被eureka server注册和发现,因为这里把配置文件都放到了config-server中,它和eureka server有着鸡生蛋,蛋生鸡的问题,所以如果要让config-server被自动注册和发现,那么就需要单独配置eureka server,然后在config server中配置eureka的uri,以及设置spring.cloud.config.discovery.enabled为true。具体以后需要用的时候再详细说明。

总结

配置eureka server相当简单,只需要加一条@EnableEurekaServer注解,并在配置中关闭自我注册和发现即可。然后在客户端应用的Application类中加上@EnableDiscoveryClient注解即可。

欢迎访问我的博客

原文地址:http://blog.51cto.com/13727459/2112134

时间: 2024-08-11 03:30:53

Spring Cloud 入门教程 - Eureka服务注册与发现的相关文章

Spring Cloud 入门教程(一): 服务注册

1.  什么是Spring Cloud? Spring提供了一系列工具,可以帮助开发人员迅速搭建分布式系统中的公共组件(比如:配置管理,服务发现,链路开关,智能路由,微代理,控制总线,一次性令牌,全局锁,主节点选举, 分布式session, 集群状态).协调分布式环境中各个系统,为各类服务提供模板性配置.使用Spring Cloud, 开发人员可以搭建实现了这些样板的应用,并且在任何分布式环境下都能工作得非常好,小到笔记本电脑, 大到数据中心和云平台. Spring Cloud官网的定义比较抽象

Spring Cloud 入门教程(四): 分布式环境下自动发现配置服务

前一章, 我们的Hello world应用服务,通过配置服务器Config Server获取到了我们配置的hello信息"hello world". 但自己的配置文件中必须配置config server的URL(http://localhost:8888), 如果把config server搬到另外一个独立IP上, 那么作为一个client的hello world应用必须修改自己的bootstrap.yml中的config server的URL地址.这明显是不够方便的. 既然confi

Spring Cloud 入门教程(五): Ribbon实现客户端的负载均衡

接上节,假如我们的Hello world服务的访问量剧增,用一个服务已经无法承载, 我们可以把Hello World服务做成一个集群. 很简单,我们只需要复制Hello world服务,同时将原来的端口8762修改为8763.然后启动这两个Spring Boot应用, 就可以得到两个Hello World服务.这两个Hello world都注册到了eureka服务中心.这时候再访问http://localhost:8761, 可以看到两个hello world服务已经注册.(服务与注册参见Spr

Spring Cloud 入门教程(六): 用声明式REST客户端Feign调用远端HTTP服务

首先简单解释一下什么是声明式实现? 要做一件事, 需要知道三个要素,where, what, how.即在哪里( where)用什么办法(how)做什么(what).什么时候做(when)我们纳入how的范畴. 1)编程式实现: 每一个要素(where,what,how)都需要用具体代码实现来表示.传统的方式一般都是编程式实现,业务开发者需要关心每一处逻辑 2)声明式实现: 只需要声明在哪里(where )做什么(what),而无需关心如何实现(how).Spring的AOP就是一种声明式实现,

Spring Cloud 入门教程(二): 配置管理

使用Config Server,您可以在所有环境中管理应用程序的外部属性.客户端和服务器上的概念映射与Spring Environment和PropertySource抽象相同,因此它们与Spring应用程序非常契合,但可以与任何以任何语言运行的应用程序一起使用.随着应用程序通过从开发人员到测试和生产的部署流程,您可以管理这些环境之间的配置,并确定应用程序具有迁移时需要运行的一切.服务器存储后端的默认实现使用git,因此它轻松支持标签版本的配置环境,以及可以访问用于管理内容的各种工具.很容易添加

Spring Cloud 入门教程(八): 断路器指标数据监控Hystrix Dashboard

1. Hystrix Dashboard (断路器:hystrix 仪表盘)  Hystrix一个很重要的功能是,可以通过HystrixCommand收集相关数据指标. Hystrix Dashboard可以很高效的现实每个断路器的健康状况. 1). 在Ribbon服务g和Feign服务的Maven工程的pom.xml中都加入依赖 1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <art

Spring Cloud入门教程-Hystrix断路器实现容错和降级

简介 Spring cloud提供了Hystrix容错库用以在服务不可用时,对配置了断路器的方法实行降级策略,临时调用备用方法.这篇文章将创建一个产品微服务,注册到eureka服务注册中心,然后我们使用web客户端访问/products API来获取产品列表,当产品服务故障时,则调用本地备用方法,以降级但正常提供服务. 基础环境 JDK 1.8 Maven 3.3.9 IntelliJ 2018.1 Git 项目源码 Gitee码云 添加产品服务 在intelliJ中创建一个新的maven项目,

Spring Cloud 入门教程(三): 配置自动刷新

之前讲的配置管理, 只有在应用启动时会读取到GIT的内容, 之后只要应用不重启,GIT中文件的修改,应用无法感知, 即使重启Config Server也不行. 比如上一单元(Spring Cloud 入门教程(二): 配置管理)中的Hello World 应用,手动更新GIT中配置文件config-client-dev.properties的内容(别忘了用GIT push到服务器) hello=Hello World from GIT version 1 刷新 http://locahost/8

Spring Cloud 入门教程(十):和RabbitMQ的整合 -- 消息总线Spring Cloud Netflix Bus

在本教程第三讲Spring Cloud 入门教程(三): 配置自动刷新中,通过POST方式向客户端发送/refresh请求, 可以让客户端获取到配置的最新变化.但试想一下, 在分布式系统中,如果存在很多个客户端都需要刷新改配置,通过这种方式去刷新也是一种非常痛苦的事情.那有没有什么办法让系统自动完成呢? 之前我们提到用githook或者jenkins等外部工具来触发.现在说另外一种思路, 如果refresh命令可以发送给config server,然后config server自动通知所有con