国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Spring Cloud Demo

這篇具有很好參考價(jià)值的文章主要介紹了Spring Cloud Demo。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問(wèn)。

Spring Cloud Demo

本文介紹Spring Cloud 常用的組件的demo代碼。gitee代碼:https://gitee.com/Aes_yt/spring-cloud-demo

包括Spring Cloud Eureka,Spring Cloud Feign,Spring Cloud Hystrix,Spring Cloud Ribbon,Spring Cloud Zuul,Spring Cloud Config,Spring Cloud Sleuth。

Spring Cloud Eureka

Server

  1. pom引入:

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

    SpringBootApplication 啟動(dòng)類(lèi)加入 @EnableEurekaServer注解。

  3. 配置:

    server:
      port: 8761
    
    eureka:
      instance:
        hostname: localhost
      client:
        register-with-eureka: false
        fetch-registry: false
        service-url:
          defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
      server:
        wait-time-in-ms-when-sync-empty: 0
        enable-self-preservation: false
    

Client

  1. pom引入:

    <dependency>
    	<groupId>org.springframework.cloud</groupId>
    	<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    
  2. 代碼:

    SpringBootApplication 啟動(dòng)類(lèi)加入 @EnableDiscoveryClient注解。

  3. 配置:

    server:
      port: 8081
    
    spring:
      application:
        name: demo-client1
    
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
    

TIPS. 非java語(yǔ)言也可使用Eureka提供的REST API接口接入Server。 wiki

常見(jiàn)問(wèn)題

  1. 為什么服務(wù)上線(xiàn)了,Eureka Client 不能及時(shí)獲取到。

    Eureka Server 的 REST API 有response cache,需要等緩存過(guò)期后才能更新數(shù)據(jù)。

  2. 為什么服務(wù)下線(xiàn)了,Eureka Server 接口返回的信息還會(huì)存在。

    應(yīng)用實(shí)例異常掛掉,沒(méi)有在掛掉之前告知Server 要下線(xiàn)。這個(gè)就需要依賴(lài)Eureka Server的EvictionTask 去剔除。

  3. 其他:

    springcloud對(duì)springboot的版本是有要求的,如果不一致,會(huì)啟動(dòng)不起來(lái)的。詳細(xì)可以看官網(wǎng)的版本要求。

Spring Cloud Feign + Spring Cloud Hystrix

demo-hello

  1. 首先先創(chuàng)建一個(gè) demo 的 module,接入Eureka配置(eureka-client )。設(shè)置端口8082,里面只有一個(gè)get方法,我們用postman調(diào)用 http://localhost:8082/hello/testGet?param=hello,能夠正常返回。

    @RestController
    @RequestMapping("/hello")
    @Slf4j
    public class HelloController {
        @GetMapping("/testGet")
        public BaseResp<String> testGet(@RequestParam("param") String param) {
            log.info("[demo-hello] testGet:{}", param);
            return BaseResp.success(param);
        }
    }
    

    yml:

    server:
      port: 8082
    spring:
      application:
        name: demo-hello
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
    

