Redis常用操作

138 阅读4分钟
  • 1.缓存基本的对象,Integer、String、实体类等,并设置过期时间
  • 2.缓存基本的对象,Integer、String、实体类等
  • 3.缓存基本的对象,Integer、String、实体类等,并根据时间颗粒度设置过期时间
  • 4.key自增
  • 5.key增加指定值
  • 6.key减少指定值
  • 7.key设置有效时间
  • 8.key根据时间单位设置有效时间
  • 9.查询key的有效时间
  • 10.获得缓存key的基本对象
  • 11.删除单个key对象
  • 12.删除集合对象
  • 13.HyperLogLog 去重 插入
  • 14.HyperLogLog 去重 获取个数
  • 15.HyperLogLog 多个集合的合并
  • 16.缓存List数据
  • 17.获得缓存的list对象
  • 18.缓存Set
  • 19.获得缓存的set
  • 20.缓存Map
  • 21.获得缓存的Map
  • 22.往Hash中存入数据
  • 23.删除Hash中的数据
  • 24.获取Hash中的数据
  • 25.获取多个Hash中的数据
  • 26.获得缓存的基本对象列表
  • 27.判断key是否存在
  • 28.判断key是否存在,存在就直接更新
  • 29.key加锁
  • 30.key自增,并将1,转换为000001的类型
package com.api.redis;

import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * spring redis 工具类
 * @author ruoyi
 **/
@SuppressWarnings(value = {"unchecked", "rawtypes"})
@Component
public class RedisCache {
    @Autowired
    public RedisTemplate redisTemplate;

    private static final Logger log = org.apache.logging.log4j.LogManager.getLogger(RedisCache.class);

