Using guava cache to cache hot data locally

Keywords: Java Redis Google Database jvm

Some hot data may be visited thousands of times in a short time, so besides placing it in redis, it can also be placed in local memory, which is JVM's memory.

We can use google's guava cache component to implement local caching. We chose guava because it can control the size and timeout of key s and value s, configure LRU policies, and guava is thread-safe.

First introduce guava cache

<dependency>
      <groupId>com.google.guava</groupId>
      <artifactId>guava</artifactId>
      <version>18.0</version>
</dependency>

Writing CacheService Interface

public interface CacheService {
    //Storage method
    void setCommonCache(String key,Object value);
    //Take method
    Object getFromCommonCache(String key);
}

Implementation of CacheService (@PostConstruct annotation method will be automatically invoked after dependency injection is completed.)

@Service
public class CacheServiceImpl implements CacheService {

    private Cache<String,Object> commonCache=null;


    @PostConstruct
    public void init(){
        commonCache= CacheBuilder.newBuilder()
                //Cache initial capacity 10
                .initialCapacity(10)
                //Up to 100. key,Over press LRU Policy removal
                .maximumSize(100)
                //How many seconds after writing expires
                .expireAfterWrite(60, TimeUnit.SECONDS).build();
    }
    @Override
    public void setCommonCache(String key, Object value) {
        commonCache.put(key,value);
    }

    @Override
    public Object getFromCommonCache(String key) {
        return commonCache.getIfPresent(key);
    }
}

Using CacheService

@RequestMapping(value = "/get",method = {RequestMethod.GET})
    @ResponseBody
    public CommonReturnType getItem(@RequestParam(name = "id")Integer id){
        //Find in the local cache
        ItemModel itemModel= (ItemModel) cacheService.getFromCommonCache("item_"+id);

        if(itemModel==null){
            //If the local cache does not exist, it will arrive redis Lookup in Cache
            itemModel= (ItemModel) redisTemplate.opsForValue().get("item_"+id);
            if(itemModel==null){
                //If none of them is found in the database, they will be put in it. redis in
                itemModel = itemService.getItemById(id);
                redisTemplate.opsForValue().set("item_"+id,itemModel);
                redisTemplate.expire("item_"+id,10, TimeUnit.MINUTES);
            }
            //When the local cache is not available, the redis Or the database is found and then put into the local cache
            cacheService.setCommonCache("item_"+id,itemModel);
        }


        ItemVO itemVO = convertVOFromModel(itemModel);

        return CommonReturnType.create(itemVO);

    }

Posted by TropicalBeach on Wed, 02 Oct 2019 10:57:30 -0700