Spring Cloud 初識

簡介:Spring Cloud是在Spring Boot的基礎上構建的,用於簡化分佈式系統構建的工具集,爲開發人員提供快速創建分佈式系統中的一些常見的模式。php

    例如:配置管理(configuration management),服務發現(service discovery),斷路器(circuit breakers),智能路由( intelligent routing),html

    微代理(micro-proxy),控制總線(control bus),一次性令牌( one-time tokens),全局鎖(global locks),領導選舉(leadership election),java

    分佈式會話(distributed sessions),集羣狀態(cluster state)。git

Spring Cloud 包含了多個子項目:github

   例如:Spring Cloud Config、Spring Cloud Netflix等spring

Spring Cloud 項目主頁:http://projects.spring.io/spring-cloud/apache

關於服務發現

      在微服務架構中,服務發現(Service Discovery)是關鍵原則之一。手動配置每一個客戶端或某種形式的約定是很難作的,而且很脆弱。Spring Cloud提供了多種服務發現的實現方式,session

例如:Eureka、Consul、Zookeeper。 Spring Cloud支持得最好的是Eureka,其次是Consul,最次是Zookeeper。架構

  • 在生產環境下,咱們每每會爲每一個應用配置一個host,使用host而非IP進行訪問。爲了更加貼近生產環境,以及後文Docker章節的講解,咱們首先配置一下Host

代碼示例

  • 建立一個Maven工程(microservice-discovery-eureka),並在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> <artifactId>microservice-discovery-eureka</artifactId> <packaging>jar</packaging> <parent> <groupId>com.itmuch.cloud</groupId> <artifactId>spring-cloud-microservice-study</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> </dependencies> </project> 
  • 編寫Spring Boot啓動程序:經過@EnableEurekaServer申明一個註冊中心:
/** * 使用Eureka作服務發現。 * @author eacdy */ @SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
  • 在默認狀況下,Eureka會將本身也做爲客戶端嘗試註冊,因此在單機模式下,咱們須要禁止該行爲,只須要在application.yml中以下配置:
server:  port: 8761 # 指定該Eureka實例的端口 eureka:  instance:  hostname: discovery # 指定該Eureka實例的主機名  client:  registerWithEureka: false  fetchRegistry: false  serviceUrl:  defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
# 參考文檔:http://projects.spring.io/spring-cloud/docs/1.0.3/spring-cloud.html#_standalone_mode
# 參考文檔:http://my.oschina.net/buwei/blog/618756

  啓動工程後,訪問:http://discovery:8761/ ,以下圖。咱們會發現此時尚未服務註冊到Eureka上面。app

 

Eureka啓動界面

 

代碼地址(任選其一)

http://git.oschina.net/itmuch/spring-cloud-study/tree/master/microservice-discovery-eureka

https://github.com/eacdy/spring-cloud-study/tree/master/microservice-discovery-eureka

相關文章
相關標籤/搜索