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

cn.cliveyuan.tools.redis.RedisCache Maven / Gradle / Ivy

The newest version!
package cn.cliveyuan.tools.redis;

import lombok.Data;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.Callable;

/**
 * Redis 缓存
 *
 * @author Clive Yuan
 * @date 2021/09/14
 */
@Data
public class RedisCache implements Cache {

    private String name;
    private RedisCacheConfig cacheConfig;
    private final RedisService redisService;

    public RedisCache(RedisCacheConfig cacheConfig, RedisService redisService) {
        Objects.requireNonNull(cacheConfig);
        Objects.requireNonNull(cacheConfig.getName());
        this.name = cacheConfig.getName();
        this.cacheConfig = cacheConfig;
        this.redisService = redisService;
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public Object getNativeCache() {
        return this;
    }

    @Override
    public ValueWrapper get(Object key) {
        return Optional.ofNullable(this.getValue(key)).map(SimpleValueWrapper::new).orElse(null);
    }

    @Override
    public  T get(Object key, Class type) {
        return (T) this.getValue(key);
    }

    @Override
    public  T get(Object key, Callable valueLoader) {
        return (T) this.getValue(key);
    }

    @Override
    public void put(Object key, Object value) {
        if (Objects.nonNull(value)) {
            if (Objects.nonNull(cacheConfig.getExpireAfterWrite()) && cacheConfig.getExpireAfterWrite().getSeconds() != 0) {
                redisService.set(this.getPrefix() + key.toString(), value, cacheConfig.getExpireAfterWrite().getSeconds());
            } else {
                redisService.set(this.getPrefix() + key.toString(), value);
            }
        }
    }

    @Override
    public void evict(Object key) {
        redisService.del(this.getPrefix() + key.toString());
    }

    @Override
    public void clear() {
        List keys = keys();
        if (!keys.isEmpty()) {
            redisService.del(keys.toArray(new String[0]));
        }
    }

    public List keys() {
        return new ArrayList<>(redisService.keys(this.getPrefix() + "*"));
    }

    private Object getValue(Object key) {
        if (Objects.isNull(key)) {
            return null;
        }
        return redisService.get(this.getPrefix() + key.toString());
    }

    private String getPrefix() {
        return name + "_";
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy