深入淺出SpringCloud

SpringCloud是一組微服務架構的框架,由Spring官方提供,它基於SpringBoot提供了一系列微服務治理工具,如服務註冊與發現、配置中心、斷路器、網關等等,使得微服務架構開發變得更加容易。下面將從不同的角度來介紹SpringCloud的一些關鍵概念和用法。

一、服務註冊與發現

服務註冊與發現是微服務最基本的功能之一,SpringCloud提供了Eureka和Consul兩個註冊中心。下面以Eureka為例,更深入地介紹如何使用服務註冊和發現機制。

1. 註冊Eureka Server

第一步是註冊一個Eureka Server,我們可以在pom.xml中加入下面的依賴:


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

然後,我們可以通過@Configuration來啟用Eureka Server。下面是一個簡單的實現:


@Configuration
@EnableEurekaServer
public class EurekaServerConfig {

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

}

啟動程序後,訪問http://localhost:8761可以看到Eureka Server的控制台。

2. 註冊Eureka Client

有了Eureka Server,我們可以在各自的服務中註冊Eureka Client。下面是示例代碼:


// 添加Eureka Client 依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

// 在程序啟動類上添加@EnableDiscoveryClient註解
@SpringBootApplication
@EnableDiscoveryClient
public class EurekaClientApplication {

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

}

啟動Eureka Client程序後,我們可以在Eureka Server的控制台上看到它的註冊信息。

二、配置中心

在微服務架構中,配置中心起着至關重要的作用。SpringCloud提供了Config Server與Config Client實現了分佈式集中式配置的功能,下面我們來看一下如何使用。

1. 註冊Config Server

第一步是還是加入SpringCloud Config Server的依賴:


<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-config-server</artifactId>
</dependency>

然後,我們可以通過@EnableConfigServer註解啟用Config Server,下面是一個簡單的實現:


@SpringBootApplication
@EnableConfigServer
public class ConfigServerApplication {

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

}

Config Server需要配置一個Git或SVN倉庫。我們可以在application.properties或者application.yml文件中配置,如下面所示:


spring.cloud.config.server.git.uri=https://git.example.com/config-repo
spring.cloud.config.server.git.username=
spring.cloud.config.server.git.password=
spring.cloud.config.server.git.search-paths=config
spring.cloud.config.server.git.clone-on-start=true

2. 註冊Config Client

接下來,我們需要在各個服務中註冊Config Client。同樣,我們先添加依賴,在程序啟動類上添加@EnableConfigClient註解,示例代碼如下:


// 添加依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-config</artifactId>
</dependency>

// 在程序啟動類上添加@EnableConfigClient註解
@SpringBootApplication
@EnableDiscoveryClient
@EnableConfigClient
public class ConfigClientApplication {

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

}

接着,在bootstrap.properties或者bootstrap.yml文件中添加關於Config Server的配置,如下面所示:


server.port=8080

spring.cloud.config.uri=http://config-server.example.com
spring.application.name=myapp
spring.profiles.active=dev
spring.cloud.config.label=master

啟動Config Client程序後,它會自動從Config Server中獲取配置文件,並將配置文件中的屬性注入到應用程序中。

三、斷路器

斷路器是為了處理微服務中的容錯和彈性而出現,SpringCloud提供了Hystrix來實現斷路器的功能。

1. 註冊Hystrix Dashboard

在使用Hystrix之前,我們可以先搭建一個Hystrix Dashboard用於監控各個服務的運行情況。示例代碼如下:


// 添加Hystrix Dashboard依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix-dashboard</artifactId>
</dependency>

// 在程序啟動類上添加@EnableHystrixDashboard註解
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication {

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

}

啟動Hystrix Dashboard後,我們可以訪問http://localhost:8080/hystrix查看Dashboard。

2. 使用斷路器

在服務中使用Hystrix非常簡單,我們只需要使用@EnableCircuitBreaker註解和使用@HystrixCommand註解即可實現,示例代碼如下:


// 添加Hystrix依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>

// 在程序啟動類上添加@EnableCircuitBreaker註解
@SpringBootApplication
@EnableDiscoveryClient
@EnableCircuitBreaker
public class ServiceApplication {

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

    @Autowired
    private ServiceClient serviceClient;

    @HystrixCommand(fallbackMethod = "fallback")
    public String hello() {
        return serviceClient.hello();
    }

    public String fallback() {
        return "fallback message";
    }

}

在上面代碼中,@HystrixCommand註解代表使用斷路器的功能。如果ServiceClient的hello方法發生異常,將會調用fallback方法返回fallback message。

