Spring Cloud 学习笔记 - No.1 服务注册发现 Eureka

Spring Cloud 介绍

官方网址 http://projects.spring.io/spring-cloud/

Spring Cloud provides tools for developers to quickly build some of the common patterns in distributed systems (e.g. configuration management, service discovery, circuit breakers, intelligent routing, micro-proxy, control bus, one-time tokens, global locks, leadership election, distributed sessions, cluster state).
Coordination of distributed systems leads to boiler plate patterns, and using Spring Cloud developers can quickly stand up services and applications that implement those patterns. They will work well in any distributed environment, including the developer's own laptop, bare metal data centres, and managed platforms such as Cloud Foundry.

Spring Cloud是一个基于Spring Boot实现的云应用开发工具,它为开发分布式应用提供了一些列工具,例如配置管理、服务发现、断路器、智能路由、微代理、控制总线、one-time tokens、全局锁、决策竞选、分布式会话和集群状态管理等。

Spring Cloud专注于提供良好的开箱即用的特性,包括:

  • 分布式/版本化配置 Distributed/versioned configuration
  • 服务注册和发现 Service registration and discovery
  • 路由 Routing
  • Service-to-service 调用 Service-to-service calls
  • 负载均衡 Load balancing
  • 断路器 Circuit Breakers
  • 全局锁 Global locks
  • 决策竞选和集群状态管理 Leadership election and cluster state
  • 分布式消息传递 Distributed messaging

Spring Cloud 的子项目

  • Spring Cloud Config
    Centralized external configuration management backed by a git repository. The configuration resources map directly to Spring Environment but could be used by non-Spring applications if desired.

  • Spring Cloud Netflix
    Integration with various Netflix OSS components (Eureka, Hystrix, Zuul, Archaius, etc.).

  • Spring Cloud Bus
    An event bus for linking services and service instances together with distributed messaging. Useful for propagating state changes across a cluster (e.g. config change events).

  • Spring Cloud for Cloud Foundry
    Integrates your application with Pivotal Cloud Foundry. Provides a service discovery implementation and also makes it easy to implement SSO and OAuth2 protected resources.

  • Spring Cloud Open Service Broker
    Provides a starting point for building a service broker that implements the Open Service Broker API.

  • Spring Cloud Cluster
    Leadership election and common stateful patterns with an abstraction and implementation for Zookeeper, Redis, Hazelcast, Consul.

  • Spring Cloud Consul
    Service discovery and configuration management with Hashicorp Consul.

  • Spring Cloud Security
    Provides support for load-balanced OAuth2 rest client and authentication header relays in a Zuul proxy.

  • Spring Cloud Sleuth
    Distributed tracing for Spring Cloud applications, compatible with Zipkin, HTrace and log-based (e.g. ELK) tracing.

  • Spring Cloud Data Flow
    A cloud-native orchestration service for composable microservice applications on modern runtimes. Easy-to-use DSL, drag-and-drop GUI, and REST-APIs together simplifies the overall orchestration of microservice based data pipelines.

  • Spring Cloud Stream
    A lightweight event-driven microservices framework to quickly build applications that can connect to external systems. Simple declarative model to send and receive messages using Apache Kafka or RabbitMQ between Spring Boot apps.

  • Spring Cloud Stream App Starters
    Spring Cloud Stream App Starters are Spring Boot based Spring Integration applications that provide integration with external systems.

  • Spring Cloud Task
    A short-lived microservices framework to quickly build applications that perform finite amounts of data processing. Simple declarative for adding both functional and non-functional features to Spring Boot apps.

  • Spring Cloud Task App Starters
    Spring Cloud Task App Starters are Spring Boot applications that may be any process including Spring Batch jobs that do not run forever, and they end/stop after a finite period of data processing.

  • Spring Cloud Zookeeper
    Service discovery and configuration management with Apache Zookeeper.

  • Spring Cloud for Amazon Web Services
    Easy integration with hosted Amazon Web Services. It offers a convenient way to interact with AWS provided services using well-known Spring idioms and APIs, such as the messaging or caching API. Developers can build their application around the hosted services without having to care about infrastructure or maintenance.

  • Spring Cloud Connectors
    Makes it easy for PaaS applications in a variety of platforms to connect to backend services like databases and message brokers (the project formerly known as "Spring Cloud").

  • Spring Cloud Starters
    Spring Boot-style starter projects to ease dependency management for consumers of Spring Cloud. (Discontinued as a project and merged with the other projects after Angel.SR2.)

  • Spring Cloud CLI
    Spring Boot CLI plugin for creating Spring Cloud component applications quickly in Groovy

  • Spring Cloud Contract
    Spring Cloud Contract is an umbrella project holding solutions that help users in successfully implementing the Consumer Driven Contracts approach.

  • Spring Cloud Gateway
    Spring Cloud Gateway is an intelligent and programmable router based on Project Reactor.

  • Spring Cloud OpenFeign
    Spring Cloud OpenFeign provides integrations for Spring Boot apps through autoconfiguration and binding to the Spring Environment and other Spring programming model idioms.

  • Spring Cloud Pipelines
    Spring Cloud Pipelines provides an opinionated deployment pipeline with steps to ensure that your application can be deployed in zero downtime fashion and easilly rolled back of something goes wrong.