feign-client

  1. 創(chuàng)建一個(gè)新module。引入Eureka-client依賴(lài),feign依賴(lài)和hystrix依賴(lài)。

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
    <!-- cloud 2020.0.x 之后無(wú)此依賴(lài) -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
    </dependency>
    

    注意:hystrix 在 spring-cloud 2020.0.x 版本廢棄,之后的版本推薦使用 Resilience4j 進(jìn)行服務(wù)的熔斷。

  2. yaml 配置

    server:
      port: 8083
    spring:
      application:
        name: feign-client
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
    
    feign:
    #  hystrix熔斷開(kāi)關(guān)
      hystrix:
        enabled: true
    #  feign-client的超時(shí)時(shí)間
      client:
        config:
          default:
            connect-timeout: 3000
            read-timeout: 3000
            logger-level: basic
    
    # 設(shè)置hystrix服務(wù)降級(jí)超時(shí)時(shí)間
    hystrix:
      command:
        default:
          execution:
            isolation:
              thread:
                timeoutInMilliseconds: 15000
    
  3. Application 注解

    @EnableFeignClients:@EnableFeignClients 是一個(gè) Spring Cloud 注解,用于啟用 Feign 客戶(hù)端的功能。

    @EnableCircuitBreaker:@EnableCircuitBreaker 是 Spring Cloud 提供的一個(gè)注解,用于啟用熔斷器(Circuit Breaker)的功能。

    @SpringBootApplication
    @EnableDiscoveryClient
    @EnableFeignClients
    @EnableCircuitBreaker
    public class FeignClientApplication {
        public static void main(String[] args) {
            SpringApplication.run(FeignClientApplication.class, args);
        }
    }
    
  4. 建立Feign調(diào)用Service

    @FeignClient(name = "demo-hello", contextId = "feign-hello", path = "/hello", fallbackFactory = FeignHelloServiceHystrix.class)
    public interface FeignHelloService {
        @RequestMapping(value = "/testGet", method = RequestMethod.GET)
        BaseResp<String> testGet(@RequestParam("param") String param);
    }
    

    name = "demo-hello" 就是 demo 項(xiàng)目的 spring.application.name,contentxId 就相當(dāng)于這個(gè)調(diào)用service的唯一id,path就是統(tǒng)一前綴。fallbackFactory 就是降級(jí)后的工廠(chǎng)。所以我們要實(shí)現(xiàn)這個(gè)工廠(chǎng)。

    我這邊的邏輯,就是記錄一下日志,然后返回統(tǒng)一的錯(cuò)誤對(duì)象。

    @Slf4j
    @Component
    public class FeignHelloServiceHystrix implements FallbackFactory<FeignHelloService> {
        @Override
        public FeignHelloService create(Throwable cause) {
            log.error("feign調(diào)用helloController報(bào)錯(cuò)", cause);
            return new FeignHelloService() {
                public BaseResp<String> testGet(String param) {
                    return BaseResp.error(param);
                }
            };
        }
    }
    
  5. 測(cè)試一下,

        @GetMapping("/testGet")
        public BaseResp<String> testGet(@RequestParam("param") String param) {
    //        try {
    //            Thread.sleep(6000);
    //        } catch (InterruptedException e) {
    //            throw new RuntimeException(e);
    //        }
    //        if(!param.isEmpty()){
    //            throw new RuntimeException("error...");
    //        }
            log.info("[demo-hello] testGet:{}", param);
            return BaseResp.success(param);
        }
    

    testGet 6秒鐘才響應(yīng)或者直接拋出異常,都是會(huì)進(jìn)入FeignHelloServiceHystrix中打印日志。

