RedisCacheUtil.java 8.82 KB
package com.glsx.common.utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;
import org.springframework.data.redis.connection.ReturnType;

/**
 * redis缓存帮助类
 * Created by liumh on 2018/8/13
 */
@Component
public class RedisCacheUtil<T> {

    @Autowired
    public RedisTemplate redisTemplate;

    private static final Long SUCCESS = 1L;
    private static final String RELEASE_LOCK_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";

    
    /**
     * 缓存基本的对象,Integer、String、实体类等
     *
     * @param key   缓存的键值
     * @param value 缓存的值
     * @return 缓存的对象
     */
    public <T> ValueOperations<String, T> setCacheObject(String key, T value, long timeout, TimeUnit unit) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        operation.set(key, value, timeout, unit);
        return operation;
    }

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

    /**
     * 缓存List数据
     *
     * @param key      缓存的键值
     * @param dataList 待缓存的List数据
     * @return 缓存的对象
     */
    public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList) {
        ListOperations listOperation = redisTemplate.opsForList();
        if (null != dataList) {
            int size = dataList.size();
            for (int i = 0; i < size; i++) {
                listOperation.leftPush(key, dataList.get(i));
            }
        }
        return listOperation;
    }

    /**
     * 获得缓存的list对象
     *
     * @param key 缓存的键值
     * @return 缓存键值对应的数据
     */
    public <T> List<T> getCacheList(String key) {
        List<T> dataList = new ArrayList<T>();
        ListOperations<String, T> listOperation = redisTemplate.opsForList();
        Long size = listOperation.size(key);

        for (int i = 0; i < size; i++) {
            dataList.add(listOperation.index(key, i));
        }
        return dataList;
    }

    /**
     * 缓存Set
     *
     * @param key     缓存键值
     * @param dataSet 缓存的数据
     * @return 缓存数据的对象
     */
    public <T> BoundSetOperations<String, T> setCacheSet(String key, 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 Set<T> getCacheSet(String key) {
        Set<T> dataSet = new HashSet<T>();
        BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
        Long size = operation.size();
        for (int i = 0; i < size; i++) {
            dataSet.add(operation.pop());
        }
        return dataSet;
    }

    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     * @return
     */
    public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap) {

        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {
            for (Map.Entry<String, T> entry : dataMap.entrySet()) {
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }
        }
        return hashOperations;
    }

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


    /**
     * 缓存Map
     *
     * @param key
     * @param dataMap
     * @return
     */
    public <T> HashOperations<String, Integer, T> setCacheIntegerMap(String key, Map<Integer, T> dataMap) {
        HashOperations hashOperations = redisTemplate.opsForHash();
        if (null != dataMap) {
            for (Map.Entry<Integer, T> entry : dataMap.entrySet()) {
                hashOperations.put(key, entry.getKey(), entry.getValue());
            }
        }
        return hashOperations;
    }

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

    public void delete(String key) {
        redisTemplate.delete(key);
    }

    public void deleteByPrex(String prex) {
        Set<String> keys = redisTemplate.keys(prex + "*");
        redisTemplate.delete(keys);
    }

    public void deleteBySuffix(String suffix) {
        Set<String> keys = redisTemplate.keys("*" + suffix);
        redisTemplate.delete(keys);
    }

    public void deleteByKeys(String... keys) {
        redisTemplate.delete(Arrays.asList(keys));
    }

    public List getListByPrex(String prex) {
        Set<String> keys = redisTemplate.keys(prex + "*");
        return redisTemplate.opsForValue().multiGet(keys);
    }
    
	/**
	 * 获取锁
	 * 
	 * @param lockKey
	 * @param value
	 * @param expireTime
	 *            :单位-秒
	 * @return
	 */
	/*public boolean getLock(String lockKey, String value, int expireTime) {
		boolean ret = false;
		try {
			String script = "if redis.call('setNx',KEYS[1],ARGV[1]) then if redis.call('get',KEYS[1])==ARGV[1] then return redis.call('expire',KEYS[1],ARGV[2]) else return 0 end end";
			RedisScript<String> redisScript = new DefaultRedisScript<>(script,
					String.class);
			Object result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), value, expireTime);
			if (SUCCESS.equals(result)) {
				return true;
			}
		} catch (Exception e) {
		}
		return ret;
	}*/

	/**
	 * 释放锁
	 * 
	 * @param lockKey
	 * @param value
	 * @return
	 */
	/*public boolean releaseLock(String lockKey, String value) {
		String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
		RedisScript<String> redisScript = new DefaultRedisScript<>(script,
				String.class);
		Object result = redisTemplate.execute(redisScript,
				Collections.singletonList(lockKey), value);
		if (SUCCESS.equals(result)) {
			return true;
		}
		return false;
	}*/
    
    /**
     * 
     * @author zhanghj 
     * @Title: lock  
     * @Description: TODO  获取锁
     * @param key
     * @param requestId
     * @param expire
     * @return
     * boolean
     *
     */
	public synchronized boolean lock(String key, String requestId, long expire) {
		return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
			Boolean result = connection.set(key.getBytes(),
					requestId.getBytes(),
					Expiration.from(expire, TimeUnit.SECONDS),
					RedisStringCommands.SetOption.SET_IF_ABSENT);
			return result;
		});
	}
  
	/**
	 * 
	 * @author zhanghj 
	 * @Title: releaseLock  
	 * @Description: TODO 释放锁
	 * @param key
	 * @param requestId
	 * @return
	 * boolean
	 *
	 */
	public synchronized boolean releaseLock(String key, String requestId) {
		return (Boolean) redisTemplate
				.execute((RedisCallback) connection -> {
					String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
					Boolean result = connection.eval(script.getBytes(),
							org.springframework.data.redis.connection.ReturnType.BOOLEAN, 1, key.getBytes(),
							requestId.getBytes());
					return result;
				});
	}
	 
}