1Feign调用动态服务路径请求(构造器的方式请求)
//构造器
@Component
public class InsFeignClientAdapter implements ApplicationContextAware {
//注册中心前缀
private static final String SERVICE_PREFIX = "aaa-";
//注册中心后缀
private static final String SERVICE_SUFIX = "-api-new";
//环境上下文
private static final String CONTEXT_ID = "名字-INS";
private static ApplicationContext applicationContext = null;
private static final Map<String, Object> BEAN_CACHE = new ConcurrentHashMap<>();
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (InsFeignClientAdapter.applicationContext==null){
InsFeignClientAdapter.applicationContext = applicationContext;
}
}
public static <T> T build(String company, Class<T> targetClass) {
//注册中心拼接
String serverName = SERVICE_PREFIX+company+SERVICE_SUFIX;
return buildClient(serverName, targetClass);
}
private static <T> T buildClient(String serverName, Class<T> targetClass) {
T t = (T) BEAN_CACHE.get(serverName);
if (Objects.isNull(t)) {
FeignClientBuilder.Builder<T> builder = new FeignClientBuilder(applicationContext).forType(targetClass, serverName);
t = builder.contextId(CONTEXT_ID).build();
BEAN_CACHE.put(serverName, t);
}
return t;
}
}
//接口
public interface InsFeignClient {
//通过名称去找到对应的请求
@RequestMapping(value = "/bbbbb", method = RequestMethod.POST)
Object bbbbb(@RequestBody JSONObject httpEntity);
}
发送请求代码
InsFeignClient client = InsFeignClientAdapter.build(company,InsFeignClient.class);
Object obj = client.bbbbb(request);
2Feign调用静态服务路径请求(注解注入的方式)
@Component
//@FeignClient:微服务客户端注解,value:指定微服务的名字,这样就可以使Feign客户端直接找到对应的微服务
@FeignClient(value = "SPRINGCOULD-PROVIDER-DEPT")
public interface DeptClientService {
@GetMapping("/dept/queryById/{id}")/
Dept queryById(@PathVariable("id") Long id);
@GetMapping("/dept")/
Dept queryByOne(Long id);
}
@Autowired
DeptClientService ds;
方法
ds.queryById(全路径,Dept.class);
ds.queryByOne(id);
3不需要扫描的方式发送请求
@Component
public class RestTemplateConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
Object obj = restTemplate.getForObject(url, Object.class);
注意:如果使用restTemplate出现冲突时
1使用@Primary指定一个主bean
2使用@Qualifier("方法名")指定bean的名称