springcloud微服务学习(2)-关于雪崩熔断器
|——feign结合Hystrix使用
(1)在pom中添加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<version>0.2.2.RELEASE</version>
</dependency>
<!--hystrix依赖,主要是用 @HystrixCommand -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
(2)在调用其他服务类的主服务类上service-stu中添加hystrix配置
# 开启熔断机制
feign.hystrix.enabled=true
# 设置hystrix超时时间,默认1000ms
hystrix.metrics.polling-interval-ms=6000
(3)在service-stu的client包里创建熔断器的实现类 OssFileDegradeFeignClient继承OssClient
package com.atrsm.stu.client.Impl;
import com.atrsm.commonutils.R;
import com.atrsm.stu.client.OssClient;
import org.springframework.stereotype.Component;
/**
* @author Ro shinMM
* @create 2020-08-18 16:36
*/
@Component
public class OssFileDegradeFeignClient implements OssClient {
/*
当你的调用时正确的这个方法不会执行
当你调用出错了,这个方法就会执行
*/
@Override
public R deloss(String filepath) {
System.out.println("删除头像出错了");
return R.error().message("删除头像出错了");
}
}
(4)修改原OssClient注解
package com.atrsm.stu.client;
import com.atrsm.commonutils.R;
import com.atrsm.stu.client.Impl.OssFileDegradeFeignClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* @author Ro shinMM
* @create 2020-08-18 10:59
*/
//修改后的FeignClient注解(fallback)
@FeignClient(name = "service-oss",fallback = OssFileDegradeFeignClient.class)
@Component
public interface OssClient {
@DeleteMapping("/oss/fileoss/deloss/{filepath}")
public R deloss(@PathVariable("filepath") String filepath);
}
(5)在启动service-stu而不启动service-oss后启动调试后
说明熔断器配置成功