springcloud項目快速開始起始模板的實現

1.創建實體類模塊

引入依賴(這裡使用tkmybatis的依賴)

  <dependencies>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>
    </dependencies>

效果如下

2.創建配置中心,搭建註冊中心集群

選擇依賴(修改spring cloud版本號)

修改application.yml搭建server集群 此處要註意域名解析peer1,peer2,peer3

server:
  port: 9004
spring:
  application:
    name: euraka-server
eureka:
  client:
    service-url:
      #如果是集群,,後面用逗號隔開
      defaultZone: http://127.0.0.1:9004/eureka
      #自己本身就是服務註冊中心,聲明不註冊自己
    register-with-eureka: false
    #聲明自己不拉取自己的服務註冊列表
    fetch-registry: false
 
  instance:
    # ⼼跳間隔時間
    lease-renewal-interval-in-seconds: 30
    # 沒收到⼼跳多⻓時間剔除
    lease-expiration-duration-in-seconds: 90
  server:
    enable-self-preservation: false # 關閉⾃我保護模式(缺省為打開)
    eviction-interval-timer-in-ms: 1000 # 掃描失效服務的間隔時間(缺省為60*1000ms)
logging:
  level:
    com.netflix: warn
---
spring:
  config:
    activate:
      on-profile: peer1
server:
  port: 9003
eureka:
  instance:
    hostname: peer1
  client:
    service-url:
      defaultZone: http://peer2:9004/eureka,http://peer3:9005/eureka
---
spring:
  config:
    activate:
      on-profile: peer2
server:
  port: 9004
eureka:
  instance:
    hostname: peer2
  client:
    service-url:
      defaultZone: http://peer1:9003/eureka,http://peer3:9005/eureka
---
spring:
  config:
    activate:
      on-profile: peer3
server:
  port: 9005
eureka:
  instance:
    hostname: peer3
  client:
    service-url:
      defaultZone: http://peer1:9003/eureka,http://peer2:9004/eureka

啟動器加@EnableEurekaServer註解

3.創建網關(修改版本號)

 網關yml配置文件

 
server:
  port: 9006
spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: service
          uri: http://127.0.0.1:9001
          predicates:
            - Path=/pay/{segment}
          filters:
            - name: CircuitBreaker
              args:
                name: backendA
                fallbackUri: forward:/fallbackA
#全部允許跨域訪問
      globalcors:
        cors-configurations:
          '[/**]':
            allowed-origin-patterns: "*" # spring boot2.4配置
            #            allowed-origins: "*"
            allowed-headers: "*"
            allow-credentials: true
            allowed-methods:
              - GET
              - POST
              - DELETE
              - PUT
              - OPTION
 
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:9004/eureka
#網關熔斷,快速降級
resilience4j:
  circuitbreaker:
    configs:
      default:
        failureRateThreshold: 30 #失敗請求百分比,超過這個比例,CircuitBreaker變為OPEN狀態
        slidingWindowSize: 10 #滑動窗口的大小,配置COUNT_BASED,表示10個請求,配置TIME_BASED表示10秒
        minimumNumberOfCalls: 5 #最小請求個數,隻有在滑動窗口內,請求個數達到這個個數,才會觸發CircuitBreader對於斷路器的判斷
        slidingWindowType: TIME_BASED #滑動窗口的類型
        permittedNumberOfCallsInHalfOpenState: 3 #當CircuitBreaker處於HALF_OPEN狀態的時候,允許通過的請求個數
        automaticTransitionFromOpenToHalfOpenEnabled: true #設置true,表示自動從OPEN變成HALF_OPEN,即使沒有請求過來
        waitDurationInOpenState: 2s #從OPEN到HALF_OPEN狀態需要等待的時間
        recordExceptions: #異常名單
          - java.lang.Exception
    instances:
      backendA:
        baseConfig: default
      backendB:
        failureRateThreshold: 50
        slowCallDurationThreshold: 2s #慢調用時間閾值,高於這個閾值的呼叫視為慢調用,並增加慢調用比例。
        slowCallRateThreshold: 30 #慢調用百分比閾值,斷路器把調用時間大於slowCallDurationThreshold,視為慢調用,當慢調用比例大於閾值,斷路器打開,並進行服務降級
        slidingWindowSize: 10
        slidingWindowType: TIME_BASED
        minimumNumberOfCalls: 2
        permittedNumberOfCallsInHalfOpenState: 2
        waitDurationInOpenState: 120s #從OPEN到HALF_OPEN狀態需要等待的時間

創建網關熔斷對應降級方法

@RestController
@Slf4j
public class FallbackController {
 
