0
votes

I want to fetch the count from DB for the first time and then update the count in the local cache. For any further request, I need to update the in memory counter variable for each request and use the updated count.

I have used Ehcache for and below is my code to fetch from the DB:

@Override
@CachePut(cacheNames="countCache", key="#id")
public int getCountFromDB(int id, int length) {

    String sqlstm = "select count(*) from Table where length=:length";
    Map<String, Object> namedParamsMap = new HashMap<String, Object>();
    namedParamsMap.put("idd", idd);
    namedParamsMap.put("length", length);
    Integer li = namedParamJdbcTemplate.queryForObject(sqlstm, namedParamsMap, Integer.class);
    return li;
}

2. I need to update this cachename with the counter value. I tried using the below method:

   @CachePut(value = "countCache", key = "#id")
    public long updateCounterCache(int id, long count)
    {
        logger.error("In side ht thew updateCounterCache method "+count);
        return count;
    }

If I call updateCounterCache with new count, the counter is not getting updated in the cache. Where am I going wrong.

1

1 Answers

2
votes

I'm not sure I would use a cache for that. I would probably just set the initial value to an AtomicLong. The reason is that you do not seem to save the value back to the database and a cache never guarantees the value won't be evicted at some point (but actually, Ehcache won't do that unless the cache is full).

So it all depends how the value is important for you.

That said, your problem is that getCountFromDB should use @Cacheable not @CachePut. See below

@Cacheable(cacheNames="countCache", key="#id")
public int getCountFromDB(int id, int length) {
    String sqlstm = "select count(*) from Table where length=:length";
    Map<String, Object> namedParamsMap = new HashMap<>(2);
    namedParamsMap.put("idd", id);
    namedParamsMap.put("length", length);
    Integer li = namedParamJdbcTemplate.queryForObject(sqlstm, namedParamsMap, Integer.class);
    return li;
}