1. 程式人生 > 其它 >Spring Cloud 學習-下

Spring Cloud 學習-下

1.Spring Cloud 學習

  • Config 分散式配置中心
  • Bus 訊息匯流排
  • Stream 訊息驅動
  • Sleuth+Zipkin 鏈路追蹤

2.config

2.1-config-概述

• Spring Cloud Config 解決了在分散式場景下多環境配置檔案的管理和維護。
• 好處:
集中管理配置檔案
不同環境不同配置,動態化的配置更新
配置資訊改變時,不需要重啟即可更新配置資訊到服務

2.2-config-快速入門

2.2.1-gitee搭建遠端倉庫

1.編寫倉庫名稱、倉庫路徑、公開(公開的比較方便)

2.語言和模板可以不選,一般使用單分支模型,只建立master分支

3.使用小烏龜工具,將遠端倉庫clone到本地

4.使用小烏龜工具將配置檔案提交到遠端倉庫

2.2.2-config server搭建

config server:

  1. 使用gitee建立遠端倉庫,上傳配置檔案

  2. 搭建 config server 模組

  3. 匯入 config-server 依賴

    <dependencies>
        <!-- config-server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-config-server</artifactId>
        </dependency>
    </dependencies>
    
  4. 編寫配置,設定 gitee 遠端倉庫地址

server:
  port: 9527

spring:
  application:
    name: config-server
  # spring cloud config
  cloud:
    config:
      server:
        # git 的 遠端倉庫地址
        git:
          uri: https://gitee.com/itheima_cch/itheima-configs.git
      label: master # 分支配置

  1. 測試訪問遠端配置檔案

2.2.3-config client搭建

config client:

  1. 匯入 starter-config 依賴

       <!--config client -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-config</artifactId>
            </dependency>
    
  2. 配置config server 地址,讀取配置檔名稱等資訊

    建立配置檔案bootstrap.yml

    # 配置config-server地址
    # 配置獲得配置檔案的名稱等資訊
    spring:
      cloud:
        config:
          # 配置config-server地址
          uri: http://localhost:9527
          # 配置獲得配置檔案的名稱等資訊
          name: config # 檔名
          profile: dev # profile指定,  config-dev.yml
          label: master # 分支
    
  3. 獲取配置值

        @Value("${itheima}")
        private String itheima;
    
  4. 啟動測試

2.2.4-config client重新整理

  1. 在 config 客戶端引入 actuator 依賴

            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
    
  2. 獲取配置資訊類上,新增 @RefreshScope 註解

/**
 * Goods Controller 服務提供方
 */

@RestController
@RequestMapping("/goods")
@RefreshScope // 開啟重新整理功能
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @Value("${server.port}")
    private int port;


    @Value("${itheima}")
    private String itheima;
    ...
    }
  1. 新增配置management.endpoints.web.exposure.include: refresh
# 配置config-server地址
# 配置獲得配置檔案的名稱等資訊
spring:
  cloud:
    config:
      # 配置config-server地址
      uri: http://localhost:9527
      # 配置獲得配置檔案的名稱等資訊
      name: config # 檔名
      profile: dev # profile指定,  config-dev.yml
      label: master # 分支

management:
  endpoints:
    web:
      exposure:
        include: refresh

  1. 使用curl工具傳送post請求
    curl -X POST http://localhost:8001/actuator/refresh

2.3-config整合Eureka

1.config-server pom.xml中引入eureka-client 座標

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

2.配置檔案中配置eureka地址

eureka:
	client:
		service-url:
			defaultZone: http://localhost:8761/eureka/

3.啟動類中添加註解

package com.itheima.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.config.server.EnableConfigServer;

