以下场景是在未使用配置中心的情况下
场景一:
近期在做项目拆分时, 遇到一个场景, 老系统中的配置文件是分 local,dev,test,prod 多个环境
当系统每拆分一个小项目时, 相同的配置需要被拷贝多次
场景二:
使用rocketMQ时, 生产者在不同的项目中, 每个项目都需要拷贝一份mq的配置, 并且还需要区分环境
如果能把生产者代码和配置文件封装成一个starter, 那么发送mq消息的项目, 只需引入一个jar包即可
大概步骤:
1.创建一个新的pringboot项目
2.添加配置文件, 如: mq-default.yml(存放一些通用的配置), mq-[local,dev,test,prod].yml(存放不同环境的配置)
3.添加mq相关配置类(略, 参考阿里云文档)
public class MessageMQResourceFactory extends DefaultPropertySourceFactory {
Logger log = LoggerFactory.getLogger(MessageMQResourceFactory.class);
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
String sourceName = (name == null) ? resource.getResource().getFilename() : name;
if (sourceName == null) {
return super.createPropertySource(name, resource);
}
YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
ClassPathResource classPathResource = null;
if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) { // 如果是带 yml后缀的就是 配置文件全名, 直接new
classPathResource = new ClassPathResource(sourceName);
} else if (StringUtils.isNotBlank(sourceName)) {
// local,dev
String[] split = sourceName.split(",");
String env = split[0];// spring 激活的环境
String mqEnv = split[1];// mq 激活的环境
if (!"null".equals(mqEnv) && isLoadable(mqEnv)) {
// 是否存在 指定mq环境的参数
classPathResource = new ClassPathResource("mq-" + mqEnv + ".yml");
} else {
// mqEnv没有设置值时, 使用env
classPathResource = new ClassPathResource("mq-" + env + ".yml");
}
}
factory.setResources(classPathResource);
factory.afterPropertiesSet();
Properties properties = factory.getObject();
if (properties != null) {
return new PropertiesPropertySource(sourceName, properties);
}
return super.createPropertySource(name, resource);
}
/**
* 是否是 可加载 的mq配置文件
*/
boolean isLoadable(String tempEnv) {
boolean contains = "local,dev,test,prod".contains(tempEnv);
if (!contains) {
log.error("期望加载的mq配置文件不存在! 请检查配置参数[rocketmq.profiles.active], 当前配置的环境为:{}", tempEnv);
}
return contains;
}
}
@Configuration
@ConfigurationProperties(prefix = "rocketmq")
@Data
@PropertySource(value = {"classpath:mq-default.yml", "${spring.profiles.active:local},${mq.profiles.active:null}"}, factory = MessageMQResourceFactory.class)
public class MyProperties {
private String groupId;
private String topic;
private String tag;
}
使用:
1.默认情况下 使用spring.profiles.active指定的 环境配置, 如系统指定了 local, 则mq加载的是 mq-local.yml; 如果是dev, 则加载mq-dev.yml
2.当希望使用指定的mq环境, 则配置参数 如: mq.profiles.active=dev
参考:
spring boot的profile-specific properties