    @GetMapping("/fallbackA")
    public ResponseEntity fallbackA() {
        return ResponseEntity.ok("服務不可用,降級");
    }
}

啟動器加@EnableDiscoveryClient 或@EnableEurekaClient註解

還可以在網關中設置全局或局部過濾器

4.搭建配置中心

添加依賴()另加下面依賴實現git倉庫自動刷新,需要配合rabbitmq使用,需要內網穿透

<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

 yml配置文件(可以更改本地作為配置中心)

server:
  port: 9007
spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
  application:
    name: cloud-config
  cloud:
    config:
      server:
        git:
          uri: https://gitee.com/zhaoy999/springcloud_config.git
          search-paths: config
          default-label: master
#配置中心設在本地使用
#  profiles:
#    active: native
#  cloud:
#    config:
#      server:
#        native:
#          search-locations: classpath:/config
 
eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:9004/eureka
#git倉庫配置中心自動刷新
management:
  endpoints:
    web:
      exposure:
        include: bus-refresh
  endpoint:
    bus-refresh:
      enabled: true

在已經指定好的倉庫config目錄下創建配置文件

5.構思需要的微服務(每個微服務既可以是提供者也可以是消費者)

引入依賴(需要另外引入下面代碼塊的依賴)

!!!修改,先不要加sleuth依賴,會報錯

這裡使用的tkmybatis操作持久層

<!--使用rabbitmq鏈路追蹤,接收rabbitmq隊列消息,實現配置的自動刷新-->
 <dependency>
        <groupId>org.springframework.amqp</groupId>
        <artifactId>spring-rabbit</artifactId>
    </dependency>
<!--微服務限流-->
    <dependency>
        <groupId>io.github.resilience4j</groupId>
        <artifactId>resilience4j-ratelimiter</artifactId>
        <version>1.7.0</version>
    </dependency>
<!-- 信號量隔離-->
    <dependency>
        <groupId>io.github.resilience4j</groupId>
        <artifactId>resilience4j-bulkhead</artifactId>
        <version>1.7.0</version>
    </dependency>
 
<!-- 配置自動刷新,需要配合@RefreshScope註解-->
<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bus-amqp</artifactId>
        </dependency>
<!-- 可不用-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
<!--數據庫連接-->
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
        </dependency>
<!--tkmybatis-->
        <dependency>
            <groupId>tk.mybatis</groupId>
            <artifactId>mapper-spring-boot-starter</artifactId>
            <version>2.0.2</version>
        </dependency>
<!--PageHelper分頁插件-->
<dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.11</version>
        </dependency>
<!--前後端分離使用的thymeleaf-->
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
<!--tkmybatis使用,增強mybatis不能用-->
 <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>

yml基本配置:

  • 連接eureka註冊中心:啟動器加@EnableDiscoveryClient 或@EnableEurekaClient註解
  • 端口號,服務名,連接配置中心:本地application.yml
  • 鏈路追蹤配置:git倉庫config目錄下application.yml
  • rabbitmq消息接收配置:git倉庫config目錄下application.yml
  • 選擇性配置feign:git倉庫config目錄下application.yml
  • 熔斷,隔離,限流:git倉庫config目錄下application.yml
  • 數據庫連接::git倉庫config目錄下application.yml

本地application.yml

server:
  port: ${port:9001}
 
spring:
  application:
    name: pay-service
  cloud:
    config:
      uri: http://localhost:9007
      profile: default
      label: master
  config:
    import: optional:configserver:http://localhost:9007

git倉庫config目錄下application.yml

spring:
  zipkin:
    base-url: http://localhost:9411
    sender:
      type: web
  sleuth:
    sampler:
      probability: 1
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: guest
    password: guest
eureka:
  client:
    service-url:
      defaultZone: http://peer1:9003/eureka,http://peer2:9004/eureka,http://peer3:9005/eureka
feign:
  client:
    config:
      default:
        connectTimeout: 5000 #防止由於服務器處理時間長而阻塞調用者
        readTimeout: 5000 #從連接建立時開始應用,在返回響應時間過長時觸發
 
  circuitbreaker:
      enabled: true
 
  compression:
    request:
      enabled: true # 請求壓縮
      mime-types: text/xml,application/xml,application/json # 壓縮的類型
      min-request-size: 2048 # 請求最小壓縮的閾值
    response:
      enabled: true #響應壓縮
      useGzipDecoder: true #使用gzip解碼器解碼響應數據
 
 
logging:
  level:
    com.zhao: debug