Spring Cloud 的版本进化

Spring Cloud 的版本进化

按字母升序排列,例如 Angel 是第一版,Brixton 是第二版。

注意:

  • Finchley 版本基于 Spring Boot 2.0.x, 不支持 Spring Boot 1.5.x.
  • Dalston 和 Edgware 版本基于 Spring Boot 1.5.x, 不支持 Spring Boot 2.0.x.
  • Camden 版本基于 Spring Boot 1.4.x, 不支持 1.5.x.
  • Brixton 和 Angel 版本已结束生命

在接下来的示例中,我们将使用 Finchley 版本的 Spring Cloud 结合 2.0.x 版本的 Spring Boot。
Finchley 版本相对于之前的版本,一些依赖的名称发生了变化,请参考 https://spring.io/blog/2017/10/31/spring-cloud-finchley-m3-released

Finchley 版本相对于之前的版本,一些依赖的名称发生了变化

Spring Cloud Netflix

在开始示例之前,先来了解下 Spring Cloud Netflix。
它的主要内容是对 Netflix 公司一系列开源产品的包装,它为Spring Boot应用提供了自配置的Netflix OSS整合。通过一些简单的注解,开发者就可以快速的在应用中配置一下常用模块并构建庞大的分布式系统。

它包含如下的组件和特性:

  • 服务发现 Service Discovery: Eureka instances can be registered and clients can discover the instances using Spring-managed beans
  • 服务发现 Service Discovery: an embedded Eureka server can be created with declarative Java configuration
  • 断路器 Circuit Breaker: Hystrix clients can be built with a simple annotation-driven method decorator
  • 断路器 Circuit Breaker: embedded Hystrix dashboard with declarative Java configuration
  • 声明式的 REST 客户端 Declarative REST Client: Feign creates a dynamic implementation of an interface decorated with JAX-RS or Spring MVC annotations
  • 客户端负载均衡 Client Side Load Balancer: Ribbon
  • 外部配置 External Configuration: a bridge from the Spring Environment to Archaius (enables native configuration of Netflix components using Spring Boot conventions)
  • 路由和过滤 Router and Filter: automatic regsitration of Zuul filters, and a simple convention over configuration approach to reverse proxy creation

通过 Eureka 实现服务注册发现

在这里我们打算建立两个项目:

  • eureka-server:服务注册中心
  • eureka-client:服务提供者

eureka-server 服务注册中心

可以通过如下的 Spring Assistant 插件来创建项目,添加 Eureka Server 作为依赖。

eureka-server 的创建

eureka-server 的创建

eureka-server 的创建

