注解上动态获取Nacos配置
统一Nacos配置
rocketmqs:
nameServer: 127.0.0.1:9876
topic: flight-xx-log
consumerGroup: flight-test
accessKey: flightmq
secretKey: 123456
enable: true
在代码中获取 Nacos 上的配置
@RefreshScope
@Component
@Slf4j
public class RocketMQConsumer implements RocketMQListener<String> {
@Value("${rocketmqs.appName}")
private String appName;
public RocketMQConsumer(TrcFlightChgInfoMqService flightChgInfoMqService) {
log.info("888");
this.flightChgInfoMqService = flightChgInfoMqService;
}
}
注解上获取 Nacos 配置方法 有两种 这个需要看情况而定,这种不行就用另一种 方法1: 使用 “${}”,获取,RocketMQ/RabbitMQ 的注解中配置是可以的,例如下面代码
@Component
@Slf4j
@RocketMQMessageListener(topic = "${rocketmqs.topic}", consumerGroup = "${rocketmqs.consumerGroup}",
accessKey = "${rocketmqs.accessKey}", secretKey = "${rocketmqs.secretKey}",
nameServer = "${rocketmqs.nameServer}")
@ConditionalOnProperty(value = "rocketmqs.enable", matchIfMissing = false,havingValue = "true")
public class RocketMQConsumer implements RocketMQListener<String> {
public RocketMQConsumer(TrcFlightChgInfoMqService flightChgInfoMqService) {
log.info("888");
this.flightChgInfoMqService = flightChgInfoMqService;
}
}
方法2: 不用"${}",直接获取,RabbitMQ是可以使用的;@ConditionalOnProperty 注解 “rocketmqs.enable” 这样才是对的
在这里插入代码片
@Component
@Slf4j
@ConditionalOnProperty(value = "rocketmqs.enable", matchIfMissing = false,havingValue = "true")
public class RocketMQConsumer implements RocketMQListener<String> {
public RocketMQConsumer(TrcFlightChgInfoMqService flightChgInfoMqService) {
log.info("888");
this.flightChgInfoMqService = flightChgInfoMqService;
}
}
如何测试上图 @ConditionalOnProperty 的 value 属性是否成功读取到 Nacos 的配置:
- 创建一个构造函数,并且记录一个日志(随便记录);
比如:
public RocketMQConsumer(TrcFlightChgInfoMqService flightChgInfoMqService) {
log.info("888");
this.flightChgInfoMqService = flightChgInfoMqService;
}
结果图:
- 启动项目,此时 rocketmqs.enable 的配置是 true,启动成功后在控制台搜索记录的日志,查看是否有打印在控制台, 有记录则表示成功;
- 修改 rocketmqs.enable 的配置为 false ,重下新启动项目,启动成功后查看控制台是否有日志记录,没有则表示已关闭该配置。
|