附加

  1. Feign 加日志打印

    1. xml配置Feign客戶(hù)端

      # Feign 日志配置
      logging:
        level:
          com.yt.demo.service.feign: debug
      
    2. Feign 配置

      /**
       * Feign 配置
       */
      @Slf4j
      @Configuration
      public class FeignConfig {
      
          /**
           * NONE:不記錄任何信息
           * BASIC:僅記錄請(qǐng)求方法、URL以及響應(yīng)狀態(tài)碼和執(zhí)行時(shí)間.
           * HEADERS:除了記錄BASIC級(jí)別的信息外,還會(huì)記錄請(qǐng)求和響應(yīng)的頭信息
           * FULL:記錄所有請(qǐng)求與響應(yīng)的明細(xì),包括頭信息、請(qǐng)求體、元數(shù)據(jù)
           */
          @Bean
          Logger.Level feignLoggerLevel() {
              return Logger.Level.FULL;
          }
      }
      
    3. 效果如下:

      2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] ---> POST http://demo-hello/hello/testPost HTTP/1.1
      2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] Content-Length: 30
      2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] Content-Type: application/json
      2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] 
      2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] {"param":"Post method: hello"}
      2023-06-23 11:38:43.026 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] ---> END HTTP (30-byte body)
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] <--- HTTP/1.1 200 (2ms)
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] connection: keep-alive
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] content-type: application/json
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] date: Fri, 23 Jun 2023 03:38:43 GMT
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] keep-alive: timeout=60
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] transfer-encoding: chunked
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] 
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] {"code":200,"data":"Post method: hello","msg":"success"}
      2023-06-23 11:38:43.029 DEBUG 496 --- [ix-demo-hello-4] c.y.d.service.feign.FeignHelloService    : [FeignHelloService#testPost] <--- END HTTP (56-byte body)
      
  2. 文件上傳

    1. feign Client 里面新增文件上傳方法

          @RequestMapping(value = "/testFile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE,
                  consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
          BaseResp<String> testFile(@RequestPart("file") MultipartFile file);
      

      注意配置@RequestPart 注解,參數(shù)加上:produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.MULTIPART_FORM_DATA_VALUE

常見(jiàn)問(wèn)題

  1. demo項(xiàng)目的方法返回報(bào)錯(cuò),或者超時(shí),都并沒(méi)有進(jìn)入熔斷工廠(chǎng)。

    檢查一下feign-client的hystrix是否啟用: feign.hystrix.enabled: true

  2. 配置了feign-client的超時(shí)時(shí)間為3s,demo返回時(shí)間6s,但是1s就馬上進(jìn)入熔斷工廠(chǎng)報(bào)超時(shí),并沒(méi)有等待3s。

    feign-client的超時(shí)時(shí)間和hystrix的超時(shí)時(shí)間都要配置。

  3. 配置了超時(shí)時(shí)間,但是還是不生效。

    根據(jù)你的cloud版本搜索一下,對(duì)應(yīng)的配置怎么配。有可能不同版本的配置方法不一樣,單詞改變了之類(lèi)的都是有可能的。

  4. feign調(diào)用報(bào)錯(cuò):Load balancer does not have available server for client : xxx

    feign客戶(hù)端的yaml配置加上 fetch-registry: true

    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
        fetch-registry: true
    

Spring Cloud Ribbon

demo-hello

  1. demo-hello 復(fù)用上面Feign的controller新增一個(gè)測(cè)試方法,打印出當(dāng)前服務(wù)器端口

        @GetMapping("/testRibbon")
        public BaseResp<String> testRibbon(@RequestParam("param") String param, HttpServletRequest httpServletRequest) {
            log.info("接收到請(qǐng)求,參數(shù):{}, serverPort:{}", param, httpServletRequest.getServerPort());
            return BaseResp.success("Response from server port: " + httpServletRequest.getServerPort());
        }
    
  2. 啟動(dòng)項(xiàng)目,之后修改application.xml的端口號(hào)port,重新啟動(dòng)一個(gè)實(shí)例。

  3. 啟動(dòng)成功之后,在Eureka界面可以看到兩個(gè)啟動(dòng)的實(shí)例。

    Application AMIs Availability Zones Status
    DEMO-HELLO n/a (2) (2) UP (2) - 192.168.0.101:demo-hello:8082 , 192.168.0.101:demo-hello:8084

ribbon-client

  1. 新建一個(gè)項(xiàng)目。[可以從Eureka-client復(fù)制,然后修改spring.application.name和pom文件的artifactId]。

  2. 引入ribbon依賴(lài)

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
    </dependency>
    
  3. 新建ribbon配置類(lèi),重點(diǎn)是用@LoadBalance注解來(lái)聲明restTemplate具有負(fù)載均衡能力。而且這樣在使用restTeamplate的時(shí)候就能通過(guò)eureka上面的服務(wù)名來(lái)調(diào)用服務(wù)了,

    @Slf4j
    @Configuration
    public class RibbonConfig {
    
        @Bean
        @LoadBalanced
        public RestTemplate restTemplate(){
            return new RestTemplate();
        }
    }
    
  4. 新建一個(gè)測(cè)試類(lèi),直接調(diào)用十次請(qǐng)求

    @RestController
    @RequestMapping("/client")
    @Slf4j
    public class HelloController {
        @Autowired
        private RestTemplate restTemplate;
    
        @GetMapping("/testRibbon")
        public BaseResp<String> testRibbon(@RequestParam("param") String param) {
            String url = "http://demo-hello/hello/testRibbon?param=" + param;
    		
            for (int i = 0; i < 10; i++) {
                BaseResp<?> resp = restTemplate.getForObject(url, BaseResp.class);
                log.info("i-{}: {}", i, resp);
            }
            return BaseResp.success(null);
        }
    }
    
  5. 返回結(jié)果:

    2023-06-23 15:42:40.802  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-0: BaseResp(code=200, data=Response from server port: 8084, msg=success)
    2023-06-23 15:42:40.805  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-1: BaseResp(code=200, data=Response from server port: 8082, msg=success)
    2023-06-23 15:42:40.807  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-2: BaseResp(code=200, data=Response from server port: 8084, msg=success)
    2023-06-23 15:42:40.810  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-3: BaseResp(code=200, data=Response from server port: 8082, msg=success)
    2023-06-23 15:42:40.812  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-4: BaseResp(code=200, data=Response from server port: 8084, msg=success)
    2023-06-23 15:42:40.814  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-5: BaseResp(code=200, data=Response from server port: 8082, msg=success)
    2023-06-23 15:42:40.818  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-6: BaseResp(code=200, data=Response from server port: 8084, msg=success)
    2023-06-23 15:42:40.820  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-7: BaseResp(code=200, data=Response from server port: 8082, msg=success)
    2023-06-23 15:42:40.824  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-8: BaseResp(code=200, data=Response from server port: 8084, msg=success)
    2023-06-23 15:42:40.826  INFO 7916 --- [nio-8085-exec-2] com.yt.demo.controller.HelloController   : i-9: BaseResp(code=200, data=Response from server port: 8082, msg=success)
    

    ribbon的默認(rèn)負(fù)載均衡策略是ZoneAvoidanceRule,可以看出請(qǐng)求分別調(diào)到了8084和8082兩個(gè)服務(wù)實(shí)例上。

  6. 負(fù)載均衡策略配置

    1. Ribbon內(nèi)置的負(fù)載均衡規(guī)則:

      規(guī)則名稱(chēng) 特點(diǎn)
      AvailabilityFilteringRule 過(guò)濾掉一直連接失敗的被標(biāo)記為circuit tripped的后端Server,并 過(guò)濾掉那些高并發(fā)的后端Server或者使用一個(gè)AvailabilityPredicate 來(lái)包含過(guò)濾server的邏輯,其實(shí)就是檢查status里記錄的各個(gè)server 的運(yùn)行狀態(tài)
      BestAvailableRule 選擇一個(gè)最小的并發(fā)請(qǐng)求的server,逐個(gè)考察server, 如果Server被tripped了,則跳過(guò)
      RandomRule 隨機(jī)選擇一個(gè)Server
      WeightedResponseTimeRule 根據(jù)響應(yīng)時(shí)間加權(quán),響應(yīng)時(shí)間越長(zhǎng),權(quán)重越小,被選中的可能性越低
      RetryRule 對(duì)選定的負(fù)載均衡策略加上重試機(jī)制,在一個(gè)配置時(shí)間段內(nèi)當(dāng) 選擇Server不成功,則一直嘗試使用subRule的方式選擇一個(gè) 可用的Server
      RoundRobinRule 輪詢(xún)選擇,輪詢(xún)index,選擇index對(duì)應(yīng)位置的Server
      ZoneAvoidanceRule 復(fù)合判斷Server所在區(qū)域的性能和Server的可用性 選擇Server,在沒(méi)有區(qū)域的環(huán)境下,類(lèi)似于輪詢(xún)(RandomRule)
    2. 修改策略為隨機(jī):

      RibbonConfig.java 新增配置[全局]

      /**
       * 配置輪詢(xún)策略為RandomRule
       * 其他的策略配置也一樣,策略類(lèi)路徑都是 com.netflix.loadbalancer.xxx
       */
      @Bean
      public IRule ribbonRule(){
          return new RandomRule();
      }
      

      或:按服務(wù)粒度進(jìn)行配置:(demo-hello 是目標(biāo)服務(wù)的服務(wù)名)

      demo-hello:
        ribbon:
          NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
      

      我直接配置全局的 ribbon.NFLoadBalancerRuleClassName=com.netflix.loadbalancer.RandomRule不生效,不知道是不是不支持全局配置。

      效果:

      2023-06-23 15:59:31.095  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-0: BaseResp(code=200, data=Response from server port: 8082, msg=success)
      2023-06-23 15:59:31.097  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-1: BaseResp(code=200, data=Response from server port: 8084, msg=success)
      2023-06-23 15:59:31.100  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-2: BaseResp(code=200, data=Response from server port: 8084, msg=success)
      2023-06-23 15:59:31.104  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-3: BaseResp(code=200, data=Response from server port: 8082, msg=success)
      2023-06-23 15:59:31.108  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-4: BaseResp(code=200, data=Response from server port: 8084, msg=success)
      2023-06-23 15:59:31.112  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-5: BaseResp(code=200, data=Response from server port: 8084, msg=success)
      2023-06-23 15:59:31.117  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-6: BaseResp(code=200, data=Response from server port: 8084, msg=success)
      2023-06-23 15:59:31.124  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-7: BaseResp(code=200, data=Response from server port: 8082, msg=success)
      2023-06-23 15:59:31.132  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-8: BaseResp(code=200, data=Response from server port: 8084, msg=success)
      2023-06-23 15:59:31.137  INFO 11492 --- [nio-8085-exec-3] com.yt.demo.controller.HelloController   : i-9: BaseResp(code=200, data=Response from server port: 8082, msg=success)
      

Spring Cloud Zuul

zuul-server

  1. 新建項(xiàng)目 [可以從Eureka-client復(fù)制,然后修改spring.application.name和pom文件的artifactId]。

  2. 引入Eureka-client依賴(lài)和zuul依賴(lài)

    <dependency>
    	<groupId>org.springframework.cloud</groupId>
    	<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
    </dependency>
    
  3. 啟動(dòng)類(lèi)加注解: @EnableZuulProxy

  4. application.yml 配置文件,加上zuul配置

    server:
      port: 8888
    
    spring:
      application:
        name: zuul-server
    
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
    
    # 將 /demo-hello/ 開(kāi)頭的請(qǐng)求,轉(zhuǎn)到demo-hello組件中
    zuul:
      routes:
        demo-hello:
          path: /demo-hello/**
          serviceId: demo-hello
    #      也可以直接設(shè)置url
    #      url: http://localhost:8082/
    
  5. 啟動(dòng) demo-hello 組件,調(diào)用請(qǐng)求: http://localhost:8888/demo-hello/hello/testGet?param=this_is_param,demo-hello[8082] 得到結(jié)果。等同于直接調(diào)用demo-hello的請(qǐng)求:http://localhost:8082/hello/testGet?param=this_is_param

  6. 路由前綴

    zuul:
      routes:
        demo-hello:
          path: /demo-hello/**
          serviceId: demo-hello
      prefix: /pre
    

    我們可以配置zuul.prefix來(lái)設(shè)置統(tǒng)一前綴。像我這樣配置的話(huà),就是得訪(fǎng)問(wèn):http://localhost:8888/pre/demo-hello/hello/testGet?param=this_is_param,才能跟上面的請(qǐng)求等效。

  7. 屏蔽服務(wù)、路徑

    zuul:
      ignored-services: demo-hello
      ignored-patterns: /**/hello/**
    

請(qǐng)求過(guò)濾

  1. 我們可以根據(jù)過(guò)濾規(guī)則,對(duì)訪(fǎng)問(wèn)的請(qǐng)求進(jìn)行校驗(yàn)。不符合規(guī)則的可以直接過(guò)濾返回。比如我們可以校驗(yàn)請(qǐng)求的參數(shù)是否有token參數(shù)。

  2. 新建過(guò)濾器:

    @Slf4j
    public class AccessFilter extends ZuulFilter {
        /**
         * 過(guò)濾器類(lèi)型
         * pre: 在請(qǐng)求被路由前調(diào)用
         * routing: 在路由請(qǐng)求時(shí)調(diào)用
         * error: 在處理請(qǐng)求時(shí)發(fā)生錯(cuò)誤時(shí)調(diào)用
         * post: 在routing和error過(guò)濾器之后調(diào)用
         */
        @Override
        public String filterType() {
            return "pre";
        }
    
        /**
         * 過(guò)濾器的執(zhí)行順序,數(shù)值越小越優(yōu)先
         */
        @Override
        public int filterOrder() {
            return 0;
        }
    
        /**
         * 是否啟用過(guò)濾
         */
        @Override
        public boolean shouldFilter() {
            return true;
        }
    
        /**
         * 具體過(guò)濾邏輯
         */
        @Override
        public Object run() throws ZuulException {
            RequestContext currentContext = RequestContext.getCurrentContext();
            HttpServletRequest request = currentContext.getRequest();
    
            log.info("zuul接收到請(qǐng)求,參數(shù):{}", request.getParameterMap());
            log.info("zuul接收到請(qǐng)求,參數(shù):{}", request.getParameter("token"));
    
            if (request.getParameterMap().get("token") == null) {
                log.info("請(qǐng)求參數(shù)未包含token字段,返回");
                currentContext.setResponseStatusCode(401);
                currentContext.setSendZuulResponse(false);
                return null;
            }
    
            log.info("正常請(qǐng)求,放行");
            return null;
        }
    }
    
  3. 創(chuàng)建bean

    @Slf4j
    @Configuration
    public class ZuulConfig {
        @Bean
        public AccessFilter accessFilter() {
            return new AccessFilter();
        }
    }
    
  4. 測(cè)試

    請(qǐng)求 http://localhost:8888/pre/demo-hello/hello/testGet?param=this_is_param&token=gyt%26kal13 可以正常調(diào)到demo-hello組件里的方法。

    請(qǐng)求http://localhost:8888/pre/demo-hello/hello/testGet?param=this_is_param返回401錯(cuò)誤碼

Spring Cloud Config

config-server

  1. 引入依賴(lài)

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-config-server</artifactId>
    </dependency>
    
  2. 啟動(dòng)類(lèi)添加注解 @EnableConfigServer

  3. bootstrap.yaml配置

    server:
      port: 8086
    
    spring:
      application:
        name: config-server
    
      cloud:
        config:
          server:
            git:
              uri: https://gitee.com/Aes_yt/spring-cloud-demo.git
    #          git 倉(cāng)庫(kù)的相對(duì)搜索路徑
              search-paths: config-repo
              username: xxxx
              password: xxxx
              default-label: master
    
  4. git 配置

    第三點(diǎn)使用的是git配置,所以我們需要有一個(gè)git倉(cāng)庫(kù)。我已經(jīng)事先建好了,配置文件放在git倉(cāng)庫(kù)的config-repo路徑下。

    在config-repo上傳配置文件,例如上傳不同環(huán)境的三個(gè)配置文件:

    config-client.yaml

    config:
      name: myConfig
    

    config-client-dev.yaml

    config:
      name: myConfig-dev
    

    config-client-test.yaml

    config:
      name: myConfig-test
    

    config-client 是我待會(huì)要?jiǎng)?chuàng)建的client項(xiàng)目的application.name,文件名的明明規(guī)則就是 {name}-{profile}.yaml 或 .properties。文件內(nèi)容的配置文件就跟普通的yaml項(xiàng)目一樣,配置所需要的一些配置,我這邊是隨便配置了一個(gè)變量名 ${config.name},后面再輸出打印測(cè)試。

  5. 先測(cè)試。啟動(dòng)config-server,訪(fǎng)問(wèn)地址 : http://localhost:8086/config-client/dev,可以看到輸出配置信息。

    {
    	"name": "config-client",
    	"profiles": ["dev"],
    	"label": null,
    	"version": "2ec77d4a4f8050fa5a032cf5ff27ff8583d3f663",
    	"state": null,
    	"propertySources": [{
    		"name": "https://gitee.com/Aes_yt/spring-cloud-demo.git/config-repo/config-client-dev.yaml",
    		"source": {
    			"config.name": "myConfig-dev"
    		}
    	}, {
    		"name": "https://gitee.com/Aes_yt/spring-cloud-demo.git/config-repo/config-client.yaml",
    		"source": {
    			"config.name": "myConfig"
    		}
    	}]
    }
    

    也可以直接訪(fǎng)問(wèn) http://localhost:8086/config-client-dev.yaml 查看yaml配置內(nèi)容

    config:
      name: myConfig-dev
    

