openfeign使用nacos服务注册方式调用的实现
作者:小风010766
文章说明如何将项目注册到Nacos,使OpenFeign调用时通过服务名自动发现服务,无需手动配置URL,需添加Nacos和Sentinel依赖,启动类使用@FeignClient注解并指定fallback,服务名称直接填入value属性即可实现动态调用
需要将项目注册到nacos上,openfeign调用时可以依赖nacos上注册的服务名称,直接进行调用,不再需要像openfeign单独使用时,配置 feignClient的url属性.
消费项目
基于openfeign+sentinel的基础上添加如下pom配置
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>2.2.5.RELEASE</version> </dependency>
启动类添加
@SpringBootApplication @EnableFeignClients @EnableDiscoveryClient public class NacosConsumerApplication { public static void main(String[] args) { SpringApplication.run(NacosConsumerApplication.class, args); } }
对应@FeignClient注解需要填写fallback属性
此时和openfeign单独使用时的唯一区别在于
- nacos调用
@FeignClient(value = "server-application",fallback = TestServiceImpl.class)
此时直接value=服务提供者注册到nacos的服务名称即可。
- openfeign单独使用
@FeignClient(name = "pay",url = "http://10.21.46.61:8880",fallback = TestServiceImpl.class)
@FeignClient(value = "server-application",fallback = TestServiceImpl.class) public interface TestService { @GetMapping("/server/getServer") String getPayMent(@RequestParam("s") String s); }
fallback = TestServiceImpl.class
- 如下:
@Service public class TestServiceImpl implements TestService { @Override public String getPayMent(String s) { return "报错了!!!!!!"; } }
对应bootstrap.yml配置
- 如下:
server: port: 8890 spring: profiles: #环境 active: dev application: name: consumer-application cloud: nacos: discovery: server-addr: 10.xx.xx.xxx:8848 sentinel: transport: #配置sentinel dashboard的地址 dashboard: localhost:8080 feign: sentinel: enabled: true client: config: default: loggerLevel: FULL connectTimeout: 5000 readTimeout: 10000
- server端没有启动
- server端 启动
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。