问题
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
回答1:
I think that it would be best (and easiest) for you to implement it as a sort of a proxy.
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:
- 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
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.
来源:https://stackoverflow.com/questions/42119144/refresh-spring-bean-instance-property-periodically-best-practice