meursault
meursault

Reputation: 295

Spring Scheduled Cache

I have a method which returns list in my spring-boot project. This list is created with DTO mapping and i don't want my code execute sql query in every refresh of page. Sometimes new updates can come to the database. So for example I want it to refresh cache every 5 hours. Cacheable is running but not receiving new data. I looked at the Cache Evict examples, but my code doesn't make any cache when I apply it. And one more thing, is it possible to cache more than one list in same method? For example like in the code below but it does not work:

@Override
@Cacheable(value = "apps")
@Scheduled(cron = "0 0/30 * * * ?")
@CacheEvict(value = "apps",  allEntries=true)
public List<Apps> executeLatestApplications(){
...
List<Apps> apps = em.createNamedQuery("Apps", Apps.class).getResultList();
...
}

This is where apps SQL Result Mapping:

@NamedNativeQuery(
        name = "AppsQuery",
        query = "SELECT id, name, address, repo, version FROM apps",
        resultSetMapping = "Mapping"
)

@SqlResultSetMapping(
        name = "Mapping",
        classes = @ConstructorResult(targetClass= com.meursault.apps.model.Apps.class,
                columns = {
                        @ColumnResult(name = "id", type = Long.class),
                        @ColumnResult(name = "name", type = String.class),
                        @ColumnResult(name = "address", type = String.class),
                        @ColumnResult(name = "repo", type = String.class),
                        @ColumnResult(name = "version", type = String.class))

Upvotes: 1

Views: 4651

Answers (2)

Thirumal
Thirumal

Reputation: 9536

I guess the problem is you are using @Cacheable(value = "apps") and @CacheEvict(value = "apps", allEntries=true) in the same method.

Use @CachePut to update all the entries.

@Override
@CachePut(value = "apps")
@Scheduled(cron = "0 0/30 * * * ?")
public List<Apps> executeLatestApplications(){
    ...
    List<Apps> apps = em.createNamedQuery("Apps", Apps.class).getResultList();
    ...
}

Upvotes: 1

Pankaj
Pankaj

Reputation: 2678

I'm not sure what you mean by 'Cacheable is running but not receiving new data. I looked at the Cache Evict examples, but my code doesn't make any cache when I apply it.

'@Cacheable works by caching return type against method argument, think of this as simple key/value store with key as method argument and value as the returned value.

You can have a separate @CacheEvict method which evicts allentries.

@CacheEvict(allEntries = true) 
public void save(App app) {
     em.insert(app);
}

Check this post

You can check more information in spring documentation.

Upvotes: 1

Related Questions