config-client

  1. 引入maven依賴(lài)

    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-config</artifactId>
    </dependency>
    
  2. bootstrap.yaml配置(我這里用application.yaml 配置啟動(dòng)會(huì)報(bào)錯(cuò))

    spring:
      application:
        name: config-client
      cloud:
        config:
          label: master
    #     config-server的地址
          uri: http://localhost:8086/
    #      環(huán)境
          profile: dev
    
    server:
      port: 8087
    
  3. 新建一個(gè)測(cè)試類(lèi),檢測(cè)配置值

    @RestController
    @RequestMapping("/config")
    public class ConfigTestController {
        @Value("${config.name}")
        private String configName;
    
        @GetMapping("/test")
        public String test() {
            return configName;
        }
    }
    
  4. 啟動(dòng)項(xiàng)目,能看到控制臺(tái)輸出,會(huì)打印出當(dāng)前使用的配置信息

    2023-07-22 10:42:16.447  INFO 13592 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Fetching config from server at : http://localhost:8086/
    2023-07-22 10:42:17.480  INFO 13592 --- [           main] c.c.c.ConfigServicePropertySourceLocator : Located environment: name=config-client, profiles=[dev], label=master, version=2ec77d4a4f8050fa5a032cf5ff27ff8583d3f663, state=null
    

    能看出當(dāng)前環(huán)境是 name=config-client, profiles=[dev], label=master ,所以會(huì)去maven倉(cāng)庫(kù)找到master分支的 config-client-dev 的配置文件。如果找不到的話(huà),在 @Value("${config.name}") 時(shí)則會(huì)報(bào)錯(cuò)。

  5. 測(cè)試,訪(fǎng)問(wèn) http://localhost:8087/config/test

    myConfig-dev

