首页 > 解决方案 > 在长时间运行的过程中刷新之前捕获 spring @RefreshScope bean 的值

问题描述

我正在构建一个微服务系统,并使用 Spring cloud config 通过 GitHub webhook 自动刷新来集中配置。

一切正常,除了在某些情况下,我们需要 bean 的值在整个过程中保持不变。

例如,如果在进程中间发生刷新,这样的代码最终会导致客户端收到更新的值:

@RefreshScope
@ConfigurationProperties
@Component
@Getter
@Setter
public class ServiceConfig {
    @Value("${example.property}")
    private String exampleProperty;
}

@RestController
@RequestMapping("/department")
public class DepartmentController {
    @Autowired
    private ServiceConfig serviceConfig;

    @GetMapping("/config")
    public ResponseEntity<String> getConfig() {
        return ResponseEntity.ok(serviceConfig.getExampleProperty());
    }

    @GetMapping("/config-delayed")
    public ResponseEntity<String> getConfigWithDelay() throws InterruptedException {
        Thread.sleep(30000L);
        return ResponseEntity.ok(serviceConfig.getExampleProperty());
    }
}

我知道String value = serviceConfig.getExampleProperty()在线程休眠之前添加一个应该可以工作,但是在具有许多方法调用的复杂场景中,它将非常难以控制和维护。

有没有简单的方法来实现这一点?我们正处于项目的设计阶段,因此欢迎使用除 spring 之外支持此行为的其他配置管理解决方案。

标签: javaspringspring-cloudspring-cloud-config

解决方案


推荐阅读