【问题标题】:Refresh a Bean without configuration change with @RefreshScope使用 @RefreshScope 在不更改配置的情况下刷新 Bean
【发布时间】:2017-07-15 10:54:48
【问题描述】:

我有一个@Configuration 类如下:

@Configuration
public class SampleKieConfiguration {

    @Bean
    public KieServices kieServices() {
        return KieServices.Factory.get();
    }

    @Bean
    public KieContainer kieContainer() {

        ReleaseId releaseId = kieServices().newReleaseId("groupId", "artifactId", "version");
        KieContainer kieContainer = kieServices().newKieContainer(releaseId);
        kieServices().newKieScanner(kieContainer).start(10_000);
        return  kieContainer;
    }

    @Bean
    public KieBase kieBase() {

        KieBaseConfiguration kieBaseConfiguration = kieServices().newKieBaseConfiguration();
        kieBaseConfiguration.setOption(EqualityBehaviorOption.EQUALITY);
        kieBaseConfiguration.setOption(EventProcessingOption.CLOUD);
        return kieContainer().newKieBase(kieBaseConfiguration);
    }
}

kieServices().newKieScanner(kieContainer).start(10_000); 行基本上轮询远程 maven 存储库并每 10 秒刷新一次 kieContainer 对象,如果有新的工件。

在我的上层(例如服务层)的某个地方,我有:

@Service
@RefreshScope
public class SampleService {

    @Autowired
    private KieBase kBase;

}

当我调用/refresh 端点时,据我所知,kBase 对象没有刷新(至少没有使用新的kieContainer 对象)。我没有集中配置,当我致电/refresh 时收到警告。我想要实现的是每次刷新kieContainer 时都有一个新的kBase 对象。我怎样才能做到这一点?谢谢!

【问题讨论】:

    标签: java spring spring-boot spring-cloud spring-cloud-config


    【解决方案1】:

    如文档所述:

    @RefreshScope works (technically) on an @Configuration class, but it might lead to surprising behaviour:
    e.g. it does not mean that all the @Beans defined in that class are themselves @RefreshScope.
    Specifically, anything that depends on those beans cannot rely on them being updated when a refresh is initiated,
    unless it is itself in @RefreshScope (in which it will be rebuilt on a refresh and its dependencies re-injected,
    at which point they will be re-initialized from the refreshed @Configuration).
    

    所以我猜你还必须直接在 KieBase @Bean 上注释 @RefreshScope

    【讨论】:

      【解决方案2】:

      刷新不会遍历层次结构。它只是清除缓存并在下一次引用(通过它创建的代理)时重新创建 bean。在您的情况下,由于 KieBase 不是 @RefreshScope,因此不会重新创建它。所以将@RefreshScope 添加到KieBase 声明中。如果SampleService 真的不需要重新创建,请删除@RefreshScope 注释。

      【讨论】:

      • 谢谢,感谢您的回答。但现在我收到java.lang.ClassCastException: $Proxy11 cannot be cast to some.package.KnowledgeBaseImpl。有什么想法吗?
      猜你喜欢
      • 2016-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2011-09-01
      • 2016-05-25
      相关资源
      最近更新 更多