1.在启动类上开启Feign功能
不开会提示找不到所需要的bean
Consider defining a bean of type in your configuration
@SpringBootApplication
@EnableFeignClients
public class AuthApplication {public static void main(String[] args) {SpringApplication.run(AuthApplication.class, args);}}
2.编写Feign客户端:
@FeignClient(value = "checkcode" ,fallbackFactory = CheckCodeClientFactory.class)
public interface CheckCodeClient {//来自checkcode模块,checkcodecontroller下的方法@PostMapping(value = "/verify")public Boolean verify(String key, String code);
}
这个客户端主要是基于SpringMVC的注解来声明远程调用的信息,比如:
服务名称:checkcode
熔断降级:CheckCodeClientFactory
请求方式:POST(请求的方法是其他模块中已有的方法,此处的方法的签名体和被调用的方法的签名体一致)
请求路径:/verify
请求参数:key,code
返回值类型:布尔
这样,Feign就可以帮助我们发送http请求,无需自己使用RestTemplate来发送了。
3.熔断方法:
/*** @author YCL* @version 1.0* @description 熔断方法* @date 2023-02-27 15:41*/
@Slf4j
@Component
public class CheckCodeClientFactory implements FallbackFactory<CheckCodeClient> {@Overridepublic CheckCodeClient create(Throwable throwable) {return new CheckCodeClient() {@Overridepublic Boolean verify(String key, String code) {log.debug("调用验证码服务熔断异常:{}",throwable.getMessage());return null;}};}
}
trick:
如果熔断方法和feign执行失败的返回值一致的话,我们无法区别到底是熔断了,还是feign执行失败了。所以此处return 的是null。而不是布尔类型,注意feign的verify方法的返回值是布尔类型。