1. 程式人生 > >03.Spring Cloud學習筆記之服務註冊與服務發現元件Eureka

03.Spring Cloud學習筆記之服務註冊與服務發現元件Eureka

前言

從本篇部落格開始將正式進入Spring Cloud的實戰部分,因為博主用了很長時間的Dubbo,並且Spring Cloud和Dubbo都是微服務框架,它們有很多相似之處,所以可能在部落格中提及進行類比,如果沒有接觸過Dubbo的朋友直接略過該部分內容即可,大可不必糾結

在微服務架構中服務治理可以說是最核心和基礎的模組,它主要用來實現各個微服務例項的自動註冊和發現,在Dubbo中主要使用Zookeeper來進行服務間的協調,在Spring Cloud中Eureka則扮演著服務治理的角色(Sping Cloud也支援Zookeeper作為註冊中心方式,但不是最佳實踐,建議感興趣的朋友自行搜尋Zookeeper與Eureka的對比)

搭建服務註冊中心

新建一個基礎Spring Boot工程,在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> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> <relativePath/> </parent> <groupId>
com.roberto.springcloud</groupId> <artifactId>eureka-server</artifactId> <version>1.0.0-SNAPSHOT</version> <packaging>jar</packaging> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka-server</artifactId> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>Dalston.SR2</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>

啟動類新增@EnableEurekaServer註解

package com.roberto.springboot;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer;

@EnableEurekaServer
@SpringBootApplication
public class SpringbootQuickStartApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootQuickStartApplication.class, args);
    }
}

在application.yml下新增Eureka的配置

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

eureka.client.register-with-eureka 表示是否將自己註冊到Eureka Server,預設值為true,由於此處為單機版Eureka Server所以設定為false,表示不向註冊中心註冊自己

eureka.client.fetch-registry 表示是否從Eureka Server獲取註冊資訊,預設為true,因為這是一個單點的Eureka Server,不需要同步其他的Eureka Server節點的資料,故而設為false

eureka.client.serviceUrl.defaultZone 表示與Eureka Server互動的地址,查詢服務和註冊服務都需要依賴這個地址。預設是http://localhost:8761/eureka,多個地址可使用 , 分隔

建立父工程用於繼承

由於後續很多DEMO都要引入Spring Boot和Spring Cloud依賴,為了避免重複依賴並且為了統一管理版本號,此處新增父工程用於子模組繼承,父工程的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>

    <groupId>com.roberto.springcloud</groupId>
    <artifactId>spring-cloud-parent</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <packaging>pom</packaging>

    <modules>
        <module>spring-cloud-user-service</module>
        <module>spring-cloud-movie-service</module>
    </modules>

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

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.SR2</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

註冊服務提供者

新建子模組,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>

    <parent>
        <artifactId>spring-cloud-parent</artifactId>
        <groupId>com.roberto.springcloud</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>spring-cloud-user-service</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
    </dependencies>
</project>

新增啟動類新增@EnableEurekaClient註解

package com.roberto.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@EnableEurekaClient
@SpringBootApplication
public class SpringCloudUserService {
    public static void main(String args[]) {
        SpringApplication.run(SpringCloudUserService.class, args);
    }
}

Controller層

package com.roberto.springcloud.controller;

import com.roberto.springcloud.repository.UserRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class UserController {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Resource(name = "discoveryClient")
    private DiscoveryClient discoveryClient;

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    public String index() {
        ServiceInstance serviceInstance = discoveryClient.getLocalServiceInstance();
        LOGGER.info("/hello,host:" + serviceInstance.getHost() + ",service_id:" + serviceInstance.getServiceId());
        return "Hello World";
    }
}

修改配置檔案application.yml

spring:
  application:
    name: user-service
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

spring.application.name 為服務命名
eureka.client.serviceUrl.defaultZone 指定註冊中心地址

啟動專案訪問Eureka資訊面板 發現user-service已經註冊成功
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>

    <parent>
        <artifactId>spring-cloud-parent</artifactId>
        <groupId>com.roberto.springcloud</groupId>
        <version>1.0.0-SNAPSHOT</version>
    </parent>

    <artifactId>spring-cloud-movie-service</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
    </dependencies>
