feign

feign url 自动更新

Posted by lijian on March 20, 2020

编写处理类

  • 一个方法处理Apollo key 改变事件,监听到改变的key 为关心的key , 开始计算反射关系
  • 一个方法处理 requestInterceptor , 如果需要改变,则重新修改 requesttemplate 的 target ``` import cn.hutool.core.util.ReflectUtil; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import com.jovision.vpass.pms.PmsApplication; import com.jovision.vpass.pms.common.thread.ApplicationConfig; import feign.RequestTemplate; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.StringUtils; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.PostMapping;

import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects;

/**

  • @author lijian@jovision.com
  • @date 2020/9/11 / @Slf4j @Component public class DynamicCallRequestInterceptor { /
    • 是否改变过 elb */ private volatile boolean hasChanged = false; /**
    • 方法映射map */ private Map<String, List> methodMapping = Maps.newHashMap();

    private final String globalKey = “global.elb.inside.”;

    /**

    • Apollo key change */ public void change(String changeKey) { if (StringUtils.isNotEmpty(changeKey) && changeKey.contains(globalKey)) { hasChanged = true; if (methodMapping.size() <= 0) { EnableFeignClients enableApolloConfig = PmsApplication.class.getAnnotation(EnableFeignClients.class); Class<?>[] clients = enableApolloConfig.clients(); for (Class<?> client : clients) { FeignClient feignClient = client.getAnnotation(FeignClient.class); String name = feignClient.name(); methodMapping.put(name, Lists.newArrayList()); Method[] methods = ReflectUtil.getMethods(client); for (Method method : methods) { PostMapping postMapping = method.getAnnotation(PostMapping.class); String[] value = postMapping.value(); methodMapping.get(name).addAll(Arrays.asList(value)); } } } } }

    /**

    • 动态调用 */ public void dynamicCallRequestInterceptor(RequestTemplate requestTemplate) { if (!hasChanged) { return; } methodMapping.forEach((name, methodList) -> { if (methodList.contains(requestTemplate.path())) { Object url1 = ApplicationConfig.getConfig(globalKey + name); // todo lj 注意这里现在调用的是 test Object url = ApplicationConfig.getConfig(globalKey + “test.” + name); if (Objects.nonNull(url)) { requestTemplate.target(“http://” + url.toString()); } } }); } }

```