結(jié)合Eureka

  1. 結(jié)合Eureka使用,首先server和client都要引入Eureka-client依賴(lài),pom中引入spring-cloud-starter-netflix-eureka-client 。其次,啟動(dòng)類(lèi)都要加上 @EnableDiscoveryClient 注解。最后yaml中都需要加上配置 eureka.client.service-url.defaultZone=http://localhost:8761/eureka/ ,這三個(gè)都可參考上文的Eureka-client配置。

  2. config-client加上discovery配置:

    spring:
      application:
        name: config-client
      cloud:
        config:
          label: master
          #     config-server的地址
    #      uri: http://localhost:8086/
          #      環(huán)境
          profile: dev
    
    #      使用eureka發(fā)現(xiàn)服務(wù)
          discovery:
            enabled: true
            service-id: config-server
    eureka:
      client:
        service-url:
          defaultZone: http://localhost:8761/eureka/
    
    server:
      port: 8087
    

Spring Cloud Sleuth

Sleuth 能夠?qū)Ψ?wù)間調(diào)用的鏈路進(jìn)行監(jiān)控追蹤,之前學(xué)習(xí) Feign 的時(shí)候,我們用 Feign-client 組件,調(diào)用了 demo-hello 組件的testGet方法,所以我們可以在之前的Feign-client 和 demo-hello 組件的基礎(chǔ)上進(jìn)行修改驗(yàn)證,添加Sleuth依賴(lài),來(lái)觀(guān)察服務(wù)間的調(diào)用情況。

  1. 添加Sleuth依賴(lài)

  2. 運(yùn)行,調(diào)用,觀(guān)察打印的日志

    feign-client:

    2023-07-23 10:10:11.296 DEBUG [feign-client,f307a05d85938646,f8b404471ba7448a,true] 15956 --- [ix-demo-hello-5] 
    2023-07-23 10:10:11.296 DEBUG [feign-client,f307a05d85938646,f8b404471ba7448a,true] 15956 --- [ix-demo-hello-5] 
    2023-07-23 10:10:11.416 DEBUG [feign-client,f307a05d85938646,f8b404471ba7448a,true] 15956 --- [ix-demo-hello-5] 
    ...
    

    demo-hello:

    2023-07-23 10:10:11.398  INFO [demo-hello,f307a05d85938646,51bf5d6b238302e9,true] 11736 --- [nio-8082-exec-1] com.yt.demo.controller.HelloController   : [demo-hello] testGet:Get method: hello
    

    可以從控制臺(tái)的日志發(fā)現(xiàn),日志多了[feign-client,f307a05d85938646,f8b404471ba7448a,true]部分,第一個(gè)參數(shù)代表application.name,第二個(gè)參數(shù) f307a05d85938646 則是一個(gè)請(qǐng)求鏈路的 Trace ID,第三個(gè)參數(shù)f8b404471ba7448a表示SpanId,是一個(gè)基本的工作單元,第四個(gè)參數(shù)表示是否要將該信息輸出到Zipkin等服務(wù)中來(lái)收集和展示。

    從feign-client 到 demo-hello 中, Trace ID 都是f307a05d85938646,所以可以將一個(gè)請(qǐng)求在不同服務(wù)中的日志串聯(lián)起來(lái)。文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-613271.html

