SpringBoot动态刷新yml中的配置

/**
 * 动态刷新yml配置Controller
 * @author Forest
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/refresh")
public class RefreshYmlController {

    private final ContextRefresher contextRefresher;

    private final Environment environment;

    private final MockConfig mockConfig;


    /**
     * 刷新是否调用mock数据配置
     */
    @GetMapping("/test")
    public String updateMockProperties() throws IOException {
        this.updateYamlFile();
        if (log.isInfoEnabled()) {
            log.info("开始刷新Context");
        }
        contextRefresher.refresh();
        if (log.isInfoEnabled()) {
            log.info("刷新Context结束");
        }
        if (log.isInfoEnabled()) {
            log.info("环境:{}。刷新是否调用mock数据配置成功!刷新后isMock为:{}",
                    environment.getActiveProfiles(), mockConfig.isValue());
        }
        return "刷新是否调用mock数据配置成功!刷新后isMock为:" + mockConfig.isValue();
    }


    @SuppressWarnings("unchecked")
    private void updateYamlFile() throws IOException {
        String filePath = "";
        String fileName = "";
        if (environment.acceptsProfiles(EnvironmentEnum.LOCAL.getEnvironment())) {
            filePath = "/config/application-local.yml";
            fileName = "application-local.yml";
        }
        if (environment.acceptsProfiles(EnvironmentEnum.TEST.getEnvironment())) {
            filePath = "/config/application-test.yml";
            fileName = "application-test.yml";
        }
        Yaml yaml = new Yaml();
        FileWriter fileWriter;
        InputStream inputStream = this.getClass().getResourceAsStream(filePath);
        Map<String, Object> yalMap = (Map<String, Object>) yaml.load(inputStream);
        Map<String, Object> esMap = (Map<String, Object>) yalMap.get("isMock");
        esMap.put("value", !mockConfig.isValue());
        // 字符输出
        fileWriter = new FileWriter(fileName);
        // 用yaml方法把map结构格式化为yaml文件结构
        fileWriter.write(yaml.dumpAsMap(yalMap));
        // 刷新
        fileWriter.flush();
        // 关闭流
        fileWriter.close();
        if (log.isInfoEnabled()) {
            log.info("更新配置文件结束");
        }
    }
}
经验分享 程序员 微信小程序 职场和发展