1. 程式人生 > >一、服務治理:Spring Cloud Eureka

一、服務治理:Spring Cloud Eureka

rest app module ribbon service 分享 chl 自己的 註冊服務

核心內容:

  1. 構建服務註冊中心
  2. 服務註冊於服務發現
  3. Eureka的基礎架構
  4. Eureka的服務治理機制
  5. Eureka的配置

服務治理:主要是用來實現各個微服務實例的自動化註冊與發現

服務註冊:在服務治理框架中,通常會構建一個註冊中心,每個服務單元向註冊中心登記自己的提供的服務,將主機與端口號、版本號、通信協議等一些信息告訴給註冊中心,註冊中心按服務名分類組織服務清單。 

  eg:  

技術分享圖片

另外,服務註冊中心還需要以心跳的方式去監測清單中的服務是否可用,若不可用需要從服務清單中踢出

服務發現:由於在服務治理框架下運作,服務間的調用不再通過制定具體的實例地址來實現,而是通過向服務名發起請求調動實現。

  步驟:1、調用方向服務註冊中心獲取所有服務的實例清單

     2、輪詢取出清單中的一個進行服務調用(負載均衡)


搭建服務註冊中心:

  1、添加依賴:

<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.SR1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>    --springboot版本和springCloud版本需要配對喲
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

  2、通過@EnableEurekaServer註解啟動一個服務註冊中心,提供給其他應用進行對話

  3、添加配置
    server.port=1111
    eureka.instance.hostname=localhost
    eureka.client.register-with-eureka=false  --由於該應用為註冊中心,所以設置為false,代表不想註冊中心註冊自己
    eureka.client.fetch-registry=false  --由於註冊中心的職責就是維護服務實例,它並不需要檢索服務,所以也設置為false
    eureka.client.service-url.defaultZone=http://${eureka.instance.hostname}:${server.port}/eureka/
  4、啟動項目訪問:http://localhost:1111

技術分享圖片



註冊服務提供者
  把一個springBoot應用加入Eureka的服務治理體系中去
1、新建一個module
2、加入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
3、在啟動類上加上@EnableEurekaClient註解
4、添加配置文件
spring.application.name=hello-service
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/

技術分享圖片


高可用註冊中心
  在Eureka的服務治理設計中,所有節點既是服務提供方,也是服務消費方,服務註冊中心也不例外。
  Eureka Server的高可用實際上就是將自己作為服務,想其他服務註冊中心註冊自己(相互註冊)
搭建:

技術分享圖片

有了多個註冊中心之後,修改服務提供者和服務消費者:
eureka.client.service-url.defaultZone=http://localhost:1111/eureka/,http://localhost:1112/eureka/

現在已經有了服務註冊中心和服務消費者,現在需要一個服務提供者。服務發現的任務由Eureka的客戶端完成,服務消費的任務由Ribbon完成
和原來的hello-service基本一致,在依賴中加入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
</dependency>
在配置類中加入RestTemplate,並加上@LoadBalanced用戶負載均衡
最後,調用hello-service裏面的服務
@Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/ribbon-consumer")
    public String helloConsumer(){
        return restTemplate.getForEntity("http://hello-service/hello", String.class).getBody();
    }

啟動ribbon-consumer,請求兩次/ribbon-consumer,可以看到在兩個控制臺一次打印信息

在ribbon-consumer還能看到被調用者信息

技術分享圖片


一、服務治理:Spring Cloud Eureka