@SpringBootApplication
@EnableConfigServer // 啟用config server功能
@EnableEurekaClient
public class ConfigServerApp {

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

4.config-provider 工程中bootstrap.yaml中注掉寫死的地址,改為從Eureka中獲取

# 配置config-server地址
# 配置獲得配置檔案的名稱等資訊
spring:
  cloud:
    config:
      # 配置config-server地址
      #uri: http://localhost:9527
      # 配置獲得配置檔案的名稱等資訊
      name: config # 檔名
      profile: dev # profile指定,  config-dev.yml
      label: master # 分支
      #從註冊中心獲取config-server地址
      discovery:
      	enabled:true
      	service-id:CONFIG-SERVER

3.bus

3.1-bus-概述

• Spring Cloud Bus 是用輕量的訊息中介軟體將分散式的節點連線起來,可以用於廣播配置檔案的更改或者服務的監控管理。關鍵的思想就是,訊息匯流排可以為微服務做監控,也可以實現應用程式之間相通訊。

• Spring Cloud Bus 可選的訊息中介軟體包括 RabbitMQ 和 Kafka

3.2-bus-rabbitmq回顧

RabbitMQ 提供了 6 種工作模式:簡單模式、work queues、Publish/Subscribe 釋出與訂閱模式、Routing
路由模式、Topics 主題模式、RPC 遠端呼叫模式(遠端呼叫,不太算 MQ;暫不作介紹)。

RabbitMQ Window 安裝參考資料中RabbitMQ Windows 安裝.md

3.3-bus-快速入門

  1. 分別在 config-server 和 config-client中引入 bus依賴:bus-amqp

            <!-- bus -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-bus-amqp</artifactId>
            </dependency>
    
  2. 分別在 config-server 和 config-client中配置 RabbitMQ

    bootstrap.yml

      #配置rabbitmq資訊
      rabbitmq:
        host: localhost
        port: 5672
        username: guest
        password: guest
        virtual-host: /
    

OrderController上新增@RefreshScope註解

@RestController
@RequestMapping("/order")
@RefreshScope
public class OrderController {


    @Value("${itheima}")
    private String itheima;
    ...
    }
  1. 在config-server中設定暴露監控斷點:bus-refresh

    application.yml

    # 暴露bus的重新整理端點
    management:
      endpoints:
        web:
          exposure:
            include: 'bus-refresh'
    
  2. 啟動測試

    curl結果中沒有資訊,說明成功了

4.stream

4.1-stream-概述

• Spring Cloud Stream 是一個構建訊息驅動微服務應用的框架。
• Stream 解決了開發人員無感知的使用訊息中介軟體的問題,因為Stream對訊息中介軟體的進一步封裝,可以做
到程式碼層面對中介軟體的無感知,甚至於動態的切換中介軟體,使得微服務開發的高度解耦,服務可以關注更多
自己的業務流程。
• Spring Cloud Stream目前支援兩種訊息中介軟體RabbitMQ和Kafka

4.2-stream-元件

• Spring Cloud Stream 構建的應用程式與訊息中介軟體之間是通過繫結器 Binder相關聯的。繫結器對於應用程式而言起到了隔離作用, 它使得不同訊息中介軟體的實現細節對應用程式來說是透明的。

• binding 是我們通過配置把應用和spring cloud stream 的 binder 繫結在一起

• output:傳送訊息 Channel,內建 Source介面

• input:接收訊息 Channel,內建 Sink介面

4.3-stream-訊息生產者

  1. 建立訊息生產者模組,引入依賴 starter-stream-rabbit

            <!-- stream -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
            </dependency>
    
  2. 編寫配置,定義 binder,和 bingings

    server:
      port: 8000
    spring:
      cloud:
        stream:
          # 定義繫結器,繫結到哪個訊息中介軟體上
          binders:
            itheima_binder: # 自定義的繫結器名稱
              type: rabbit # 繫結器型別
              environment: # 指定mq的環境
                spring:
                  rabbitmq:
                    host: localhost
                    port: 5672
                    username: guest
                    password: guest
                    virtual-host: /
          bindings:
            output: # channel名稱
              binder: itheima_binder #指定使用哪一個binder
              destination: itheima_exchange # 訊息目的地
    
    
  3. 定義訊息傳送業務類。新增 @EnableBinding(Source.class),注入
    MessageChannel output ,完成訊息傳送

MessageProducer

package com.itheima.stream.producer;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

@Component
@EnableBinding(Source.class)
public class MessageProducer {

    @Autowired
    private MessageChannel output;