pom.xml 中可以看出,导入了如下的依赖:

  • 2.0.3.RELEASE 版本的 Spring Boot
  • Finchley.RELEASE 版本的 Spring Cloud
  • spring-cloud-starter-netflix-eureka-server
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.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>
    </dependency>
</dependencies>

随后在启动程序中通过 @EnableEurekaServer 注解启动一个服务注册中心提供给其他应用进行对话:

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

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

随后在 application.properties:将服务注册中心端口设置为 1234。在默认设置下,该服务注册中心也会将自己作为客户端来尝试注册它自己,所以我们需要禁用它的客户端注册行为。

spring.application.name=eureka-server
server.port=1234

eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

最后通过 mvn spring-boot:run 命令启动项目,启动完成后,可以通过 http://127.0.0.1:1234 查看服务的注册情况,可以看到目前暂无服务注册到 Eureka Server。

目前暂无服务注册到 Eureka Server

eureka-client 服务提供者

可以通过如下的 Spring Assistant 插件来创建项目,添加 Eureka DiscoveryWeb 作为依赖。

eureka-client 的创建

eureka-client 的创建

eureka-client 的创建

pom.xml 中可以看出,导入了如下的依赖:

  • 2.0.3.RELEASE 版本的 Spring Boot
  • Finchley.RELEASE 版本的 Spring Cloud
  • spring-cloud-starter-netflix-eureka-client
  • spring-boot-starter-web
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.3.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Finchley.RELEASE</spring-cloud.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</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-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

随后在启动程序中通过 @EnableDiscoveryClient 来激活 Eureka 中的 DiscoveryClient 实现:

@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientApplication {

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

随后在 application.properties:通过 spring.application.name 属性,我们可以指定微服务的名称后续在调用的时候只需要使用该名称就可以进行服务的访问。eureka.client.serviceUrl.defaultZone 属性对应服务注册中心的配置内容,指定服务注册中心的位置。

spring.application.name=eureka-client
server.port=2001
eureka.client.serviceUrl.defaultZone=http://localhost:1234/eureka/

随后,我们创建一个 CalculatorController 类来提供加法服务:

@RestController
public class CalculatorController {

    @GetMapping("/add")
    public Integer add(@RequestParam Integer operand1, @RequestParam Integer operand2) {
        return operand1 + operand2;
    }
}

最后通过 mvn spring-boot:run 命令启动项目,启动完成后,可以通过 http://127.0.0.1:1234 查看服务的注册情况,可以看到目前有一个服务注册到 Eureka Server。

目前有一个服务注册到 Eureka Server

通过 http://10.93.67.135:2001/add 可以调用该加法服务:

调用该加法服务

如果我们将端口修改为 2002,重新打开一个 terminal 启动项目,可以看到该服务对应了两个实例 Zones。


该服务对应了两个实例 Zones

通过 Consul 实现服务注册发现

Spring Cloud Consul项目是针对Consul的服务治理实现。Consul是一个分布式高可用的系统,它包含多个组件,但是作为一个整体,在微服务架构中为我们的基础设施提供服务发现和服务配置的工具。

此处不详细介绍,参见 Spring Cloud构建微服务架构:服务注册与发现(Eureka、Consul)【Dalston版】


引用:
程序猿DD Spring Cloud基础教程
Spring Cloud构建微服务架构:服务注册与发现(Eureka、Consul)【Dalston版】
Spring Cloud Dalston中文文档

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,099评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,355评论 6 343
  • Spring Cloud学习02-服务注册与发现 Spring Cloud简介 Spring Cloud是一个基于...
    it_zzy阅读 4,520评论 2 20
  • 1 为什么需要服务发现 简单来说,服务化的核心就是将传统的一站式应用根据业务拆分成一个一个的服务,而微服务在这个基...
    谦小易阅读 24,979评论 4 93
  • 这是我自学彩铅画的第二幅画——葡萄 1.先用铅笔起稿 2.用红紫、枣红、深紫、深蓝先后刻画色彩丰富的葡萄粒 3.用...
    雨灵200601阅读 326评论 7 5