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

com.feingto.cloud.cache.provider.RedisProvider Maven / Gradle / Ivy

There is a newer version: 2.5.2.RELEASE
Show newest version
package com.feingto.cloud.cache.provider;

import com.feingto.cloud.cache.ICache;
import com.feingto.cloud.cache.RedisManager;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * Redis 缓存值操作
 *
 * @author longfei
 */
@SuppressWarnings("unchecked")
public class RedisProvider implements ICache {
    private static RedisManager redisManager;

    public RedisProvider(RedisTemplate template) {
        redisManager = new RedisManager().setTemplate(template);
    }

    @Override
    public Map get() {
        return keys().stream().collect(Collectors.toMap(k -> k, v -> v));
    }

    @Override
    public  T get(String key) {
        return (T) redisManager.getValueStore().get(key);
    }

    @Override
    public void put(String key, Object value) {
        redisManager.getValueStore().set(key, value);
    }

    @Override
    public void put(String key, Object value, long expireTime) {
        this.put(key, value, expireTime, TimeUnit.MILLISECONDS);
    }

    @Override
    public void put(String key, Object value, long expireTime, TimeUnit timeUnit) {
        redisManager.getValueStore().set(key, value, expireTime, timeUnit);
    }

    @Override
    public boolean has(String key) {
        return Objects.nonNull(redisManager.getValueStore().get(key));
    }

    @Override
    public void remove(String key) {
        redisManager.getTemplate().delete(key);
    }

    @Override
    public void removeByPrefix(String prefix) {
        Optional.ofNullable(redisManager.getTemplate().keys(prefix + "*"))
                .ifPresent(keys -> keys.stream()
                        .filter(key -> key.startsWith(prefix))
                        .forEach(this::remove));
    }

    @Override
    public void clear() {
        redisManager.getTemplate().execute((RedisCallback) connection -> {
            connection.flushDb();
            return "ok";
        });
    }

    @Override
    public Set keys() {
        return redisManager.getTemplate().keys("*");
    }
}