    public void send(){
        String msessage = "hello stream~~~";

        //傳送訊息
        output.send(MessageBuilder.withPayload(msessage).build());

        System.out.println("訊息傳送成功~~~");

    }
}

ProducerController

package com.itheima.stream.producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ProducerController {

    @Autowired
    private MessageProducer producer;

    @RequestMapping("/send")
        public String sendMsg(){
        producer.send();
        return "success";
    }
}

  1. 編寫啟動類,測試
package com.itheima.stream;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProducerApp {
    public static void main(String[] args) {

        SpringApplication.run(ProducerApp.class,args);
    }
}

4.4-stream-訊息消費者

  1. 建立訊息消費者模組,引入依賴 starter-stream-rabbit

            <!-- stream -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-stream-rabbit</artifactId>
            </dependency>
    
  2. 編寫配置,定義 binder,和 bingings

    server:
      port: 9000
    spring:
      cloud:
        stream:
          # 定義繫結器,繫結到哪個訊息中介軟體上
          binders:
            itheima_binder: # 自定義的繫結器名稱
              type: rabbit # 繫結器型別
              environment: # 指定mq的環境
                spring:
                  rabbitmq:
                    host: localhost
                    port: 5672
                    username: guest
                    password: guest
                    virtual-host: /
          bindings:
            output: # channel名稱
              binder: itheima_binder #指定使用哪一個binder
              destination: itheima_exchange # 訊息目的地
    
    
  3. 定義訊息接收業務類。新增 @EnableBinding(Sink.class),使用
    @StreamListener(Sink.INPUT),完成訊息接收。

package com.itheima.stream.consumer;

import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.messaging.Sink;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 訊息接收類
 */
@EnableBinding({Sink.class})
@Component
public class MessageListener {

    @StreamListener(Sink.INPUT)
    public void receive(Message message){

        System.out.println(message);
        System.out.println(message.getPayload());
    }
}

  1. 編寫啟動類,測試
package com.itheima.stream;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConsumerApp {
    public static void main(String[] args) {

        SpringApplication.run(ConsumerApp.class,args);
    }
}

5.Sleuth+Zipkin

5.1-Sleuth+Zipkin-概述

• Spring Cloud Sleuth 其實是一個工具,它在整個分散式系統中能跟蹤一個使用者請求的過程,捕獲這些跟蹤數
據,就能構建微服務的整個呼叫鏈的檢視,這是除錯和監控微服務的關鍵工具。
• 耗時分析
• 視覺化錯誤
• 鏈路優化
• Zipkin 是 Twitter 的一個開源專案,它致力於收集服務的定時資料,以解決微服務架構中的延遲問題,包
括資料的收集、儲存、查詢和展現。

5.2-Sleuth+Zipkin-快速入門

  1. 安裝啟動zipkin。 java –jar zipkin.jar

​ 啟動成功日誌

  1. 訪問zipkin web介面。 http://localhost:9411/
  1. 在服務提供方和消費方分別引入 sleuth 和 zipkin 依賴
        <!-- sleuth-zipkin -->
        <!--<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-sleuth</artifactId>
        </dependency>-->

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zipkin</artifactId>
        </dependency>
  1. 分別配置服務提供方和消費方。

sleuth-provider application.yaml

server:
  port: 8001

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: feign-provider
  zipkin:
    base-url: http://localhost:9411/  # 設定zipkin的服務端路徑

  sleuth:
    sampler:
      probability: 1 # 採集率 預設 0.1 百分之十。


sleuth-consumer application.yaml

server:
  port: 9000


eureka:
  instance:
    hostname: localhost # 主機名
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka
spring:
  application:
    name: feign-consumer # 設定當前應用的名稱。將來會在eureka中Application顯示。將來需要使用該名稱來獲取路徑
  zipkin:
    base-url: http://localhost:9411/  # 設定zipkin的服務端路徑

  sleuth:
    sampler:
      probability: 1 # 採集率 預設 0.1 百分之十。


logging:
  level:
    com.itheima: debug


  1. 啟動,測試 http://localhost:9411/

詳細資訊