【问题标题】:changing custom annotations on the fly from Spring Cloud Config Server. Is it possible?从 Spring Cloud Config Server 动态更改自定义注释。可能吗?
【发布时间】:2020-11-02 18:39:36
【问题描述】:

上下文:我需要提供一种在生产过程中更改参数值的方法,以尽可能降低性能成本。

目标:我想即时更改注释值并将其立即应用于所有微服务实例。

个人背景和限制:我知道我可以使用 Spring Cloud Config 动态更改参数,如 this article 中所述,我知道动态更改注释涉及一些挑战和陷阱,也如 @987654322 中所述@。

我知道 Spring Cloud Config 可用于设置在启动/启动期间应用于所有微服务实例的集中配置。我用过一点。我想知道是否可以使用它来集中可能影响自定义注释的参数。

一个想象的解决方案是:

...每当我需要一些属性值时

@Value("${config.somePropertyValue}")
private String somePropertyValue;

@Bean
public String somePropertyValue(){
    return somePropertyValue;
}

所有微服务端点中的配置客户端,不仅在应用程序启动时而且在 Spring Cloud Config Server bootstrap.properties 中管理的 somePropertyValue 更新时都必须调用:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
public class SpringConfigClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringConfigClientApplication.class, args);
    }
}

@RefreshScope
@RestController
class MessageRestController {

    @Value("${server.somePropertyValue:Unable to connect to config server}")
    private String somePropertyValue;

    @RequestMapping("/server/somePropertyValue")
    String getSomePropertyValue() {
        return this.somePropertyValue;
    }
}
 

并且在 Spring Cloud Config 中以某种方式维护 somePropertyValue,如果在生产期间发生更改,它会影响所有微服务实例中对 somePropertyValue 进行注释的任何地方的需求。

我目前正在通过在所有侦听/观察主题的 SpringBoot 微服务中添加一个 kafka 消费者来实现此行为,并且当它接收到新消息时,它会即时更改参数值。我在所有公司微服务中创建了一个 Kafka 依赖项,这似乎很奇怪。由于我在类似的场景中使用了 Spring Config,因此我想知道是否有更好的替代方案使用一些开箱即用的 Spring 方法。在我的情况下,性能也非常重要,同步所有参数的一点延迟不是问题。延迟是指在所有微服务中更新参数的两三秒不是问题。

【问题讨论】:

    标签: spring-boot reflection annotations spring-cloud-config spring-cloud-config-server


    【解决方案1】:

    有两种方法可以做到这一点:

    i- 有一个刷新端点,您实际上可以为服务调用它,它实际上会在不重新启动自身的情况下刷新其配置,这非常简洁。例如MS-A8080 上列出,然后在此端点发出POST 请求: localhost:8080/refresh.

    注意: Spring Actuator实际上是在我们用@RefreshScope注释MS-A中的控制器时自动向应用程序添加一个RefreshEndpoint。

    ii- 你也可以使用Spring Cloud Bus,广播一个事件,然后每个服务监听并刷新自己。如果您有几十个服务都使用 Config Server,这很方便,并且您不想像我们在第一种方法中所做的那样逐个访问/refresh 端点。您只想向公共汽车广播一条消息,然后让所有这些东西自动接收。

    参考资料:我在Pluralsight上课时学到的两个概念

    【讨论】:

      猜你喜欢
      • 2020-11-01
      • 1970-01-01
      • 2015-08-28
      • 2019-03-02
      • 1970-01-01
      • 2015-06-18
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多