
快速入门使用引入依赖spring-cloud-starter-openfeign启动类加上注解EnableFeignclientOpenFeign的使用和SpringMvc完全是反过来的非常好理解接下来我们举例说明注解SpringMVCOpenFeign通用性Controller后端页面控制器不使用不通用RestControllerJSON 接口控制器不使用不通用RequestMapping定义请求路径定义远程接口路径通用Get/PostMapping限定请求方式限定远程请求方式通用RequestParam获取 url 参数拼接查询参数通用PathVariable获取路径变量填充路径占位符通用RequestBody接收 JSON 请求体传递 JSON 请求体通用代码举例对比SpringMVCRestController public class OrderController{ GetMapping(/order/{orderId}) public Order getOrderInfo(PathVariable (orderId)Long orderId){} }OpenFeign注意事项openfeign远程调用自动实现负载均衡只要是业务相关的代码Controller里面的代码可以直接拿到FeignClient里面用负载均衡服务端负载均衡订单服务-→请求商品服务-→负载均衡调用商品服务的实例客户端的负载均衡多个用户点击服务-→请求到统一网关→负载均衡的分配到对应的服务器来处理请求日志开启openfeign默认调用远程是不输出日志的第一步配置中修改日志级别logging.level. 类的reference路径 :debug第二步配置bean超时处理防止某个服务单点长时间卡死导致整体系统不可用默认超时时间 连接超时连接服务事件10s 读超时业务处理事件60s修改默认的全局超时配置spring.cloud.openfeign.client.config.defalt.……对单个服务进行配置只需要在defalut下方再起一行写上对应的服务名称即可测试一下我们在productController里面让线程睡眠5秒触发连接超时连接重试Configuration public class FeignConfig { Bean public Retryer feignRetryer() { // 参数每100ms重试一次最多等1000ms最多重试3次 return new Retryer.Default(100, 1000, 3); } }RequestInterce请求拦截器:每次发送远程调用前进行拦截Component public class FeignAuthInterceptor implements RequestInterceptor { Override public void apply(RequestTemplate template) { // 给每个 Feign 请求加一个请求头 template.header(Authorization, Bearer xxx-token-xxx); // 或者从当前请求上下文拿 Token // RequestAttributes attributes RequestContextHolder.getRequestAttributes(); // String token ((ServletRequestAttributes) attributes).getRequest().getHeader(Authorization); // template.header(Authorization, token); } }和SpringMVC的请求拦截器的对比Component public class MyInterceptor implements HandlerInterceptor { Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { System.out.println(请求来了 request.getRequestURI()); return true; // true 放行false 拦截 } } 然后在配置类里注册才能生效 Configuration public class WebConfig implements WebMvcConfigurer { Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new MyInterceptor()).addPathPatterns(/**); } }远程调用的fallback兜底机制 即发生调用错误的时候更改配置:openfeign.sentinel.enabled:true在远程调用的注解中加上fallbackFeignClient(value service-product,fallback ProductClientFallback.class) public interface ProductClient { GetMapping(/product) Product getProduct(RequestParam Long productId); }编写一个类实现当前远程调用的接口Component public class ProductClientFallback implements ProductClient { Override public Product getProduct(Long productId) { Product product new Product(); product.setId(String.valueOf(productId)); product.setName(fallback-未知商品); product.setDescription(未知); product.setPrice(0D); product.setNumber(0L); return product; } }