创建模块cloud-consumer-resilience4j-order80
POM引入依赖
<dependencies>
<!-- 引入Eureka 客户端依赖 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!-- 引入服务调用依赖 OpenFigen -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version>
</dependency>
<!-- actuator监控信息完善 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>io.github.resilience4j</groupId>
<artifactId>resilience4j-spring-cloud2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-circuitbreaker-resilience4j</artifactId>
</dependency>
</dependencies>
修改YML文件
server:
port: 80
eureka:
instance:
#实例名字
instance-id: cloud-order-resilience4j-consumer80
client:
# Eureka Server地址
service-url:
# 单机Eureka server 地址
# defaultZone: http://localhost:7001/eureka
defaultZone: http://localhost:7001/eureka/,http://localhost:7002/eureka/
spring:
application:
# 设置应用名字
name: cloud-order-consumer
logging:
level:
com.hgy.service: debug
# 超时机制
resilience4j:
timelimiter:
instances:
delay:
# 设置超时时间 5秒
timeoutDuration: 2
编写服务提供者提供超时方法
/**
* 超时服务
* @return
*/
@GetMapping("timeout")
public String timeout(){
try {
TimeUnit.SECONDS.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "success";
}
编写服务提供者Controller
@GetMapping("/timeout")
@TimeLimiter(name = "delay",fallbackMethod = "timeoutfallback")
public CompletableFuture<String> timeout() {
log.info("********* 进入方法 ******");
//异步操作
CompletableFuture<String> completableFuture = CompletableFuture
.supplyAsync((Supplier<String>) () -> (paymentFeignService.timeout()));
log.info("********* 离开方法 ******");
return completableFuture;
}
编写服务降级方法
/**
* 超时服务降级方法
* @param e
* @return
*/
public CompletableFuture<ResponseEntity> timeoutfallback(Exception e){
e.printStackTrace();
return CompletableFuture.completedFuture(ResponseEntity.ok("超时啦"));
}
测试