定期刷新Spring bean实例属性的最佳实践? [英] refresh Spring bean instance property periodically best practice?
问题描述
我有一个spring组件,它调用AWS来做一些事情。它获取持续时间< = 1h的临时会话凭证,以在我的应用程序开始时初始化AWS服务客户端。 AWS服务客户端被设置为Bean的实例属性。然后,在这小时之后,我需要使用此bean阻塞所有线程,并刷新服务客户端使用的临时会话凭据。
I have a spring component that calls AWS to do some stuff. It acquires temporary session credentials lasting for <=1h to initialize the AWS service client at the start of my app. The AWS service client is set as an instance property of the bean. Then after this hour, I need to block all threads using this bean and refresh the temporary session credentials used by the service client.
有没有建议的方法?任何提示/提示都会被赞赏
Is there any recommended way to do this? Any hints/clues are appreciated
推荐答案
我认为最好将它作为一种实现(也是最简单的)代理。
I think that it would be best (and easiest) for you to implement it as a sort of a proxy.
首先,为要刷新的对象创建一个类。让我们称之为 RefreshableProperty
。
First, create a class for an object that will be refresh. Lets call it RefreshableProperty
.
然后,您需要具有以下职责的代理:
Then you need the proxy which will have following responsibilities:
- 它将注入需要访问
RefreshableProperty
- 它可以具有以<$ c注释的方法$ c> @Scheduled (带有某些cron表达式),将定期调用
- 此方法将连接到您的配置服务器并下载新的设置放入
RefreshableProperty
- 的新实例中,在此操作结束时,您的代码应交换引用,以便指向新对象
<的任何地方li>它将具有类型为
AtomicReference< RefreshableProperty>
的字段的实例- It will be injected into any place that requires access to
RefreshableProperty
- It would have an instance of a field of type
AtomicReference<RefreshableProperty>
- It can have a method annotated with
@Scheduled
(with some cron expression) that would be invoked periodically - This method would connect to your configuration server and download new settings which would be put into a new instance of
RefreshableProperty
- At the end of such operation your code should swap the reference so that it points to a new object
如果您需要每小时进行一次,那么这将是一项艰巨的任务,我强烈建议您不要这样做同步此服务将非常棘手客户与您的Spring Application。
If you need to have it being done exactly every hour then it will be a difficult task and I would strongly advise against it since it would be very tricky to synchronize this service client with your Spring Application.
这篇关于定期刷新Spring bean实例属性的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!