</project>

啟動類新增@EnableEurekaClient註解 並注入RestTemplate

package com.roberto.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@EnableEurekaClient
@SpringBootApplication
public class SpringCloudMovieService {
    @Bean
    @LoadBalanced
    RestTemplate restTemplate(){
        return new RestTemplate();
    }

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

Controller層

package com.roberto.springcloud.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

@RestController
public class MovieController {
    @Resource(name = "restTemplate")
    private RestTemplate restTemplate;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
        return restTemplate.getForEntity("http://user-service/hello", String.class).getBody();
    }
}

修改配置檔案application.yml

server:
  port: 9090
spring:
  application:
    name: movie-service
eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/

至此服務消費者已經建立成功

Eureka高可用

在分散式環境中為了避免系統故障引發一系列問題,我們必須對各個元件進行高可用部署。Eureka的高可用實際就是將自己作為服務向其他註冊中心註冊自己,這樣就可以形成一組相互註冊的服務註冊中心,以實現服務清單的同步,達到高可用效果。由於機器數量限制本次搭建為Eureka的偽叢集

修改host檔案 新增如下配置

127.0.0.1       peer1 peer2 peer3

修改Eureka的application.yml檔案如下

spring:
  application:
    name: EUREKA-HA

---
server:
  port: 8761
spring:
  profiles: peer1
eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: http://peer2:8762/eureka/,http://peer3:8763/eureka/

---
server:
  port: 8762
spring:
  profiles: peer2
eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: http://peer1:8761/eureka/,http://peer3:8763/eureka/
---
server:
  port: 8763
spring:
  profiles: peer3
eureka:
  instance:
    hostname: peer3
  client:
    serviceUrl:
      defaultZone: http://peer1:8761/eureka/,http://peer2:8762/eureka/

新增啟動引數 分別啟動三個Eureka例項

-Dspring.profiles.active=peer

訪問Eureka資訊面板如下圖所示表明HA環境搭建成功
Eureka資訊面板

注:在HA環境下無需配置eureka.client.register-with-eureka與eureka.client.fetch-registry屬性 預設為true

Eureka的安全配置

為了服務註冊中心的安全考慮,很多時候我們都會為服務註冊中心加入安全校驗,過程如下

在pom.xml新增Security依賴

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

修改application.yml檔案 新增security配置

spring:
  application:
    name: EUREKA-HA

---
spring:
  profiles: peer1
server:
  port: 8761
security:
  basic:
    enabled: true
  user:
    name: roberto
    password: roberto123
eureka:
  instance:
    hostname: peer1
  client:
    serviceUrl:
      defaultZone: http://roberto:[email protected]:8762/eureka/,http://roberto:[email protected]:8763/eureka/

---
spring:
  profiles: peer2
server:
  port: 8762
security:
  basic:
    enabled: true
  user:
    name: roberto
    password: roberto123
eureka:
  instance:
    hostname: peer2
  client:
    serviceUrl:
      defaultZone: http://roberto:[email protected]:8761/eureka/,http://roberto:[email protected]:8763/eureka/

---
spring:
  profiles: peer3
server:
  port: 8763
security:
  basic:
    enabled: true
  user:
    name: roberto
    password: roberto123
eureka:
  instance:
    hostname: peer3
  client:
    serviceUrl:
      defaultZone: http://roberto:[email protected]:8761/eureka/,http://roberto:[email protected]:8762/eureka/

注:在配置serviceUrl時,需要在value值的URL中加入相應的安全校驗資訊,格式為http://<username>:<password>@hostname:port/eureka,其中username為使用者名稱,password為密碼,hostname為主機名或IP地址,port為埠號

其他服務例項連線到Eureka時可以通過如下配置進行授權

@Bean
public BasicAuthRequestInterceptor basicAuthRequestInterceptor() {
    return new BasicAuthRequestInterceptor("roberto", "roberto123");
}

自定義Eureka的Instance ID

