Spring Cloud第一章 服務註冊中心 Eureka

Spring Cloud簡介

Spring Cloud是一個基於Spring Boot實現的雲應用開發工具,它爲基於JVM的雲應用開發中涉及的配置管理、服務發現、斷路器、智能路由、微代理、控制總線、全局鎖、決策競選、分佈式會話和集羣狀態管理等操作提供了一種簡單的開發方式。

Spring Cloud包含了多個子項目(針對分佈式系統中涉及的多個不同開源產品),比如:Spring Cloud Config、Spring Cloud Netflix、Spring Cloud0 CloudFoundry、Spring Cloud AWS、Spring Cloud Security、Spring Cloud Commons、Spring Cloud Zookeeper、Spring Cloud CLI等項目。

微服務架構

“微服務架構”在這幾年非常的火熱,以至於關於微服務架構相關的開源產品被反覆的提及(比如:netflix、dubbo),Spring Cloud也因Spring社區的強大知名度和影響力也被廣大架構師與開發者備受關注。

那麼什麼是“微服務架構”呢?簡單的說,微服務架構就是將一個完整的應用從數據存儲開始垂直拆分成多個不同的服務,每個服務都能獨立部署、獨立維護、獨立擴展,服務與服務間通過諸如RESTful API的方式互相調用。

服務治理

在簡單介紹了Spring Cloud和微服務架構之後,下面迴歸本文的主旨內容,如何使用Spring Cloud來實現服務治理。

由於Spring Cloud爲服務治理做了一層抽象接口,所以在Spring Cloud應用中可以支持多種不同的服務治理框架,比如:Netflix Eureka、Consul、Zookeeper。在Spring Cloud服務治理抽象層的作用下,我們可以無縫地切換服務治理實現,並且不影響任何其他的服務註冊、服務發現、服務調用等邏輯。

Spring Cloud Eureka

首先,我們來嘗試使用Spring Cloud Eureka來實現服務治理。

Spring Cloud Eureka是Spring Cloud Netflix項目下的服務治理模塊。而Spring Cloud Netflix項目是Spring Cloud的子項目之一,主要內容是對Netflix公司一系列開源產品的包裝,它爲Spring Boot應用提供了自配置的Netflix OSS整合。通過一些簡單的註解,開發者就可以快速的在應用中配置一下常用模塊並構建龐大的分佈式系統。它主要提供的模塊包括:服務發現(Eureka),斷路器(Hystrix),智能路由(Zuul),客戶端負載均衡(Ribbon)等。

  • [ ]
  • [ ]

引入eureka -server依賴

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

在啓動類添加 @EnableEurekaServer註解


@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {

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

}

配置application.yml 文件

server:
  port: 8000   //設置eureka端口

eureka:
  instance:
    hostname: localhost
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/

啓動服務 訪問端口 http://localhost:8000/

在這裏插入圖片描述

 注  :服務中心 搭建完成

下面搭建client

引入eureka-client 依賴

	    <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
注:依賴spring-cloud-starter-netflix-eureka-client,標識它是一個客戶端服務實例;

在啓動類添加 @EnableEurekaClient 註解

@SpringBootApplication
@EnableEurekaClient
public class ClientApplication {

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

}

配置yml文件

server:
  port: 8081
eureka:
  client:
    serviceUrl:
     defaultZone: http://localhost:8761/eureka/

訪問端口

在這裏插入圖片描述

出現圖上圈出的 eureka 搭建完成

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章