四、網關

在微服務架構中,網關類似於路由器的作用,它可以映射和重定向請求、調用相應服務,並將結果返回給客戶端。

1. 註冊Zuul Gateway

SpringCloud提供了Zuul來實現微服務的網關,我們可以在程序啟動類上添加@EnableZuulProxy註解來啟用Zuul Gateway,示例代碼如下:


// 添加Zuul依賴
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

// 在程序啟動類上添加@EnableZuulProxy註解
@SpringBootApplication
@EnableDiscoveryClient
@EnableZuulProxy
public class GatewayApplication {

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

}

Zuul Gateway通過配置路由實現請求的轉發和調用,可以在application.properties或者application.yml文件中配置路由,如下面所示:


zuul.routes.book.path=/app/**
zuul.routes.book.url=http://localhost:9000

上面代碼中,/app/**路徑的請求將被轉發到http://localhost:9000服務。

2. 使用Zuul Redirect

使用Zuul重定向請求也非常簡單,我們只需要在目標服務中使用@RestController註解和@RequestMapping註解,然後返回重定向地址即可,示例代碼如下:


@RestController
@RequestMapping("/redirect")
public class RedirectController {

    @GetMapping
    public String redirect() {
        return "redirect:https://www.baidu.com";
    }

}

上面代碼中,當我們訪問/redirect路徑時,將會被重定向到https://www.baidu.com。

原創文章,作者:UDDLQ,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/370171.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
UDDLQ的頭像UDDLQ
上一篇 2025-04-18 13:40
下一篇 2025-04-18 13:40

相關推薦

  • 深入淺出統計學

    統計學是一門關於收集、分析、解釋和呈現數據的學科。它在各行各業都有廣泛應用,包括社會科學、醫學、自然科學、商業、經濟學、政治學等等。深入淺出統計學是指想要學習統計學的人能夠理解統計…

    編程 2025-04-25
  • 深入淺出torch.autograd

    一、介紹autograd torch.autograd 模塊是 PyTorch 中的自動微分引擎。它支持任意數量的計算圖,可以自動執行前向傳遞、後向傳遞和計算梯度,同時提供很多有用…

    編程 2025-04-24
  • 深入淺出SQL佔位符

    一、什麼是SQL佔位符 SQL佔位符是一種佔用SQL語句中某些值的標記或佔位符。當執行SQL時,將使用該標記替換為實際的值,並將這些值傳遞給查詢。SQL佔位符使查詢更加安全,防止S…

    編程 2025-04-24
  • 深入淺出:理解nginx unknown directive

    一、概述 nginx是目前使用非常廣泛的Web服務器之一,它可以運行在Linux、Windows等不同的操作系統平台上,支持高並發、高擴展性等特性。然而,在使用nginx時,有時候…

    編程 2025-04-24
  • 深入淺出ThinkPHP框架

    一、簡介 ThinkPHP是一款開源的PHP框架,它遵循Apache2開源協議發佈。ThinkPHP具有快速的開發速度、簡便的使用方式、良好的擴展性和豐富的功能特性。它的核心思想是…

    編程 2025-04-24
  • 深入淺出arthas火焰圖

    arthas是一個非常方便的Java診斷工具,包括很多功能,例如JVM診斷、應用診斷、Spring應用診斷等。arthas使診斷問題變得更加容易和準確,因此被廣泛地使用。artha…

    編程 2025-04-24
  • 深入淺出AWK -v參數

    一、功能介紹 AWK是一種強大的文本處理工具,它可以用於數據分析、報告生成、日誌分析等多個領域。其中,-v參數是AWK中一個非常有用的參數,它用於定義一個變量並賦值。下面讓我們詳細…

    編程 2025-04-24
  • 深入淺出Markdown文字顏色

    一、Markdown文字顏色的背景 Markdown是一種輕量級標記語言,由於其簡單易學、易讀易寫,被廣泛應用於博客、文檔、代碼注釋等場景。Markdown支持使用HTML標籤,因…

    編程 2025-04-23
  • 深入淺出runafter——異步任務調度器的實現

    一、runafter是什麼? runafter是一個基於JavaScript實現的異步任務調度器,可以幫助開發人員高效地管理異步任務。利用runafter,開發人員可以輕鬆地定義和…

    編程 2025-04-23
  • 深入淺出TermQuery

    一、TermQuery概述 TermQuery是Lucene中最基本、最簡單、最常見的查詢方法之一。它完全符合其名字,意味着只能對一個單詞進行查詢。 TermQuery可以用於搜索…

    編程 2025-04-23

發表回復

登錄後才能評論