在Spring Cloud中,服務的Instance ID的預設值是${spring.cloud.client.hostname}:${spring.application.name}:${spring.application.instance_id:${server.port}},也就是機器主機名:應用名稱:應用埠 。因此在Eureka Server首頁中看到的服務的資訊類似如下:localhost:EUREKA-HA:8763,如需自定義該部分資訊只需在application.yml中新增如下配置

eureka:
  instance:
    preferIpAddress: true
    instance-id: ${spring.cloud.client.ipAddress}:${server.port}

Eureka配置屬性

Eureka涉及到的引數配置項數量眾多,詳細可參見Eureka配置屬性

Eureka配置所在類

org.springframework.cloud.netflix.eureka.EurekaInstanceConfigBean
org.springframework.cloud.netflix.eureka.EurekaClientConfigBean
org.springframework.cloud.netflix.eureka.server.EurekaServerConfigBean

相關推薦

03.Spring Cloud學習筆記服務註冊服務發現元件Eureka

前言 從本篇部落格開始將正式進入Spring Cloud的實戰部分,因為博主用了很長時間的Dubbo,並且Spring Cloud和Dubbo都是微服務框架,它們有很多相似之處,所以可能在部落格中提及進行類比,如果沒有接觸過Dubbo的朋友直接略過該部分內容即

Spring Cloud學習筆記Eureka Server註冊中心

Eureka Server提供服務註冊服務,各個節點啟動後,會在Eureka Server中進行註冊,這樣EurekaServer中的服務登錄檔中將會儲存所有可用服務節點的資訊,服務節點的資訊可以在介面中直觀的看到。我們簡單實現一下Eureka Server。 1.新建一個Maven專案

06.Spring Cloud學習筆記宣告式服務呼叫元件Feign

前言 Spring Cloud Feign基於Netflix Feign實現,整合了Spring Cloud Ribbon與Spring Cloud Hystrix,除了提供這兩者的強大功能外,還提供了一種宣告式的Web服務客戶端定義方式,我們可以做到使用HT

Spring Cloud學習筆記Eureka框架的原理

Eureka 服務發現與註冊:我們在呼叫微服務的時候,如果我們的微服務部署了多份,我們應該如何去呼叫?這裡就涉及到了服務發現與註冊。服務發現就是程式如何通過一個標誌來獲取服務列表,並且這個服務列表是能夠隨著服務的狀態而動態變更的。 Spring Cloud提供了多種註冊中心的支援:如Eur

Spring Cloud學習筆記微服務實現(一)(Spring Boot+IDEA)

我們先使用Spring Boot實現一個微服務,業務非常簡單: 1.商品微服務,通過商品id查詢商品的微服務 2.訂單微服務,通過訂單id查詢訂單資料,同時需要呼叫商品微服務查詢出訂單詳情資料對應的商品資料。 說明: 1.對於商品微服務而言,商品微服務是服務的提供者,訂單微服務是服務的消費

Spring Cloud學習筆記微服務實現(二)(Spring Boot+Spring Cloud+IDEA)

在【Spring Cloud學習筆記之微服務實現(一)】中,我們實現了微服務,但是在實際的專案中,我們需要實現動態訪問微服務,在此之前,已經介紹了Spring Cloud和Eureka,並且實現了eureka註冊中心。現在我們實現一下動態呼叫。 注:註冊中心的服務在此期間保持啟動狀態。

android學習筆記客戶端服務端保持session登入狀態

剛進公司不久,也沒有具體專案任務,只有一個混合開發模式,使用AppCan開發的專案。 雖然混合開發很便捷、很高效,使用html和js就可以完成。 但我依然對android原生開發有著極高的熱情,尤其是在體驗了Android 5.0版本之後,更是對原生體驗著迷。 所以,我利用

Spring Cloud學習筆記(三)——服務發現消費使用Ribbon

服務消費一般使用ribbon和feign兩種方式。而feign實際上也是以ribbon為基礎的。有多個服務提供者例項的情況下ribbon可以實現負載均衡。 1.pom檔案:這裡與服務提供者不同的是需要引入ribbon包。 <dependency>

Spring Cloud學習筆記(四)——服務發現消費使用Feign