#設置自己作為斷路器
resilience4j:
  circuitbreaker:
    configs:
      default:
        failureRateThreshold: 30 #失敗請求百分比,超過這個比例,CircuitBreaker變為OPEN狀態
        slidingWindowSize: 10 #滑動窗口的大小,配置COUNT_BASED,表示10個請求,配置TIME_BASED表示10秒
        minimumNumberOfCalls: 5 #最小請求個數,隻有在滑動窗口內,請求個數達到這個個數,才會觸發CircuitBreader對於斷路器的判斷
        slidingWindowType: TIME_BASED #滑動窗口的類型
        permittedNumberOfCallsInHalfOpenState: 3 #當CircuitBreaker處於HALF_OPEN狀態的時候,允許通過的請求個數
        automaticTransitionFromOpenToHalfOpenEnabled: true #設置true,表示自動從OPEN變成HALF_OPEN,即使沒有請求過來
        waitDurationInOpenState: 2s #從OPEN到HALF_OPEN狀態需要等待的時間
        recordExceptions: #異常名單
          - java.lang.Exception
    instances:
      backendA:
        baseConfig: default #熔斷器backendA,繼承默認配置default
      backendB:
        failureRateThreshold: 50
        slowCallDurationThreshold: 2s #慢調用時間閾值,高於這個閾值的呼叫視為慢調用,並增加慢調用比例。
        slowCallRateThreshold: 30 #慢調用百分比閾值,斷路器把調用時間大於slowCallDurationThreshold,視為慢調用,當慢調用比例大於閾值,斷路器打開,並進行服務降級
        slidingWindowSize: 10
        slidingWindowType: TIME_BASED
        minimumNumberOfCalls: 2
        permittedNumberOfCallsInHalfOpenState: 2
        waitDurationInOpenState: 2s #從OPEN到HALF_OPEN狀態需要等待的時間
 
  bulkhead:
    configs:
      default:
        maxConcurrentCalls: 5 # 隔離允許並發線程執行的最大數量
        maxWaitDuration: 20ms # 當達到並發調用數量時,新的線程的阻塞等待的最長時間
    instances:
      backendA:
        baseConfig: default
      backendB:
        maxWaitDuration: 10ms
        maxConcurrentCalls: 20
#線程池隔離()
  thread-pool-bulkhead:
    configs:
      default:
        maxThreadPoolSize: 4 # 最大線程池大小
        coreThreadPoolSize: 2 # 核心線程池大小
        queueCapacity: 2 # 隊列容量
    instances:
      backendA:
        baseConfig: default
      backendB:
        maxThreadPoolSize: 1
        coreThreadPoolSize: 1
        queueCapacity: 1
#微服務限流
  ratelimiter:
    configs:
      default:
        timeoutDuration: 5 # 線程等待權限的默認等待時間
        limitRefreshPeriod: 1s # 限流器每隔1s刷新一次,將允許處理的最大請求重置為2
        limitForPeriod: 2 #在一個刷新周期內,允許執行的最大請求數
    instances:
      backendA:
        baseConfig: default
      backendB:
        timeoutDuration: 5
        limitRefreshPeriod: 1s
        limitForPeriod: 5

實現微服務的負載均衡(有使用resttemplate和使用openfeign兩種方式),這裡直接使用restTemplate,在消費者啟動器類裡引入restTemplate Bean類,加上@loadbalanced註解就可以用瞭

@EnableDiscoveryClient
@SpringBootApplication
 
public class OrderApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(OrderApplication.class, args);
    }
    @Bean
    @LoadBalanced
 
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

使用方法示例:

 @Autowired
    private RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;
    @GetMapping("/pay/{id}")
    @RateLimiter(name = "backendA", fallbackMethod = "fallback")
    public ResponseEntity<Payment> getPaymentById(@PathVariable("id") Integer id) throws InterruptedException, ExecutionException {
        log.info("now i enter the method!!!");
 
       // Thread.sleep(10000L); //阻塞10秒,已測試慢調用比例熔斷
 
        String url = "http://pay-service/pay/" + id;
        Payment payment = restTemplate.getForObject(url, Payment.class);
 
        log.info("now i exist the method!!!");
 
        return ResponseEntity.ok(payment);
    }

6.依賴引入完畢,以上全部微服務創建出來後修改位置

啟動器加啟動器加@EnableDiscoveryClient 或@EnableEurekaServer
逐個修改yml文件,修改端口號和服務名
打開services,方便同時打開多個服務
配置中心加@EnableConfigServer
修改倉庫配置文件
添加本項目實體類依賴
打開rabbitmq,打開方法參考我的另一篇博客rabbitmq安裝全過程[含安裝包,可直接用
打開鏈路追蹤控制臺
開始寫邏輯代碼;

到此這篇關於springcloud項目快速開始起始模板的實現的文章就介紹到這瞭,更多相關springcloud 起始模板 內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: