目录
- 知识点
- 注册中心
- 配置中心
知识点
- 微服务A调用过微服务B时,A会在本地维护一个实例缓存,之后即使 Nacos 宕机,也不再依赖注册中心,远程调用仍能完成,直到缓存过期或更新。
- 如果 Properties和 Nacos 配置中心有相同的配置项,以配置中心的配置为准。
- 如果从 Nacos 导入的多个配置有相同的配置项,以引入时靠前的配置项为准。
注册中心
- pom.xml中引入依赖:- <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
- properties中写入配置:- spring.cloud.nacos.server-addr=127.0.0.1:8848
配置中心
- 在 Nacos 配置列表中创建 aaa.properties和bbb.properties。
- 在微服务中写入配置: - spring.cloud.nacos.config.namespace=public spring.config.import=nacos:aaa.properties?group=DEFAULT_GROUP,nacos:bbb.properties?group=DEFAULT_GROUP
- 通过 - @RefreshScope注解可以使配置变更后自动刷新;也可以通过创建一个类来实现,例如 Nacos 中的配置如下:- order.timeout=30min order.auto-confirm=7d- 创建类: - @Component @ConfigurationProperties(prefix = "order") @Data @RefreshScope public class OrderProperties { String timeout; String autoConfirm; // 驼峰 }- 调用: - @Resource OrderProperties orderproperties; System.out.println(orderproperties.getTimeout()); System.out.println(orderproperties.getAutoConfirm());
- 通过实现 - ApplicationRunner函数式接口,实现在应用启动并初始化完成后,启动配置变更监听:- @SpringBootApplication public class XXApplication { public static void main(String[] args) { SpringApplication.run(XXApplication.class, args); } @Bean ApplicationRunner applicationRunner(NacosConfigManager nacosConfigManager) { return args -> { ConfigService configService = nacosConfigManager.getConfigService(); configService.addListener("xxxx.properties", "DEFAULT_GROUP", new Listener() { @Override public Executor getExecutor() { return Executors.newFixedThreadPool(4); } @Override public void receiveConfigInfo(String configInfo) { System.out.println("Config changed: " + configInfo); } }); }; } }
OpenFeign 远程调用
- 确认生产者的微服务已经在 Nacos 上注册。
- 消费者在 - pom.xml中引入依赖:- <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-loadbalancer</artifactId> </dependency>
- 消费者在启动类上添加 @EnableFeignClients注解。
- 消费者创建接口: - @FeignClient(name = "service-name") public interface XXClient { // "/test" 为被调用微服务的路径 @RequestMapping(value = "/test", method = RequestMethod.POST) void test(XXCmd cmd); }
- 消费者调用接口: - @Resource private transient XXClient xxClient; xxClient.test();
文章标题:Nacos
文章作者:nek0peko
文章链接:https://nek0peko.com/index.php/archives/269/
商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,未经站长允许不得对文章文字内容进行修改演绎。
本文采用创作共用保留署名-非商业-禁止演绎4.0国际许可证
                
hello