亲宝软件园·资讯

展开

springcloud 起始模板

探索永不止息 人气:0

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基本配置:

本地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安装全过程[含安装包,可直接用
打开链路追踪控制台
开始写逻辑代码;

加载全部内容

相关教程
猜你喜欢
用户评论