-
配置依赖
同搭建生产者服务一样,将依赖加入,并需要新增添spring-cloud-starter-netflix-ribbon依赖和spring-cloud-starter-openfeign依赖
ribbon依赖是为了进行RestTemplate的测试,而openfeign的依赖是进行Feign调用的测试。 -
配置启动类
@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients(basePackages = "cn.kiring")
public class NacosConsumerDemoApplication {
// 配置RestTemplate
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(NacosConsumerDemoApplication.class, args);
}
}
相比生产者,需要新增@EnableFeignClient进行Feign的使用。
因为要使用RestTemplate,所以需要进行RestTemplate的bean的配置。
在bean上贴上@LoadBalanced注解默认使用集群轮询
踩坑:因为RestTemplate在使用service_name服务名当做URI的时候,服务名是不能有下划线,否则就报错:Request URI does not contain a valid hostname
所以在设值spring.application.name的时候,不能使用下划线。
-
配置FeingClient,并进行调用,能够完成正常调用
并且重新发布配置,能够马上刷新环境配置(需要贴上@RefreshScope) -
编写配置文件
server:
port: 8021
spring:
cloud:
nacos:
config:
server-addr: 192.168.116.210:9000
file-extension: yaml
discovery:
server-addr: 192.168.116.210:9000
application:
name: nacos-consumer-demo
feign:
client:
config:
default:
connectTimeout: 5000 # 连接超时时间
readTimeout: 5000 # 运行超时时间
官方文档:https://github.com/alibaba/spring-cloud-alibaba/wiki/Nacos-discovery