到了這里,關(guān)于Spring Cloud Demo的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來(lái)自互聯(lián)網(wǎng)用戶(hù)投稿,該文觀(guān)點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Spring Cloud Alibaba-01-微服務(wù)介紹

    Spring Cloud Alibaba-01-微服務(wù)介紹

    Lison dreamlison@163.com , v1.0.0 , 2023.05.07 架構(gòu)的演變 隨著互聯(lián)網(wǎng)的發(fā)展,網(wǎng)站應(yīng)用的規(guī)模也不斷的擴(kuò)大,進(jìn)而導(dǎo)致系統(tǒng)架構(gòu)也在不斷的進(jìn)行變化,從互聯(lián)網(wǎng)早起到現(xiàn)在,系統(tǒng)架構(gòu)大體經(jīng)歷了下面幾個(gè)過(guò)程: 單體應(yīng)用架構(gòu): 把所有功能都集中在一個(gè)應(yīng)用中,統(tǒng)一部署,開(kāi)發(fā)成本、

    2024年02月22日
    瀏覽(308)
  • Spring Cloud Alibaba 介紹與版本映射關(guān)系

    Spring Cloud Alibaba 介紹與版本映射關(guān)系

    目錄 前言 一、Spring Cloud Alibaba 是什么? 二、Spring Cloud Alibaba 版本依賴(lài) ????????Spring Cloud 本身并不是一個(gè)拿來(lái)即可用的框架,它是一套微服務(wù)規(guī)范,這套規(guī)范共有兩代實(shí)現(xiàn)。 (子項(xiàng)目): ● 第一代實(shí)現(xiàn): Spring Cloud Netflix, ● 第二代實(shí)現(xiàn): Spring Cloud Alibaba。 2018 年 12 月1

    2024年02月03日
    瀏覽(30)
  • Nacos 單機(jī)集群搭建及常用生產(chǎn)環(huán)境配置 | Spring Cloud 3

    Nacos /nɑ:k??s/ 是 Dynamic Naming and Configuration Service 的首字母簡(jiǎn)稱(chēng),一個(gè)更易于構(gòu)建云原生應(yīng)用的動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、配置管理和服務(wù)管理平臺(tái)。 Nacos 致力于幫助您發(fā)現(xiàn)、配置和管理微服務(wù)。 Nacos 提供了一組簡(jiǎn)單易用的特性集,幫助您快速實(shí)現(xiàn)動(dòng)態(tài)服務(wù)發(fā)現(xiàn)、服務(wù)配置、服務(wù)元數(shù)據(jù)

    2024年02月03日
    瀏覽(30)
  • 【Spring Cloud】關(guān)于Nacos配置管理的詳解介紹

    【Spring Cloud】關(guān)于Nacos配置管理的詳解介紹

    ????歡迎來(lái)到我的CSDN主頁(yè)!???? ??我是Java方文山,一個(gè)在CSDN分享筆記的博主。???? ??推薦給大家我的專(zhuān)欄《Spring Cloud》。???? ??點(diǎn)擊這里,就可以查看我的主頁(yè)啦!???? Java方文山的個(gè)人主頁(yè) ??如果感覺(jué)還不錯(cuò)的話(huà)請(qǐng)給我點(diǎn)贊吧!???? ??期待你的加入,一起

    2024年02月01日
    瀏覽(64)
  • Spring Cloud-Config介紹及Git入門(mén)

    Spring Cloud-Config介紹及Git入門(mén)

    二、Spring cloud config 分布式配置中心能干嗎? ================================= (1)集中式管理配置文件 (2)不同環(huán)境,不同配置,動(dòng)態(tài)化的配置更新,分環(huán)境部署,比如 /dev /test /prod /beta /release (3)運(yùn)行期間動(dòng)態(tài)調(diào)整配置,不再需要在每個(gè)服務(wù)部署的機(jī)器上編寫(xiě)配置文件,服務(wù)

    2024年04月12日
    瀏覽(20)
  • Spring Cloud Gateway 服務(wù)網(wǎng)關(guān)的部署與使用詳細(xì)介紹

    Spring Cloud Gateway 服務(wù)網(wǎng)關(guān)的部署與使用詳細(xì)介紹

    1、什么是服務(wù)網(wǎng)關(guān): ????????傳統(tǒng)的單體架構(gòu)中只需要開(kāi)放一個(gè)服務(wù)給客戶(hù)端調(diào)用,但是微服務(wù)架構(gòu)中是將一個(gè)系統(tǒng)拆分成多個(gè)微服務(wù),如果沒(méi)有網(wǎng)關(guān),客戶(hù)端只能在本地記錄每個(gè)微服務(wù)的調(diào)用地址,當(dāng)需要調(diào)用的微服務(wù)數(shù)量很多時(shí),它需要了解每個(gè)服務(wù)的接口,這個(gè)工

    2024年02月02日
    瀏覽(27)
  • 【Spring Cloud】微服務(wù)架構(gòu)演變及微服務(wù)架構(gòu)介紹

    【Spring Cloud】微服務(wù)架構(gòu)演變及微服務(wù)架構(gòu)介紹

    歡迎來(lái)到阿Q社區(qū) https://bbs.csdn.net/topics/617897123 隨著互聯(lián)網(wǎng)的發(fā)展,網(wǎng)站應(yīng)用的規(guī)模也在不斷的擴(kuò)大,進(jìn)而導(dǎo)致系統(tǒng)架構(gòu)也在不斷的進(jìn)行變化。從互聯(lián)網(wǎng)早期到現(xiàn)在,系統(tǒng)架構(gòu)大體經(jīng)歷了下面幾個(gè)過(guò)程:?jiǎn)误w應(yīng)用架構(gòu)—垂直應(yīng)用架構(gòu)—分布式架構(gòu)—SOA架構(gòu)—微服務(wù)架構(gòu),當(dāng)然還

    2024年02月02日
    瀏覽(82)
  • 微服務(wù)之Spring Cloud Alibaba Sentinel介紹與下載(詳細(xì)方法)

    微服務(wù)之Spring Cloud Alibaba Sentinel介紹與下載(詳細(xì)方法)

    隨著微服務(wù)的流行,服務(wù)和服務(wù)之間的穩(wěn)定性變得越來(lái)越重要。Sentinel 以流量為切入點(diǎn),從流量控制、流量路由、熔斷降級(jí)、系統(tǒng)自適應(yīng)過(guò)載保護(hù)、熱點(diǎn)流量防護(hù)等多個(gè)維度保護(hù)服務(wù)的穩(wěn)定性。 2012 年,Sentinel 誕生,主要功能為入口流量控制。 2013-2017 年,Sentinel 在阿里巴巴

    2024年02月11日
    瀏覽(95)
  • Spring Cloud Alibaba全家桶(六)——微服務(wù)組件Sentinel介紹與使用

    Spring Cloud Alibaba全家桶(六)——微服務(wù)組件Sentinel介紹與使用

    本文小新為大家?guī)?lái) 微服務(wù)組件Sentinel介紹與使用 相關(guān)知識(shí),具體內(nèi)容包括 分布式系統(tǒng)存在的問(wèn)題 , 分布式系統(tǒng)問(wèn)題的解決方案 , Sentinel介紹 , Sentinel快速開(kāi)始 (包括: API實(shí)現(xiàn)Sentinel資源保護(hù) , @SentinelResource注解實(shí)現(xiàn)資源保護(hù) ), Sentinel控制臺(tái) , Spring Cloud Alibaba整合

    2024年01月17日
    瀏覽(96)
  • Spring Cloud Alibaba 整合Seata 之概念介紹及Seata-server搭建

    Spring Cloud Alibaba 整合Seata 之概念介紹及Seata-server搭建

    目錄 前言 基礎(chǔ)介紹 官方文檔 模式分類(lèi) 角色介紹 Seata Server 部署 -??docker-compose? 數(shù)據(jù)庫(kù) 服務(wù)器 ?nacos配置 docker-compose.yaml 啟動(dòng) 后記 Seata 是 阿里巴巴 開(kāi)源的 分布式事務(wù)中間件,以 高效 并且對(duì)業(yè)務(wù) 0 侵入 的方式,解決 微服務(wù) 場(chǎng)景下面臨的分布式事務(wù)問(wèn)題。 主要指講述

    2024年02月07日
    瀏覽(19)

覺(jué)得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包