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;
}
}
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;
}
}
3.Feign接口模板
public interface FeignClientTemplate {
@PostMapping("/TEMPLATE/list")
Result<List<ResDTO>> list(@RequestBody ReqDTO dto);
}
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);
}
}
}
}
5.使用
public void use(ReqDTO dto){
FeignClientTemplate client = FeignClientUtils.build("TEXT","TEXT",FeignClientTemplate.class);
Result< List<ResDTO>> result = client.list(dto);
}