EventBus
EventBus copied to clipboard
Subscription cause Spring cache annotation not working correctly
I am trying to put the content of a property file into the Spring cache, and when the file is changed, the content will be reloaded. In order to decouple the components, event bus is used here, like below:
@Subscribe
//@CacheEvict(value = Constants.CACHE_NAME, cacheManager = Constants.CACHE_MANAGER_NAME, allEntries = true)
public void onSecretChangesEvent(final SecretChangesEvent event) throws IOException {
cacheManager.getCache(Constants.CACHE_NAME).clear(); // @CacheEvict is not working, maybe caused by eventbus subscription
}
@Cacheable(value = Constants.CACHE_NAME, cacheManager = Constants.CACHE_MANAGER_NAME)
public Properties getSecrets() throws IOException {
final Properties properties = new Properties();
final BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
properties.load(bufferedReader);
return properties;
}
The problem is the @CacheEvict annotatoin is not working at all, I have to clear the cache through the cache manager. I guess this is caused by the subscription mechanism.
Sorry, I'm not familiar with Spring cache. Possibly try to ask this on Stack Overflow? -Uwe
I encountered the same problem,possible reason is EventBus and Spring‘s annotation processor work alone,the method EventBus call is not the method in your class(i am not sure). If you want use EventBus to notify evict all cache you need add a middle class tocall method with @CacheEvict
.The below code work well.
@CacheConfig(cacheNames={"names"})
@Component
public class CacheService {
@Cacheable
public String getName() throws Exception {
TimeUnit.SECONDS.sleep(2);
System.out.println("begin to get name");
return "hello world";
}
@CacheEvict
public void evictAll() {
System.out.println("begin to evict all");
}
// The below code not works
// @Subscribe
// public void callback(TestEvent event) {
// System.out.println("get event");
// evictAll();
// }
}
middle class response for call a method with @CacheEvict
@Component
public class SubscriberService {
@Autowired
private CacheService cacheService;
@Subscribe
public void callback(TestEvent event) {
System.out.println("get event");
cacheService.evictAll();
}
}