天天看點

java工具類分享(Redis工具類)

import com.sun.istack.internal.NotNull;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.util.CollectionUtils;
 
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
 
import static com.google.common.base.Preconditions.checkNotNull;
 
/**
 * redis工具模闆類
 *
 **/
public class RedisUtil {
 
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
 
    /**
     * 指定緩存失效時間
     *
     * @param key  鍵
     * @param time 時間(秒)
     * @return 傳回設定成功結果
     */
    public boolean cacheExpireTime(String key, long time) {
        try {
            if (time > 0) {
                return checkNotNull(redisTemplate.expire(key, time, TimeUnit.SECONDS));
            }
            return false;
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 開始事務
     *
     */
    public void startTransaction() {
        redisTemplate.multi();
    }
 
    /**
     * 結束事務
     *
     */
    public List<Object> endTransaction() {
        return redisTemplate.exec();
    }
 
    /**
     * 根據key 擷取過期時間
     *
     * @param key 鍵 不能為null
     * @return 時間(秒) 傳回0代表為永久有效
     */
    public long getExpire(String key) {
        try {
            return checkNotNull(redisTemplate.getExpire(key, TimeUnit.SECONDS));
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    /**
     * 判斷key是否存在
     *
     * @param key 鍵
     * @return true 存在 false不存在
     */
    public boolean existKey(@NotNull String key) {
        try {
            return checkNotNull(redisTemplate.hasKey(key));
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 删除緩存
     *
     * @param key 可以傳一個值 或多個
     */
    public void remove(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                List list = CollectionUtils.arrayToList(key);
                redisTemplate.delete(list);
            }
        }
    }
    // ============================String=============================
 
    /**
     * 普通緩存擷取
     *
     * @param key 鍵
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
 
    /**
     * 普通緩存放入
     *
     * @param key   鍵
     * @param value 值
     * @return true成功 false失敗
     */
    public <E> boolean put(String key, E value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 普通緩存放入并設定時間
     *
     * @param key   鍵
     * @param value 值
     *              -1 或者 0 将設定無限期
     * @return true成功 false 失敗
     */
    public <E> boolean put(String key, E value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                put(key, value);
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 根據Key遞增
     *
     * @param key   鍵
     * @param delta 要增加幾(大于0)
     * @return 傳回增加後的數 -1說明不存在此關鍵字
     */
    public long increaseByKey(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞增因子必須大于0");
        }
        try {
            return checkNotNull(redisTemplate.opsForValue().increment(key, delta));
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    /**
     * 遞減
     *
     * @param key   鍵
     * @param delta 要減少幾(小于0)
     * @return 傳回減少後的數  -1說明不存在此關鍵字
     */
    public long lowerByKey(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("遞減因子必須大于0");
        }
        try {
            return checkNotNull(redisTemplate.opsForValue().increment(key, -delta));
        } catch (NullPointerException e) {
            return -1;
        }
 
    }
    // ================================Map=================================
 
    /**
     * 擷取Hash清單中的Hash
     *
     * @param key  集合key 不能為null
     * @param item 集合key中的hashkey 不能為null
     * @return 傳回對象值
     */
    public Object getHashMap(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
 
    /**
     * 擷取hashKey對應的所有鍵值
     *
     * @param key 鍵
     * @return 對應的多個鍵值
     */
    public Map<Object, Object> getAllHashMap(String key) {
        return redisTemplate.opsForHash().entries(key);
    }
 
    /**
     * 根據一個KEY 插入Map對象
     *
     * @param key 鍵
     * @param map 對應多個鍵值
     * @return true 成功 false 失敗
     */
    public boolean putMultipleHashMapByKey(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 根據一個KEY 插入Map對象 并設定時間
     *
     * @param key  鍵
     * @param map  對應多個鍵值
     * @param time 時間(秒)
     * @return true成功 false失敗
     */
    public boolean putMultipleHashMap(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                cacheExpireTime(key, time);
            } else {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 向一張hash表中放入資料,如果不存在将建立
     *
     * @param key   鍵
     * @param item  項 HashMap中的KEY
     * @param value 值 HashMap中的Value
     * @return true 成功 false失敗
     */
    public boolean putHashMap(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 向一張hash表中放入資料,如果不存在将建立
     *
     * @param key   鍵
     * @param item  項 HashMap中的KEY
     * @param value 值 HashMap中的Value
     * @param time  時間(秒) 注意:如果已存在的hash表有時間,這裡将會替換原有的時間
     * @return true 成功 false失敗
     */
    public boolean putHashMap(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                return cacheExpireTime(key, time);
            }
            return false;
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 删除hash表中的值
     *
     * @param key  鍵 不能為null
     * @param item 項 可以使多個 不能為null
     * @return 删除成功個數
     */
    public long removeMultipleHashMapByKey(@NotNull String key, Object... item) {
        return redisTemplate.opsForHash().delete(key, item);
    }
 
    /**
     * 判斷hash表中是否有該項的值
     *
     * @param key  鍵  對應的KEY
     * @param item 項  HashMap的KEY
     * @return true 存在 false不存在
     */
    public boolean existHashKey(@NotNull String key, @NotNull String item) {
        try {
            return redisTemplate.opsForHash().hasKey(key, item);
        } catch (NullPointerException e) {
            return false;
        }
 
    }
 
    /**
     * hash遞增 如果不存在,就會建立一個 并把新增後的值傳回
     *
     * @param key  鍵 對應的KEY
     * @param item 項 HashMap的KEY
     * @param by   要增加幾(大于0)
     * @return 傳回遞增結果
     */
    public double increaseHashMapByKey(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, by);
    }
 
    /**
     * hash遞減
     *
     * @param key  鍵
     * @param item 項
     * @param by   要減少記(小于0)
     * @return
     */
    public double lowerHashMapByKey(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(key, item, -by);
    }
    // ============================set=============================
 
    /**
     * 根據key擷取Set集合中的所有值
     *
     * @param key 鍵
     * @return 傳回Set集合
     */
    public <E> Set<E> getAllSetValue(String key) {
        try {
            Set set = redisTemplate.opsForSet().members(key);
            return set;
        } catch (Exception e) {
            return null;
        }
    }
 
    /**
     * 根據value從一個set中查詢,是否存在
     *
     * @param key   鍵
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean existSetValue(String key, Object value) {
        try {
            return checkNotNull(redisTemplate.opsForSet().isMember(key, value));
        } catch (Exception e) {
            return false;
        }
    }
 
    /**
     * 将資料放入set緩存
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 成功個數
     */
    public <E> long putSetCache(String key, E... values) {
        try {
            return checkNotNull(redisTemplate.opsForSet().add(key, values));
        } catch (Exception e) {
            return -1;
        }
    }
 
    /**
     * 将Set類型資料放入set緩存,帶時間參數
     *
     * @param key  鍵
     * @param time 過期時間
     * @param set  set集合
     * @return 傳回成功個數 失敗傳回-1
     */
    public <E> long putTypeSetCache(String key, long time, Set<E> set) {
        long num = 0;
        num = putTypeSetCache(key, set);
        if (time > 0) {
            cacheExpireTime(key, time);
        } else {
            return -1;
        }
        return num;
    }
 
    /**
     * 将Set類型資料放入set緩存,不帶時間參數
     *
     * @param key 鍵
     * @param set set集合
     * @return 傳回成功個數 失敗傳回-1
     */
    public <E> long putTypeSetCache(String key, Set<E> set) {
        try {
            SetOperations<String, Object> setValue = redisTemplate.opsForSet();
            return checkNotNull(setValue.add(key, set.toArray()));
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    /**
     * 将set資料放入緩存
     *
     * @param key    鍵
     * @param time   時間(秒)
     * @param values 值 可以是多個
     * @return 成功個數  -1 說明修改失敗
     */
    public long putSetCacheByTime(String key, long time, Object... values) {
        try {
            long num = checkNotNull(redisTemplate.opsForSet().add(key, values));
            if (time > 0) {
                if (cacheExpireTime(key, time)) {
                    return num;
                }
            }
            return -1;
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    /**
     * 擷取set緩存的長度
     *
     * @param key 鍵
     * @return 傳回set長度
     */
    public long getSetCacheLength(String key) {
        try {
            return checkNotNull(redisTemplate.opsForSet().size(key));
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    /**
     * 移除值為value的
     *
     * @param key    鍵
     * @param values 值 可以是多個
     * @return 移除的個數
     */
    public long removeSetValue(String key, Object... values) {
        try {
            return checkNotNull(redisTemplate.opsForSet().remove(key, values));
        } catch (NullPointerException e) {
            return -1;
        }
    }
    // ===============================list=================================
 
    /**
     * 擷取list緩存的内容
     *
     * @param key   鍵
     * @param start 開始
     * @param end   結束 0 到 -1代表所有值
     * @return 傳回list緩存
     */
    public List<Object> getListCache(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (NullPointerException e) {
            return null;
        }
    }
 
    /**
     * 擷取list緩存的長度
     *
     * @param key 鍵
     * @return 傳回List長度
     */
    public long getListCacheLength(String key) {
        try {
            return checkNotNull(redisTemplate.opsForList().size(key));
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    /**
     * 通過索引 擷取list中的值
     *
     * @param key   鍵
     * @param index 索引 index>=0時, 0 表頭,1 第二個元素,依次類推;index<0時,-1,表尾,-2倒數第二個元素,依次類推
     * @return 傳回List數組中的某個對象 null為沒找到
     */
    public Object getListbyIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (NullPointerException e) {
            return Optional.empty();
        }
    }
 
    /**
     * 将單個值放入list緩存,順序從右邊開始放
     *
     * @param key   鍵
     * @param value 值
     * @return 傳回成功結果 true 為成功 false 為失敗
     */
    public boolean putListCache(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 将單個值放入list緩存,順序從右邊開始放,并設定失效時間
     *
     * @param key   鍵
     * @param value 值 List數組
     * @param time  過期時間(秒)
     * @return 傳回成功結果 true 為成功 false 為失敗
     */
    public boolean putListCache(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                return cacheExpireTime(key, time);
            }
            return false;
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 将多個值放入list緩存
     *
     * @param key   鍵
     * @param value 值
     * @return 傳回成功結果 true 為成功 false 為失敗
     */
    public boolean putListCache(String key, List<Object> value) {
        try {
            checkNotNull(redisTemplate.opsForList().rightPushAll(key, value));
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 将多個對象放入list緩存
     *
     * @param key   鍵
     * @param value 值
     * @param time  過期時間(秒)
     * @return 傳回成功結果 true 為成功 false 為失敗
     */
    public boolean putListCache(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                return cacheExpireTime(key, time);
            }
            return false;
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 根據索引修改list中的某條資料
     *
     * @param key   鍵
     * @param index 索引
     * @param value 值
     * @return 傳回成功結果 true 為成功 false 為失敗
     */
    public boolean updateListByIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (NullPointerException e) {
            return false;
        }
    }
 
    /**
     * 移除N個值為value
     *
     * @param key   鍵
     * @param count 移除多少個
     * @param value 值
     * @return 移除的個數
     */
    public long removeListByValue(String key, long count, Object value) {
        try {
            return checkNotNull(redisTemplate.opsForList().remove(key, count, value));
        } catch (NullPointerException e) {
            return -1;
        }
    }
 
    public void setDataBase(@NotNull int index) {
        //最小索引
        int minIndex = 0;
        //最大索引
        int maxIndex = 15;
        if (index < minIndex || index > maxIndex) {
            return;
        }
        LettuceConnectionFactory lettuceConnectionFactory = (LettuceConnectionFactory) redisTemplate.getConnectionFactory();
        lettuceConnectionFactory.setDatabase(index);
        redisTemplate.setConnectionFactory(lettuceConnectionFactory);
        lettuceConnectionFactory.resetConnection();
    }
}
           
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-redis</artifactId>
            <version>1.4.1.RELEASE</version>
        </dependency>