OpenFeign
# 基础
官⽹: https://docs.spring.io/spring-cloud-openfeign/reference/spring-cloud-openfeign.html#spring-cloud-feign
OpenFeign 是—个声明式远程调用客户端
# 引入依赖
可以在父项目中统一引入
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
# 开启功能
@EnableFeignClients
@SpringBootApplication
public class Application {
public static void main(String [] args) {
SpringApplication.run(Application.class, args);
}
}
# 远程调用⭐
使用SpringMVC的注解在@Controller注解上就是前端请求,在@FeignClient注解就是远程调用
@FeignClient("stores")
public interface StoreClient {
@RequestMapping(method = RequestMethod.GET, value = "/stores")
List<Store> getStores();
@GetMapping("/stores")
Page<Store> getStores(Pageable pageable);
@PostMapping(value = "/stores/{storeId}", consumes = "application/json", params = "mode=upsert")
Store update(@PathVariable("storeId") Long storeId, Store store);
@DeleteMapping("/stores/{storeId:\\d+}")
void delete(@PathVariable Long storeId);
}
@FeignClient默认参数是value,表示向注册中心的哪个微服务发送请求⭐
如果设置了url参数,表示会直接访问指定的固定地址(调用第三方API时),跳过注册中心。此时 value
不参与实际路由。
技巧:编写Feign时,如果是调用自己的API可以直接将Controller的方法复制粘贴
# 面试题
客户端负载均衡与服务端负载均衡区别
客户端负载均衡是从注册中心获取被调用方的所有API地址,由客户端用负载均衡算法决定调用哪个服务地址
服务端负载均衡是由被调用方的中间代理(如 Nginx)决定请求转发到哪个后端实例。
# 进阶配置
# 开启日志
设置指定包路径的日志级别
logging:
level:
com.atguigu.order.feign: debug
//注册bean
@Bean
Logger.Level feignLoggerLevel() {
return Logger.Level.FULL;
}
# 超时控制
spring:
cloud:
openfeign:
client:
config:
default:
logger-level: full
connect-timeout: 1000
read-timeout: 2000
service-product:
logger-level: full
connect-timeout: 3000
read-timeout: 5000
# 重试机制
@Bean
Retryer retryer(){
return new Retryer.Default();
}
# 拦截器
Interceptor
public class XTokenRequestInterceptor implements RequestInterceptor{
/**
*请求拦截器
*@param template请求模板
*/
@Override
public void apply(RequestTemplate template){
template.header(name:"X-Token",UUID.randomUUID().tostring());
}
}
# fallback——兜底返回
使用兜底返回需要开启sentinel
引⼊ sentinel
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
开启熔断
feign:
sentinel:
enabled: true
编写fallback函数
package com.feign
@FeignClient(value = "service-product",fallback = ProductFeignClientFallback.class) // feign客户端
public interface ProductFeignClient {
//mvc注解的两套使⽤ 逻辑
//1、标注在Controller上,是接受这样的请求
//2、标注在FeignClient上,是发送这样的请求
@GetMapping("/product/{id}")
Product getProductById(@PathVariable("id") Long id);
}
package com.fallback
@Component
public class ProductFeignClientFallback implements ProductFeignClient {
@Override
public Product getProductById(Long id) {
System.out.println("兜底回调 ....");
Product product = new Product();
product.setId(id);
product.setPrice(new BigDecimal("0"));
product.setProductName("未知商品");
product.setNum(0);
return product;
}
}
上次更新: 2025/6/10 19:14:39