前言
本文依托于
在SpringCloud的使用过程中我总结为三步曲。
- 引入spring-cloud-starter相应jar包
- properties或yml加入相关配置
- 启动类加上@Enable相关注解
客户端feign+hystrix
1.引入jar
老版本引入spring-cloud-starter-feign.jar后就集成了hystrix功能不需要额外引入jar包。但新版本引入的是spring-cloud-starter-openfeign.jar,如果不引入hysrtix的jar包,hystirx不生效。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.properties加入配置
老版本的配置是feign.hystrix.enable=true,就会生效,新版本不是。槽点太多,无话可说。
feign.circuitbreaker.enabled=true
3.启动类加入注解
无需额外加入注解
4.定义回调函数的类
需要实现对应的Feign接口
package com.ykq.api.hystrix;
import com.ykq.api.HelloFeign;
import org.springframework.stereotype.Component;
/**
* @author: kqyin
* @date: 2021/11/25 10:00
* @Description: helloFeign断路器
*/
@Component
public class HelloFeignHystrix implements HelloFeign {
public String hello() {
return "hello world, I am feign hystrix1";
}
}
5.@FeignClient指定回调函数
指定fallback回调函数类
package com.ykq.api;
import com.ykq.api.hystrix.HelloFeignHystrix;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
/**
* @author: kqyin
* @date: 2021/11/24 15:06
* @Description:
*/
@FeignClient(name= "springcloud-producer", fallback= HelloFeignHystrix.class)
public interface HelloFeign {
@RequestMapping(value = "/hello")
String hello();
}
服务端hystrix
1.引入jar
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
2.properties加入配置
无需加入额外配置
3.启动类加入注解
以前的版本是推荐使用@EnableCircuitBreaker,现在这个注解已经@Deprecated,不推荐使用。
推荐使用@EnableHystrix
@EnableHystrix
实际上@EnableHystrix还是由@EnableCircuitBreaker组成的。
4.定义并指定回调函数
使用@HystrixCommand(fallbackMethod = “”)注解
package com.ykq.test;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author: kqyin
* @date: 2021/11/25 13:57
* @Description:
*/
@RestController
public class TestController1 {
@HystrixCommand(fallbackMethod = "hystrixFallBack")
@RequestMapping(value = "/test")
public String hystrix() {
throw new RuntimeException();
}
public String hystrixFallBack() {
return "I am hystrixFallBack1";
}
}
问题
1.加入了feign.hystrix.enable=true配置,feign+hystrix不生效
上面已经提及,可以使用feign.circuitbreaker.enabled=true试试。
或者可以在application.properties中打出feign看看有啥提示,寻找相应的配置提示。不要盲目相信包括我的文档在内的文档。SpringCloud更新版本后,官方文档都不更新,坑。上面的配置确认后,还不行则引入hystrix的jar。