• 动态feign调用


    1.上下文类

    @Component("springContextS")
    public class SpringContextS implements ApplicationContextAware{
    
        private static ApplicationContext applicationContext;
    
        public void setApplicationContext(ApplicationContext applicationContext) throw BeansException {
            SpringContextS.applicationContext = applicationContext;    }
    
        public static ApplicationContext getApplicationContext(){
           return applicationContext;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    2.Feign工具类

    public class FeignClientUtils {
        private static final Map<String,Object> FEIGN_CACHE = new ConcurrentHashMap();
        private static <T> T build(String type,String server,Class<T> clazz){
             String key = String.format("%s-%s",type,server);
             T t = (T) FEIGN_CACHE.get(key);
             if(Objects.isNull(t)){
                FeignClientBuilder.Builder<T> builder = new FeignClientBuilder(SpringContextS.getApplicationContext()).forType(clazz,server):
                builder = builder.contextId(UUID.randomUUID().toString());
                t = builder.build();
                FEIGN_CACHE.put(key,t);
             }
             return t;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    3.Feign接口模板

    public interface FeignClientTemplate {
       @PostMapping("/TEMPLATE/list")
       Result<List<ResDTO>> list(@RequestBody ReqDTO dto); 
    }
    
    • 1
    • 2
    • 3
    • 4

    4.Feign拦截器

    @Configuration
    public class TempFeignInterceptor implements RequestInterceptor{
        @Override
        public void apply(RequestTemplate template){
            String server = template.feignTarget().name.toLowerCase();
            String url = "/" + server+"/test"
            String tempUrl = template.url();
            if(StringUtils.isNotEmpty(templateUrl){
                if(tempUrl.contains("TEMPLATE")){
                   template.uri(tempUrl.replace("TEMPLATE",url);
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    5.使用

    
    public void use(ReqDTO dto){
        FeignClientTemplate client = FeignClientUtils.build("TEXT","TEXT",FeignClientTemplate.class);
       Result< List> result =  client.list(dto);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
  • 相关阅读:
    Nginx实现负载均衡
    Pandas
    JMeter测试工具介绍
    饮酒后回家途中死亡,同饮者是否担责?
    亚马逊黑色星期五什么时候开始?
    ubuntu 安装 gparted
    1093 Count PAT‘s
    【Make YOLO Great Again】YOLOv1-v7全系列大解析(Head篇)(完整版)
    leetcode LCR 007 mid. 三数之和。对撞指针解法
    杭电oj--平方和与立方和
  • 原文地址:https://blog.csdn.net/ks2356/article/details/133983467