简体   繁体   中英

Spring Boot EhCache: Storing a List of objects without a key

I am using the @PostConstruct annotation on application start to query the entire list result from the DB and am storing it as a static global variable. I am parsing this result list and getting the responses I need. As shown below:

private static List<Object[]> allObjects;

@PostConstruct
     public void test() {
        System.out.println("Calling Method");
        Query q = entityManager.createNativeQuery(query);
        List<Object[]> resultList = (List<Object[]>) q.getResultList();
        allObjects = resultList;
}

However, I would like to use ehcache to store the result list so I can refresh the cache at any time or remove the items from the cache. Is it possible to store a result list (without a key) in the cache instead of storing it as a global variable?

If you are working with spring boot than using spring cache abstraction is the most natural and recommended way for any caching needs (including with EhCache). It'll also solve the problem that you are trying to solve. Please setup the EhCacheManager as outlined in Spring Boot Ehcache Example article. Post this setup, separate the dbloading routine in a new bean and make it cache enabled. To pre-load the cache on startup, you can invoke this bean's method in any other bean's postconstruct. Following outline will give you fully working solution.

@Component
public class DbListProvider {

    @Cacheable("myDbList")
    public List<Object[]> getDbList() {
        System.out.println("Calling Method");
        Query q = entityManager.createNativeQuery(query);
        List<Object[]> resultList = (List<Object[]>) q.getResultList();
        return resultList;
    }
}

// In your existing post construct method, just call this method to pre-load 
// these objects on startup Please note that you CAN NOT add this PostConstruct 
// method to DbListProvider as it will not trigger spring boot cache 
// abstraction responsible for managing and populating the cache
public class Myinitializer {
    @Autowired
    private DbListProvider listProvider;
    
    @PostConstruct
    private void init() {
        // load on startup 
        listProvider.getDbList();
    }
}

You can further inject DbListProvider bean anywhere in code base which gives you additional flexibility (should you need that).

You can use @CachePut, @CacheEvict as per your eviction policies without having to worry about EhCache behind the scene. I'll further recommend to understand all options available from spring cache and use them appropriately for your future needs. Following should help -

  1. A Guide To Caching in Spring
  2. Spring Cache Abstraction

Hope this helps!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM