RedisCache.java 2.13 KB
Newer Older
张辰's avatar
张辰 committed
1 2 3
package com.tanpu.community.cache;

import com.alibaba.fastjson.JSON;
张辰's avatar
张辰 committed
4
import com.fasterxml.jackson.core.type.TypeReference;
张辰's avatar
张辰 committed
5 6
import com.tanpu.common.redis.RedisHelper;
import com.tanpu.common.redis.RedisKeyHelper;
张辰's avatar
张辰 committed
7
import com.tanpu.common.util.JsonUtil;
张辰's avatar
张辰 committed
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
import com.tanpu.community.util.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.List;
import java.util.function.Supplier;

public class RedisCache {

    private String cacheName;
    private RedisHelper redisHelper;

    public<T> T getObject(String key, Integer expireSeconds, Supplier<T> func, Class<T> clz) {
        String value = get(key);
        // todo 考虑缓存穿透的问题.
        if (StringUtils.isNotBlank(value)) {
张辰's avatar
张辰 committed
25
            return JsonUtil.toBean(value, clz);
张辰's avatar
张辰 committed
26 27 28
        }

        T ret = func.get();
张辰's avatar
张辰 committed
29 30 31
        if (ret != null) {
            put(key, ret, expireSeconds);
        }
张辰's avatar
张辰 committed
32 33 34
        return ret;
    }

张辰's avatar
张辰 committed
35
    public<T> T getList(String key, Integer expireSeconds, Supplier<T> func, TypeReference<T> ref) {
张辰's avatar
张辰 committed
36 37
        String value = get(key);
        if (StringUtils.isNotBlank(value)) {
张辰's avatar
张辰 committed
38
            return JsonUtil.toBean(value, ref);
张辰's avatar
张辰 committed
39 40
        }

张辰's avatar
张辰 committed
41 42 43 44
        T ret = func.get();
        if (ret != null) {
            put(key, ret, expireSeconds);
        }
张辰's avatar
张辰 committed
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
        return ret;
    }

    private String get(String key) {
        key = cacheName + ":" + key;
        return redisHelper.get(key);
    }

    private void put(String key, Object obj, Integer expireSeconds) {
        key = cacheName + ":" + key;
        String value = JSON.toJSONString(obj);
        if (expireSeconds == 0) {
            redisHelper.set(key, value);
        } else {
            redisHelper.set(key, value, Duration.ofSeconds(expireSeconds));
        }
    }

    public static class Builder {
        RedisCache cache = new RedisCache();

        public Builder cacheName(String cacheName) {
            cache.cacheName = cacheName;
            cache.redisHelper = SpringUtils.getBean(RedisHelper.class);
张辰's avatar
张辰 committed
69
            return this;
张辰's avatar
张辰 committed
70 71 72 73 74 75 76
        }

        public RedisCache build() {
            return cache;
        }
    }
}