使用@RefreshScope

时间:2017-02-24 14:46:21

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

我有一个@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;

}

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:-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).

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