Feign 是一個宣告web服務客戶端,這便得編寫web服務客戶端更容易,使用Feign 建立一個介面並對它進行註解,它具有可插拔的註解支援包括Feign註解與JAX-RS註解,Feign還支援可插拔的編碼器與解碼器,Spring Cloud 增加了對 Spring MVC的

Sprng Cloud學習筆記單體架構和微服務架構

微服務架構 目前微服務是非常火的架構或者說概念,也是在構建大型網際網路專案時採用的架構方式。 單體架構 一個歸檔包(可以是JAR、WAR、EAR或其它歸檔格式)包含所有功能的應用程式,通常稱為單體應用。單體架構中,所有的業務模組都編寫在一個專案中,最終打成war包執行。 軟體設計

Sprng Cloud學習筆記Spring Cloud簡介

Spring Cloud Spring Cloud是一系列框架的有序集合(Spring Cloud並不是一個專案,它是一套專案的組合)。它利用Spring Boot的開發便利性巧妙地簡化了分散式系統基礎設施的開發,如服務發現註冊、配置中心、訊息匯流排、負載均衡、斷路器、資料監控等,都可以

Spring Cloud學習筆記16——微服務的消費

微服務的消費模式 基於http的客戶端經常被用作微服務的消費者,因為http本身是平臺無關的、語言無關的,所以基於http的客戶端往往會被廣大的社群支援 服務直連模式 特點: 簡潔明瞭,只要傳入一個URL,就能直接連過去,獲取到資源 平臺語言無關性,非常直白,不

Spring Cloud 學習筆記二(服務發現消費)

配置高可用註冊中心 Eureka Server 的高可用就是指將服務註冊中心本身向其他服務註冊中心註冊自己,這樣就可以實現服務清單的同步,增強系統可用性,而不是單節點的服務註冊中心。 在學習筆記一里,我們設定過如下兩個引數 eureka.client.regis

Spring Cloud學習筆記28——訊息驅動的微服務Spring Cloud Stream

Spring Cloud Stream是一個用來為微服務應用構建訊息驅動能力的框架。它可以基於Spring Boot來建立獨立的、可用於生產的Spring應用程式。它通過使用Spring Integration來連線訊息代理中介軟體以實現訊息事件驅動。Spring Cloud Stream為

Spring Cloud學習筆記26——Spring Cloud服務實戰

微服務構建:Spring Boot 構建Maven專案 通過官方的Spring Initializr工具來產生基礎專案。 下載並解壓生成的專案壓縮包,並用IDE以Maven專案匯入,以Intellij IDEA為例。 單擊Import project fro

Spring Cloud學習筆記11——天氣預報系統微服務(5)城市資料 API 微服務

開發環境 JDK8+ Gradle4+ Spring Boot Web Starter 建立專案 新建專案資料夾: 將micro-weather-report專案中的原始碼檔案複製貼上到新專案資料夾中: 修改原始碼 修改build.gradle配置,刪除

spring-cloud學習筆記Eureka註冊中心(四)修改成IP顯示

修改配置類 eureka: instance: #使用IP訪問註冊中心 prefer-ip-address: true #在註冊中心status的時候顯示的格式,這裡是 ip:埠 instance-id: ${spring.cloud.c

Spring Cloud 學習筆記(一) -服務治理

Spring Cloud Eureka 服務治理 服務治理可以說是SpringCloud微服務架構中最為核心核基礎的模組, 它主要實現各個微服務例項的自動化註冊和發現。 服務註冊: 在服務框架中, 通常會構建一個註冊中心,每個服務啟動時向註冊中心登記自己提供的

Spring Cloud學習筆記1——服務治理(Eureka

1、搭建服務註冊中心 1)新建一個Spring Boot專案,取名為EurekaServer,程式碼見碼雲:https://gitee.com/wudiyong/EurekaServer.git,然後在pom.xml檔案中加入依賴: <parent> &

我的第一個spring boot程序(spring boot 學習筆記二)

獲取json 了解 訪問 static 依賴 過程 public 獲取數據 gap 第一個spring boot程序 寫在前面:鑒於spring註解以及springMVC的配置有大量細節和知識點,在學習理解之後,我們將直接進入spring boot的學習,在後續學習中用到註