Spring Cloud Eureka 初探

Eureka介紹

Spring Cloud Eureka 是 Spring Cloud Netflix 微服務套件的一部分,基於 Netflix Eureka 作了二次封裝,主要負責完成微服務架構中的服務治理功能。git

除了用Eureka來作註冊中心,咱們還可使用Consul,Etcd,Zookeeper等等來做爲服務的註冊中心。github

有用過dubbo的同窗應該清楚,dubbo中也有幾種註冊中心,有基於Zookeeper的,有基於redis的等等,用的最多的仍是Zookeeper方式。redis

至於使用哪一種方式,其實都是能夠的,註冊中心無非就是管理全部服務的信息和狀態。spring

用咱們生活中的列子來講明的話,我以爲12306比較合適。服務器

首先12306就比如一個註冊中心,N量火車都註冊在了12306上面,咱們顧客就比如調用的客戶端,當咱們須要坐火車時,咱們會去12306上看有沒有票,有票就能夠購買,而後拿到火車的班次,時間等等,最後出發。架構

程序也是同樣,當你須要調用某一個服務的時候,你會先去Eureka中去拉取服務列表,查看你調用的服務在不在其中,在的話就拿到服務地址,端口,等等信息,而後調用。app

註冊中心帶來的好處就是你不須要知道有多少提供方,你只須要關注註冊中心便可,你沒必要關係有多少火車在運行,你只須要去12306上看有沒有票能夠買就能夠。maven

Spring Cloud中使用Eureka

<!-- Spring Boot -->
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
        <relativePath />
</parent>
<dependencies>
       <!-- eureka -->
       <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
       </dependency>
</dependencies>
<!-- Spring Cloud -->
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
</dependencyManagement>
  • 接着建立一個啓動類
/**
 * 服務註冊中心
 * 
 * @author yinjihuan
 *
 */
@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {
    
    public static void main(String[] args) {
        SpringApplication.run(EurekaServerApplication.class, args);
    }
    
}
  • 編寫配置文件application.properties
server.port=8761
spring.application.name=fangjia-eureka
eureka.instance.hostname=localhost
# 因爲該應用爲註冊中心,因此設置爲false,表明不向註冊中心註冊本身
eureka.client.register-with-eureka=false
# 因爲註冊中心的職責就是維護服務實例,他並不須要去檢索服務,因此也設置爲false
eureka.client.fetch-registry=false
# 關閉自我保護
eureka.server.enableSelfPreservation=false

最後啓動EurekaServerApplication,訪問http://localhost:8761/就能夠打開管理頁面了。spring-boot

具體代碼能夠參考個人github:微服務

https://github.com/yinjihuan/spring-cloud

相關文章
相關標籤/搜索