All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.iqiny.silly.starter.cache.SillyCaffeineCache Maven / Gradle / Ivy

The newest version!
/*
 *  Copyright  iqiny.com
 *
 *  https://gitee.com/iqiny/silly
 *
 *  project name:silly-spring-boot-starter
 *  project description:top silly project pom.xml file
 */
package com.iqiny.silly.starter.cache;

import com.github.benmanes.caffeine.cache.Caffeine;
import com.iqiny.silly.core.base.SillyInitializable;
import com.iqiny.silly.core.cache.SillyCache;
import org.springframework.cache.Cache;
import org.springframework.cache.caffeine.CaffeineCacheManager;

import java.util.Collection;
import java.util.concurrent.TimeUnit;

/**
 * 默认集成Caffeine本地缓存工具
 */
public class SillyCaffeineCache implements SillyCache, SillyInitializable {

    private CaffeineCacheManager cacheManager;

    @Override
    public void init() {
        cacheManager = new CaffeineCacheManager();
        int initialCapacity = 1024;
        long maximumSize = 1024;
        long expireAfterWrite = 4;

        Caffeine cacheBuilder = Caffeine.newBuilder()
                //设置写缓存过期
                .expireAfterWrite(expireAfterWrite, TimeUnit.HOURS)
                //设置缓存容量的初始容量
                .initialCapacity(initialCapacity)
                //设置缓存最大容量 ,超过之后会按照LRU最近最少使用算法来移除缓存项
                .maximumSize(maximumSize)
                //设置要统计缓存的命中率
                .recordStats();
        cacheManager.setCaffeine(cacheBuilder);
    }

    protected Cache getSillyCache(String category) {
        return cacheManager.getCache(category);
    }

    @Override
    public void clearAll() {
        Collection cacheNames = cacheManager.getCacheNames();
        cacheNames.forEach(this::clearAll);
    }

    @Override
    public void clearAll(String category) {
        Cache sillyCache = getSillyCache(category);
        sillyCache.clear();
    }

    @Override
    public  T getValue(String category, Object key) {
        if (category == null || key == null) {
            return null;
        }
        Cache sillyCache = getSillyCache(category);
        Cache.ValueWrapper wrapper = sillyCache.get(key);
        return wrapper == null ? null : (T) wrapper.get();
    }

    @Override
    public void setValue(String category, Object key, Object value) {
        if (category == null || key == null) {
            return;
        }

        Cache sillyCache = getSillyCache(category);
        sillyCache.put(key, value);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy