1. 程式人生 > 其它 >一個簡單的Redis工具類 -- RedisUtils

一個簡單的Redis工具類 -- RedisUtils

基於spring、redisTemplate,對string、set、list、hash基礎資料結構簡單的操作進行封裝,提供靜態方法方便呼叫。

package cn.demo.utils;

import cn.demo.component.SpringContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.RedisKeyCommands;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @description redis工具類
 * @date 2020/08/18
 */
@Slf4j
public class RedisUtils {

    private static final RedisTemplate<String, Object> redisTemplate;

    static {
        redisTemplate = SpringContextHolder.getBean(RedisTemplate.class);
    }

    /**
     * 是否存在 key
     * @param key 鍵
     * @return java.lang.Boolean
     */
    public static Boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 刪除快取
     * @param keys 鍵集合
     * @return void
     */
    public static void del(String... keys) {
        redisTemplate.delete(Arrays.asList(keys));
    }

    /**
     * 獲取快取 TTL
     * @param key 鍵
     * @return java.lang.Long 時長(s)
     */
    public static Long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 設定快取 TTL
     * @param key  鍵
     * @param time 時長(s)
     */
    public static void expire(String key, long time) {
        try {
            redisTemplate.expire(key, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("set TTL key:{} time:{} fail ", key, time, e);
        }
    }


    /**
     * 新增快取 - string
     * @param key   鍵
     * @param value 值
     */
    public static void set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
        } catch (Exception e) {
            log.error("set STRING key:{} val:{} fail ", key, value, e);
        }
    }

    /**
     * 新增快取 - string
     * @param key   鍵
     * @param value 值
     * @param time  ttl (s)
     */
    public static void set(String key, Object value, long time) {
        try {
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("set STRING key:{} val:{} ttl:{} fail ", key, value, time, e);
        }
    }

    /**
     * 獲取快取 - string
     * @param key 鍵
     * @return java.lang.Object
     */
    public static Object get(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    /**
     * 自增 - string
     * @param key  鍵
     * @param incr 增量
     * @return java.lang.Long 自增後值
     */
    public static Long incr(String key, long incr) {
        return redisTemplate.opsForValue().increment(key, incr);
    }


    /**
     * 新增hash快取 - hash
     * @param key   鍵
     * @param item  項
     * @param value 值
     */
    public static void hSet(String key, Object item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
        } catch (Exception e) {
            log.error("set HASH key:{} item:{} val:{} fail ", key, item, value, e);
        }
    }

    /**
     * 新增hash快取 - hash
     * @param key 鍵
     * @param map 對應多個鍵
     */
    public static void hSet(String key, Map<Object, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
        } catch (Exception e) {
            log.error("set HASH key:{} map:{} fail ", key, map, e);
        }
    }

    /**
     * 獲取hash快取 - hash
     * @param key 鍵
     * @return Map<Object, Object>
     */
    public static Map<Object, Object> hGet(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 獲取hash快取 - hash
     * @param key  鍵
     * @param item 項
     * @return java.lang.Object
     */
    public static Object hGet(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 刪除hash快取某項 - hash
     * @param key   鍵
     * @param items 項
     */
    public static void hDel(String key, Object... items) {
        redisTemplate.opsForHash().delete(key, items);
    }

    /**
     * hash是否存在某項 - hash
     * @param key  鍵
     * @param item 項
     * @return java.lang.Boolean
     */
    public static Boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    /**
     * hash自增 - hash
     * @param key  鍵
     * @param item 項
     * @param incr 增量
     * @return long 自增後值
     */
    public static long hIncr(String key, String item, long incr) {
        return redisTemplate.opsForHash().increment(key, item, incr);
    }


    /**
     * 新增set快取 - set
     * @param key    鍵
     * @param values 值
     */
    public static void sSet(String key, Object... values) {
        try {
            redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            log.error("set SET key:{} set:{} fail ", key, values, e);
        }
    }

    /**
     * 獲set大小 - set
     * @param key 鍵
     * @return java.lang.Long
     */
    public static Long sSize(String key) {
        return redisTemplate.opsForSet().size(key);
    }

    /**
     * 獲取set快取 - set
     * @param key 鍵
     * @return Set<Object>
     */
    public static Set<Object> sGet(String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * set是否存在某值 - set
     * @param key   鍵
     * @param value 值
     * @return java.lang.Boolean
     */
    public static Boolean sHasKey(String key, Object value) {
        return redisTemplate.opsForSet().isMember(key, value);
    }

    /**
     * 從set中移除值 - set
     * @param key    鍵
     * @param values 值
     */
    public static void sRemove(String key, Object... values) {
        redisTemplate.opsForSet().remove(key, values);
    }


    /**
     * 新增快取 - list
     * @param key   鍵
     * @param value 值
     */
    public static void lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
        } catch (Exception e) {
            log.error("set LIST key:{} val:{} fail ", key, value, e);
        }
    }

    /**
     * 新增快取 - list
     * @param key    鍵
     * @param values 值集合
     */
    public static void lSet(String key, Object... values) {
        try {
            redisTemplate.opsForList().rightPushAll(key, Arrays.asList(values));
        } catch (Exception e) {
            log.error("set LIST key:{} list:{} fail ", key, values, e);
        }
    }

    /**
     * 獲取list快取大小 - list
     * @param key 鍵
     * @return java.lang.Long
     */
    public static Long lSize(String key) {
        return redisTemplate.opsForList().size(key);
    }

    /**
     * 獲取list快取區間 - list
     * @param key   鍵
     * @param start 起始
     * @param end   結束
     * @return List<Object>
     */
    public static List<Object> lRange(String key, long start, long end) {
        return redisTemplate.opsForList().range(key, start, end);
    }

    /**
     * list快取頭插入列
     * @param key   鍵
     * @param value 值
     */
    public static void lLeftPush(String key, Object value) {
        try {
            redisTemplate.opsForList().leftPush(key, value);
        } catch (Exception e) {
            log.error("LIST left push key:{} set:{} fail ", key, value, e);
        }
    }

    /**
     * list快取尾插入列
     * @param key   鍵
     * @param value 值
     */
    public static void lRightPush(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
        } catch (Exception e) {
            log.error("LIST right push key:{} set:{} fail ", key, value, e);
        }
    }

    /**
     * list左出列
     * @param key     鍵
     * @param isBlock 是否阻塞
     * @return java.lang.Object
     */
    public static Object lLeftPop(String key, boolean isBlock) {
        if (isBlock) {
            return redisTemplate.opsForList().leftPop(key, Integer.MAX_VALUE, TimeUnit.SECONDS);
        } else {
            return redisTemplate.opsForList().leftPop(key);
        }
    }

    /**
     * list右出列
     * @param key     鍵
     * @param isBlock 是否阻塞
     * @return java.lang.Object
     */
    public static Object lRightPop(String key, boolean isBlock) {
        if (isBlock) {
            return redisTemplate.opsForList().rightPop(key, Integer.MAX_VALUE, TimeUnit.SECONDS);
        } else {
            return redisTemplate.opsForList().rightPop(key);
        }
    }


    /**
     * 獲取所有正則匹配的key
     * @param pattern 正則
     * @return java.util.List<java.lang.String>
     */
    public static List<String> getKeys(String pattern) {
        return redisTemplate.execute(connection -> {
            RedisKeyCommands command = connection.keyCommands();
            ScanOptions scanOpts = ScanOptions.scanOptions().match(pattern).count(100).build();
            Cursor<byte[]> cursor = command.scan(scanOpts);
            Set<String> set = new HashSet<>();
            while (cursor.hasNext()) {
                byte[] bytes = cursor.next();
                set.add(new String(bytes, StandardCharsets.UTF_8));
            }
            return new ArrayList<>(set);
        }, true);
    }

}