Feign的权限访问(拦截器)

  • Post author:
  • Post category:其他




Feign的权限访问(拦截器)

当在微服务中进行互相的调用时,将不会走设定的全局拦截器,此时,请求中不包含登录信息,当调用其他微服务中的方法时,将出现没有访问权限问题,这个时候创建Feign的拦截器RequestInterceptor



一、发送请求的微服务中配置

在微服务的config配置中创建Feign的拦截器RequestInterceptor

@Slf4j
@Component
public class MyFeignInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
//        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
//
//        log.info("===request: {}", template.url());
        
        template.header("aaaa", "bbbb");//名称--值
    }
}

将拦截器通过注解交给该微服务的spring扫描



二、在feign-api中配置

同样的在微服务的config配置中创建Feign的拦截器RequestInterceptor,但不可使用注解去交给spring。而是通过下述几种方法实现:



简单

  1. config下创建FeignConfig,将该拦截器作为Bean注入
@Configuration
public class FeignConfig {
    @Bean
    public RequestInterceptor requestInterceptor(){
        return new MyFeignInterceptor();
    }
}
  1. 在定义的clients中的需要使用该功能的Client接口上的@FeignClient()内加上configuration = FeignConfig.class参数,以交给spring管理
@FeignClient(value ="itemservice",path = "/item",configuration = FeignConfig.class)
public interface ItemClient {

    @GetMapping("/list")
    public PageDTO<Item> page(@RequestParam("page") Integer page, @RequestParam("size") Integer size);

    @GetMapping("/{id}")
    public Item getById(@PathVariable Long id);
}



进阶

在resources文件夹下新建文件夹META-INF及文件spring.factories,其中配置交给spring管理的东西

org.springframework.boot.autoconfigure.EnableAutoConfiguration
  =com.hmall.common.config.FeignConfig
//=FeignConfig的全路径名,右键文件名选择Copy Reference

放在这儿的配置将会在初始化时由spring自动装载



版权声明:本文为weixin_52472963原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。