    /**
     * 缓存基本的对象,Integer、String、实体类等,并设置过期时间
     * @param key     缓存的键值
     * @param value   缓存的值
     * @param timeout 时间
     * @return true=设置成功;false=设置失败
     */
    public boolean setIfAbsent(final String key, final Object value, final Duration timeout) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, timeout);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等
     * @param key   缓存的键值
     * @param value 缓存的值
     */
    public <T> void setCacheObject(final String key, final T value) {
        redisTemplate.opsForValue().set(key, value);
    }

    /**
     * 缓存基本的对象,Integer、String、实体类等,并根据时间颗粒度设置过期时间
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间颗粒度
     */
    public <T> void setCacheObject(final String key, final T value, final Integer timeout, final TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * key自增
     * @param key Redis键
     */
    public Long increment(final String key) {
        return redisTemplate.opsForValue().increment(key);
    }

    /**
     * key增加指定值
     * @param key   Redis键
     * @param delta 增加值
     */
    public Long increment(final String key, long delta) {
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * key减少指定值
     * @param key   Redis键
     * @param delta 减少值
     */
    public Long decrement(final String key, long delta) {
        return redisTemplate.opsForValue().decrement(key, delta);
    }

    /**
     * key设置有效时间
     * @param key     Redis键
     * @param timeout 超时时间
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout) {
        return expire(key, timeout, TimeUnit.SECONDS);
    }
    
    /**
     * key根据时间单位设置有效时间
     * @param key     Redis键
     * @param timeout 超时时间
     * @param unit    时间单位
     * @return true=设置成功;false=设置失败
     */
    public boolean expire(final String key, final long timeout, final TimeUnit unit) {
        return redisTemplate.expire(key, timeout, unit);
    }

    /**
     * 查询key的有效时间
     */
    public Long getExpire(final String key) {
        return redisTemplate.getExpire(key);
    }

    /**
     * 获得缓存key的基本对象
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T getCacheObject(final String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }

    /**
     * 删除单个key对象
     * @param key
     */
    public boolean deleteObject(final String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 删除集合对象
     * @param collection 多个对象
     * @return
     */
    public long deleteObject(final Collection collection) {
        return redisTemplate.delete(collection);
    }

    /****
     * HyperLogLog 去重  插入
     * **/
    public void addHyperLog(String key, String value) {
        redisTemplate.opsForHyperLogLog().add(key, value);
    }

    /****
     * HyperLogLog 去重  获取个数
     * **/
    public Long hyperLogSize(String key) {
        return redisTemplate.opsForHyperLogLog().size(key);
    }

    /****
     * HyperLogLog 多个集合的合并
     * **/
    public void union(String key, String[] sourceKeys) {
        redisTemplate.opsForHyperLogLog().union(key, sourceKeys);
    }

    /**
     * 缓存List数据
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> Long setCacheList(final String key, final List<T> dataList) {
        Long count = redisTemplate.opsForList().rightPushAll(key, dataList);
        return count == null ? 0 : count;
    }

    /**
     * 获得缓存的list对象
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(final String key) {
        return redisTemplate.opsForList().range(key, 0, -1);
    }

    /**
     * 缓存Set
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(final String key, final Set<T> dataSet) {
        BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
        Iterator<T> it = dataSet.iterator();
        while (it.hasNext()) {
            setOperation.add(it.next());
        }
        return setOperation;
    }

    /**
     * 获得缓存的set
     * @param key
     * @return
     */
    public <T> Set<T> getCacheSet(final String key) {
        return redisTemplate.opsForSet().members(key);
    }

    /**
     * 缓存Map
     * @param key
     * @param dataMap
     */
    public <T> void setCacheMap(final String key, final Map<String, T> dataMap) {
        if (dataMap != null) {
            redisTemplate.opsForHash().putAll(key, dataMap);
        }
    }

    /**
     * 获得缓存的Map
     * @param key
     * @return
     */
    public <T> Map<String, T> getCacheMap(final String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * 往Hash中存入数据
     * @param key   Redis键
     * @param hKey  Hash键
     * @param value 值
     */
    public <T> void setCacheMapValue(final String key, final String hKey, final T value) {
        redisTemplate.opsForHash().put(key, hKey, value);
    }

    /**
     * 删除Hash中的数据
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return
     */
    public Long deleteCacheMapValue(final String key, final Object... hKeys) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.delete(key, hKeys);
    }

    /**
     * 获取Hash中的数据
     * @param key  Redis键
     * @param hKey Hash键
     * @return Hash中的对象
     */
    public <T> T getCacheMapValue(final String key, final String hKey) {
        HashOperations<String, String, T> opsForHash = redisTemplate.opsForHash();
        return opsForHash.get(key, hKey);
    }

    /**
     * 获取多个Hash中的数据
     * @param key   Redis键
     * @param hKeys Hash键集合
     * @return Hash对象集合
     */
    public <T> List<T> getMultiCacheMapValue(final String key, final Collection<Object> hKeys) {
        return redisTemplate.opsForHash().multiGet(key, hKeys);
    }

    /**
     * 获得缓存的基本对象列表
     * @param pattern 字符串前缀
     * @return 对象列表
     */
    public Collection<String> keys(final String pattern) {
        return redisTemplate.keys(pattern);
    }

    /**
     * 判断key是否存在
     * @param key key
     * @return true:存在、false:不存在
     */
    public Boolean hasKey(final String key) {
        return redisTemplate.hasKey(key);
    }
    
    /**
     * 判断key是否存在,存在就直接更新
     * @param key Redis键
     * @param num 增几
     * @return 更新后的值
     */
    public long addStock(String key, int num) {
        boolean hasKey = redisTemplate.hasKey(key);
        // 判断key是否存在,存在就直接更新
        if (hasKey) {
            return redisTemplate.opsForValue().increment(key, num);
        }
        try {
            hasKey = redisTemplate.hasKey(key);
            if (!hasKey) {
                redisTemplate.opsForValue().set(key, num);
            }
        } catch (Exception e) {
        }
        return getStock(key);
    }

    public int getStock(String key) {
        Integer stock = (Integer) redisTemplate.opsForValue().get(key);
        return stock == null ? 0 : stock;
    }

    /**
     * key加锁
     */
    public boolean execueTask(String lock, String key) {
        boolean loc = false;
        try {
            loc = setIfAbsent(key, lock, Duration.ofSeconds(20));
        } catch (Exception e) {
        }
        return loc;
    }

    /**
     * key自增,并将1,转换为000001的类型
     * count 代表补充多少个0
     * @param key Redis键
     */
    public String incrementBeforeSupplyZero(final String key, Integer count) {
        if (count == null || count == 0) {
            String.valueOf(redisTemplate.opsForValue().increment(key));
        }
        String supplyZero = "%0" + count + "d";
        return String.format(supplyZero, redisTemplate.opsForValue().increment(key));
    }

}