FeignClient设置动态url方式
作者:scanklm
文章介绍了如何在Spring Cloud环境下使用FeignClient实现负载均衡,通过配置Nacos和FeignClient属性,可以实现服务间的负载均衡调用
FeignClient设置动态url
1、引入org.springframework.cloud:spring-cloud-loadbalancer依赖包
2、feign server端nacos添加loadbalancer.ribbon.enabled配置
spring: cloud: loadbalancer: ribbon: enabled: false nacos: config: server-addr: ${CONFIG_NACOS_HOSTS:192.168.96.5:8848} file-extension: yaml group: ${CONFIG_NACOS_GROUP:DEFAULT_GROUP} discovery: server-addr: ${DISCOVERY_NACOS_HOSTS:192.168.96.5:8848} # ip: ${LOCAL_IP_ADDRESS:192.168.96.1}
3、FeignClient属性name与URL一定要指定
@FeignClient(url = “http://localhost:8080/xxxxxxx”, name = “xxx”)
name
属性,是@FeignClient 注解必要的,不定义会报错。url
属性,一定要指定,值无所谓,因为最终都会被方法的URI参数对应值替换掉,添加这个属性的作用就是将接口的代理对象变成feign.Client.Default(LoadBalancerFeignClient),这样就绕过了从nacos取节点地址这一步(细节参见 FeignClientFactoryBean.getTarget())
4、FeignClient注解类接口添加URI参数
import java.net.URI; @FeignClient(name = "xxx", url = "EMPTY", configuration = FeignClientConfig.class) public interface SocketApiClient { @PostMapping("/test") R<?> test(URI uri, @RequestBody Data data); }
如上
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。