Spring Cloud常用組件詳解

一、Eureka註冊中心

Eureka是Spring Cloud中的一個服務註冊和發現框架,通常用於實現微服務中的服務治理。Eureka Server作為服務註冊中心,負責管理各個服務實例的狀態信息,Eureka Client則作為服務提供者和服務消費者向Eureka Server註冊/查詢服務信息。

在創建Eureka Server時,我們需要添加spring-cloud-starter-netflix-eureka-server依賴,並在啟動類上添加@EnableEurekaServer註解。

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

在創建Eureka Client時,我們需要添加spring-cloud-starter-netflix-eureka-client依賴,並在啟動類上添加@EnableDiscoveryClient註解。同時,還需要在application.yml配置文件中指定服務名稱和註冊中心地址。

    spring:
      application:
        name: service-a
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/

二、Ribbon負載均衡

Ribbon是Spring Cloud中的一個客戶端負載均衡器,能夠實現服務提供者之間的負載均衡。當服務消費者向服務註冊中心獲取服務列表時,Ribbon會通過負載均衡演算法選擇一個服務實例,將請求發送到該實例上。

在創建Ribbon客戶端時,我們需要添加spring-cloud-starter-loadbalancer依賴,並在RestTemplate中注入LoadBalancerClient,使用該客戶端發起請求時,會經過負載均衡器選擇一個服務實例。代碼示例:

    @RestController
    public class TestController {

        private final RestTemplate restTemplate;
        private final LoadBalancerClient loadBalancerClient;

        public TestController(RestTemplate restTemplate, LoadBalancerClient loadBalancerClient) {
            this.restTemplate = restTemplate;
            this.loadBalancerClient = loadBalancerClient;
        }

        @GetMapping("/test")
        public String test() {
            ServiceInstance instance = loadBalancerClient.choose("service-a");
            String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/hello";
            return restTemplate.getForObject(url, String.class);
        }
    }

三、Feign調用

Feign是Spring Cloud中的一個聲明式HTTP客戶端,它使用註解方式定義介面,Spring Cloud會自動生成實現該介面的代理對象。在調用其他服務時,我們只需要定義一個介面,並添加@FeignClient註解即可。同時,Feign還支持負載均衡和服務發現功能。

在創建Feign客戶端時,我們需要添加spring-cloud-starter-openfeign依賴,並在啟動類上添加@EnableFeignClients註解。Feign還提供了@PathVariable、@RequestParam等註解,用於設置請求參數。代碼示例:

    @FeignClient("service-a")
    public interface ServiceAFeignClient {

        @GetMapping("/hello")
        String hello();
    }

    @RestController
    public class TestController {

        private final ServiceAFeignClient serviceAFeignClient;

        public TestController(ServiceAFeignClient serviceAFeignClient) {
            this.serviceAFeignClient = serviceAFeignClient;
        }

        @GetMapping("/test")
        public String test() {
            return serviceAFeignClient.hello();
        }
    }

四、Hystrix熔斷器

Hystrix是Spring Cloud中的一個熔斷器,用於實現服務的降級和熔斷。當服務出現故障或響應緩慢時,Hystrix會自動觸發熔斷邏輯,避免請求在服務間傳遞導致整個系統崩潰。

在創建使用Hystrix的服務時,我們需要添加spring-cloud-starter-netflix-hystrix依賴,並在介面中添加@HystrixCommand註解定義服務降級邏輯。代碼示例:

    @RestController
    @DefaultProperties(defaultFallback = "fallback")
    public class TestController {

        private final RestTemplate restTemplate;

        public TestController(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }

        @GetMapping("/test")
        @HystrixCommand
        public String test() {
            return restTemplate.getForObject("http://service-a/hello", String.class);
        }

        private String fallback() {
            return "fallback";
        }
    }

五、Gateway網關

Gateway是Spring Cloud中的一個網關組件,用於實現服務的路由和過濾。通過Gateway,我們能夠實現動態路由、請求重試、過濾請求等功能,使服務提供者更加靈活和智能。

在創建Gateway網關時,我們需要添加spring-cloud-starter-gateway依賴,並在配置文件中定義路由規則。Gateway的路由規則定義採用yaml格式,代碼示例:

    spring:
      cloud:
        gateway:
          routes:
            - id: service-a
              uri: http://localhost:8080
              predicates:
                - Path=/service-a/**
            - id: service-b
              uri: http://localhost:8081
              predicates:
                - Path=/service-b/**

其中id為路由規則唯一標識符,uri為目標服務地址,predicates為匹配規則。

六、Config配置中心

Config是Spring Cloud中的一個配置中心,用於集中管理各個服務的配置信息。在Config中,我們能夠實現配置文件的動態刷新、加密和解密等功能,使系統更加安全和易於維護。

在創建Config服務時,我們需要添加spring-cloud-config-server依賴,並在啟動類上添加@EnableConfigServer註解。同時,還需要在啟動類的配置文件中指定Git倉庫地址和配置文件路徑。代碼示例:

    @SpringBootApplication
    @EnableConfigServer
    public class ConfigServerApplication {

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

    spring:
      cloud:
        config:
          server:
            git:
              uri: https://github.com/spring-cloud-samples/config-repo
              search-paths: '{profile}'

七、Bus消息匯流排

Bus是Spring Cloud中的一個消息匯流排,用於實現Config配置文件的動態刷新。在使用Bus時,我們需要向Config服務註冊上Bus,並在需要刷新配置的服務中觸發/actuator/bus-refresh介面,此時Config將發送消息通知其他使用該配置文件的服務進行配置更新。

在使用Bus時,我們需要添加spring-cloud-starter-bus-amqp依賴,並在配置文件中指定RabbitMQ的連接信息和交換機。同時,在每個服務的配置文件中添加management.endpoints.web.exposure.include屬性,開啟/actuator/bus-refresh介面。代碼示例:

    spring:
      rabbitmq:
        host: localhost
        port: 5672
        username: guest
        password: guest
      cloud:
        bus:
          enabled: true
        stream:
          rabbit:
            bindings:
              input:
                destination: config
                group: service-a
            bindings:
              output:
                destination: config
                group: service-a
            bindings:
              output:
                destination: config
                group: service-b
    management:
      endpoints:
        web:
          exposure:
            include: bus-refresh

八、Sleuth鏈路追蹤

Sleuth是Spring Cloud中的一個鏈路追蹤組件,通過在服務調用過程中添加TraceId和SpanId等信息,實現對服務調用全鏈路監控和性能調優。

在使用Sleuth時,我們只需要添加spring-cloud-starter-sleuth依賴,Spring Cloud會自動為服務添加Trace信息。代碼示例:

    @RestController
    public class TestController {

        private final RestTemplate restTemplate;

        public TestController(RestTemplate restTemplate) {
            this.restTemplate = restTemplate;
        }

        @GetMapping("/test")
        public String test() {
            return restTemplate.getForObject("http://service-a/hello", String.class);
        }
    }

總結

Spring Cloud是一個非常強大的微服務框架,其中提供了豐富的組件和工具,使得服務治理、負載均衡、熔斷降級、路由過濾、配置管理等功能更加便捷、靈活和智能。在使用Spring Cloud時,我們需要根據業務需求靈活選擇組件,同時結合各個組件的特點和優勢,以實現更加優秀的微服務架構。

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

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
UOQRB的頭像UOQRB
上一篇 2025-01-27 13:34
下一篇 2025-01-27 13:34

相關推薦

發表回復

登錄後才能評論