欢迎访问悦橙教程(wld5.com),关注java教程。悦橙教程  java问答|  每日更新
页面导航 : > > 文章正文

Caffeine 缓存 动态的为每个值设置过期时间,

来源: javaer 分享于  点击 37811 次 点评:27

Caffeine 缓存 动态的为每个值设置过期时间,


引入jar

 <!--本地缓存caffeine-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-cache</artifactId>
        </dependency>
        <dependency>
            <groupId>com.github.ben-manes.caffeine</groupId>
            <artifactId>caffeine</artifactId>
            <version>2.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.checkerframework</groupId>
            <artifactId>checker-qual</artifactId>
            <version>3.5.0</version>
        </dependency>
        <dependency>
            <groupId>org.checkerframework</groupId>
            <artifactId>checker-compat-qual</artifactId>
            <version>2.5.5</version>
        </dependency>

实现方法

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.github.benmanes.caffeine.cache.Expiry;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.checkerframework.checker.index.qual.NonNegative;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Caffeine本地内存缓存操作
 */
@Component
public class CaffeineEntryCacheUtil {
    private Cache<String, CaffeineEntry> cache;

    /**
     * 初始化,创建可自定义控制过期时间的cache
     * l1是当前键剩余的时间
     *
//     * @param maximumSize
     */
    private CaffeineEntryCacheUtil() {
        Cache<String, CaffeineEntry> build = Caffeine.newBuilder()
                .maximumSize(100)
                .expireAfter(new Expiry<String, CaffeineEntry>() {
                    @Override
                    public long expireAfterCreate(@NonNull String s, @NonNull CaffeineEntry caffeineEntry, long l) {
                        return caffeineEntry.getExpireTime();
                    }

                    @Override
                    public long expireAfterUpdate(@NonNull String s, @NonNull CaffeineEntry caffeineEntry, long l, @NonNegative long l1) {
                        return caffeineEntry.getExpireTime();
                    }

                    @Override
                    public long expireAfterRead(@NonNull String s, @NonNull CaffeineEntry caffeineEntry, long l, @NonNegative long l1) {
                        if (caffeineEntry.isAccessFresh()) {
                            return caffeineEntry.getExpireTime();
                        }
                        return l1;
                    }
                }).build();
        this.cache = build;
    }

    /**
     * 加入缓存,默认过期时间24小时且读后不刷新
     *
     * @param key
     * @param value
     */
    public void putIntoCache(String key, Object value) {
        putIntoCache(key, value, 24, TimeUnit.HOURS, false);
    }

    /**
     * 加入缓存,可指定过期时间,默认不刷新 默认是分钟
     *
     * @param key
     * @param value
     * @param duration
     */
    public void putIntoCache(String key, Object value, long duration) {
        putIntoCache(key, value, duration, TimeUnit.MINUTES, false);
    }

    /**
     * 加入缓存,可指定过期时间、读后是否刷新
     *
     * @param key
     * @param value
     * @param duration
     * @param timeUnit
     * @param accessFresh
     */
    public void putIntoCache(String key, Object value, long duration, TimeUnit timeUnit, boolean accessFresh) {
        CaffeineEntry caffeineEntry = new CaffeineEntry();
        caffeineEntry.setKey(key);
        caffeineEntry.setValue(value);
        caffeineEntry.setExpireTime(timeUnit.toNanos(duration));
        caffeineEntry.setAccessFresh(accessFresh);
        cache.put(key, caffeineEntry);
    }

    /**
     * 获取缓存对象
     *
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getCacheObject(String key, Class<T> clazz) {
        final Object result = getCacheObject(key);
        return Objects.nonNull(result) ? clazz.cast(result) : null;
    }

    /**
     * 获取缓存集合
     *
     * @param key
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> List<T> getCacheObjectList(String key, Class<T> clazz) {
        final Object result = getCacheObject(key);
        if (Objects.nonNull(result)) {
            Collection<?> collection = (Collection<?>) result;
            List<T> list = new ArrayList<>();
            collection.forEach(item -> list.add(clazz.cast(item)));
            return list;
        }
        return null;
    }

    /**
     * 获取基本缓存对象
     *
     * @param key
     * @return
     */
    public Object getCacheObject(String key) {
        final Object[] value = {null};
        Optional.ofNullable(cache.getIfPresent(key))
                .ifPresent(item -> {
                    value[0] = item.getValue();
                });
        return value[0];
    }

    /**
     * 删除单个缓存
     * @param key
     */
    public void deleteCacheObject(String key) {
        cache.invalidate(key); // 手动删除指定键的缓存项
    }

    /**
     * 删除所有缓存
     */
    public void deleteCacheObject() {
        cache.invalidateAll();
    }


    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class CaffeineEntry {
        private String key;
        private Object value;
        private long expireTime;
        private boolean accessFresh;
    }
}

调用访问

   @Resource
    private CaffeineEntryCacheUtil caffeineEntryCacheUtil;

 public static void main(String[] args) {
         List<Class> cacheList = caffeineEntryCacheUtil.getCacheObject("name",List.class);
        if (cacheList != null && cacheList.size() != 0) {
            list=cacheList;
        } else {
            //实现查询数据
             list = null;
            //保存缓存
            caffeineEntryCacheUtil.putIntoCache("name",list);
        }
    }

 

相关栏目:

用户点评