Redis学習ノート(二)Redisユーティリティクラス


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.ScanParams;
import redis.clients.jedis.ScanResult;
import redis.clients.jedis.ShardedJedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class RedisUtil {
    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    /**
     *      
     * @param lock
     * @param expired
     * @return
     */
    public static boolean acquireLock(String lock,long expired) {
        boolean success = false;
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            // 1.   SETNX      lock
            long value = System.currentTimeMillis() + expired + 1;
            long acquired = shardedJedis.setnx(lock, String.valueOf(value));
            //SETNX  ,        
            if (acquired == 1)
                success = true;
                //SETNX  ,            ,         
            else {
                String tempValue = shardedJedis.get(lock);
                if (tempValue != null){
                    long oldValue = Long.valueOf(tempValue);
                    //  
                    if (oldValue < System.currentTimeMillis()) {
                        String getValue = shardedJedis.getSet(lock, String.valueOf(value));
                        //      
                        if (Long.valueOf(getValue) == oldValue)
                            success = true;
                            //            
                        else
                            success = false;
                    }
                    //   ,       
                    else
                        success = false;
                }else {
                    success = false;
                }
            }
        } catch (Exception e) {
            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();
        }
        return success;
    }

    /**
     *       
     *
     * @param key   
     * @return
     */
    public static byte[] rpop(byte[] key) {

        byte[] bytes = null;
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            bytes = shardedJedis.rpop(key);

        } catch (Exception e) {

            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();

        }
        return bytes;
    }

    /**
     *   REDIS       
     *
     * @param key   reids  
     * @param value   
     */
    public static void lpush(byte[] key, byte[] value) {

        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
//            jedis = jedisPool.getResource();
            shardedJedis.lpush(key, value);

        } catch (Exception e) {

            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();

        }
    }

    public static Long setnx(byte[] key, Object obj) {

        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            byte[] value = SerializeUtil.serialize(obj);
            return shardedJedis.setnx(key, value);

        } catch (Exception e) {
            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();
        }
        return 0L;
    }


    public static boolean setObject(byte[] key, Object obj) {
        boolean result = true;
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            byte[] value = SerializeUtil.serialize(obj);
            shardedJedis.set(key, value);

        } catch (Exception e) {
            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    /**
     *            。    : 。
     * @param key
     * @param obj
     * @param seconds
     * @return
     */
    public static boolean setObject(byte[] key, Object obj, int seconds) {
        boolean result = true;
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            byte[] value = SerializeUtil.serialize(obj);
            shardedJedis.setex(key, seconds, value);

        } catch (Exception e) {
            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();
            result = false;
        }
        return result;
    }

    public static Object getObject(byte[] key) {
        Object obj = new Object();
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            obj = SerializeUtil.unserialize(shardedJedis.get(key));
            return obj;
        } catch (Exception e) {
            //  redis  
            JedisPoolHolder.cleanup();
            e.printStackTrace();

        }
        return null;
    }

    /**
     *     key     (  : )
     *
     * @param key     key 
     * @param seconds       
     * @return 1:         0:        /        
     */
    public static long expire(String key, int seconds) {
        if (key == null || key.equals("")) {
            return 0;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
//            shardedJedisPool.getResource();
            return shardedJedis.expire(key, seconds);
        } catch (Exception ex) {
            logger.error("EXPIRE error[key=" + key + " seconds=" + seconds + "]" + ex.getMessage(), ex);
            //returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0;
    }

    /**
     *     key        
     *
     * @param key           key 
     * @param unixTimestamp unix   , 1970-01-01 00:00:00        
     * @return 1:         0:        /        
     */
    public static long expireAt(String key, int unixTimestamp) {
        if (key == null || key.equals("")) {
            return 0;
        }

        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            return shardedJedis.expireAt(key, unixTimestamp);
        } catch (Exception ex) {
            logger.error("EXPIRE error[key=" + key + " unixTimestamp=" + unixTimestamp + "]" + ex.getMessage(), ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0;
    }

    /**
     *     List
     *
     * @param key     key
     * @param start       0  
     * @param end       
     * @return    
     */
    public static String trimList(String key, long start, long end) {
        if (key == null || key.equals("")) {
            return "-";
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            return shardedJedis.ltrim(key, start, end);
        } catch (Exception ex) {
            logger.error("LTRIM   [key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return "-";
    }

    /**
     *   Set  
     *
     * @param key
     * @return
     */
    public static long countSet(String key) {
        if (key == null) {
            return 0;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.scard(key);
        } catch (Exception ex) {
            logger.error("countSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0;
    }

    /**
     *    Set (        )
     *
     * @param key     key 
     * @param seconds        s
     * @param value
     * @return
     */
  /*  public static boolean addSet(String key, int seconds, String... value) {
        boolean result = addSet(key, value);
        if (result) {
            long i = expire(key, seconds);
            return i == 1;
        }
        return false;
    }*/

    /**
     *    Set 
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean addSet(String key, String... value) {
        if (key == null || value == null) {
            return false;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();

           long result = shardedJedis.sadd(key, value);
            return true;
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error("setList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    /**
     * @param key
     * @param value
     * @return         set 
     */
    public boolean containsInSet(String key, String value) {
        if (key == null || value == null) {
            return false;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.sismember(key, value);
        } catch (Exception ex) {
            logger.error("setList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    /**
     *   Set
     *
     * @param key
     * @return
     */
    public static Set<String> getSet(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.smembers(key);
        } catch (Exception ex) {
            logger.error("getList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    /**
     *  set   value
     *
     * @param key
     * @return
     */
    public static boolean removeSetValue(String key, String... value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.srem(key, value);
            return true;
        } catch (Exception ex) {
            logger.error("getList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }


    /**
     *  list   value   count 1
     *
     * @param key
     * @param values  list
     * @return
     */
    public static int removeListValue(String key, List<String> values) {
        return removeListValue(key, 1, values);
    }

    /**
     *  list   value
     *
     * @param key
     * @param count
     * @param values  list
     * @return
     */
    public static int removeListValue(String key, long count, List<String> values) {
        int result = 0;
        if (values != null && values.size() > 0) {
            for (String value : values) {
                if (removeListValue(key, count, value)) {
                    result++;
                }
            }
        }
        return result;
    }

    /**
     *  list   value
     *
     * @param key
     * @param count      
     * @param value
     * @return
     */
    public static boolean removeListValue(String key, long count, String value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.lrem(key, count, value);
            return true;
        } catch (Exception ex) {
            logger.error("getList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    /**
     *   List
     *
     * @param key
     * @param start     
     * @param end       
     * @return
     */
    public static List<String> rangeList(String key, long start, long end) {
        if (key == null || key.equals("")) {
            return null;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.lrange(key, start, end);
        } catch (Exception ex) {
            logger.error("rangeList   [key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    /**
     *   List  
     *
     * @param key
     * @return
     */
    public static long countList(String key) {
        if (key == null) {
            return 0;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.llen(key);
        } catch (Exception ex) {
            logger.error("countList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0;
    }

    /**
     *    List (        )
     *
     * @param key     key 
     * @param seconds        s
     * @param value
     * @return
     */
    public static boolean addList(String key, int seconds, String... value) {
        boolean result = addList(key, value);
        if (result) {
            long i = expire(key, seconds);
            return i == 1;
        }
        return false;
    }

    /**
     *    List
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean addList(String key, String... value) {
        if (key == null || value == null) {
            return false;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.lpush(key, value);
            return true;
        } catch (Exception ex) {
            logger.error("setList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    /**
     *    List(   )
     *
     * @param key
     * @param list
     * @return
     */
    public static boolean addList(String key, List<String> list) {
        if (key == null || list == null || list.size() == 0) {
            return false;
        }
        for (String value : list) {
            addList(key, value);
        }
        return true;
    }

    /**
     *   List
     *
     * @param key
     * @return
     */
    public static List<String> getList(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.lrange(key, 0, -1);
        } catch (Exception ex) {
            logger.error("getList error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    /**
     *   HashSet  
     *
     * @param domain   
     * @param key      
     * @param value  Json String or String value
     * @return
     */
    public static boolean setHSet(String domain, String key, String value) {
        if (value == null) return false;
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.hset(domain, key, value);
            return true;
        } catch (Exception ex) {
            logger.error("setHSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    /**
     *   HashSet  
     *
     * @param domain   
     * @param key      
     * @return Json String or String value
     */
    public static String getHSet(String domain, String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.hget(domain, key);
        } catch (Exception ex) {
            logger.error("getHSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    /**
     *   HashSet  
     *
     * @param domain   
     * @param key      
     * @return       
     */
    public static long delHSet(String domain, String key) {
        ShardedJedis shardedJedis = null;
        long count = 0;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            count = shardedJedis.hdel(domain, key);
        } catch (Exception ex) {
            logger.error("delHSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return count;
    }

    /**
     *   HashSet  
     *
     * @param domain   
     * @param key      
     * @return       
     */
    public static long delHSet(String domain, String... key) {
        ShardedJedis shardedJedis = null;
        long count = 0;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            count = shardedJedis.hdel(domain, key);
        } catch (Exception ex) {
            logger.error("delHSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return count;
    }

    /**
     *   key    
     *
     * @param domain   
     * @param key      
     * @return
     */
    public static boolean existsHSet(String domain, String key) {
        ShardedJedis shardedJedis = null;
        boolean isExist = false;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            isExist = shardedJedis.hexists(domain, key);
        } catch (Exception ex) {
            logger.error("existsHSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return isExist;
    }

    public static boolean existsKey(String key) {
        ShardedJedis shardedJedis = null;
        boolean isExist = false;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            isExist = shardedJedis.exists(key);
        } catch (Exception ex) {
            logger.error("existsKey error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return isExist;
    }


    /**
     *     hset
     *
     * @param match field    
     * @return
     */
    public static List<Map.Entry<String, String>> scanHSet(String domain, String match) {
        ShardedJedis shardedJedis = null;
        try {
            int cursor = 0;
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            ScanParams scanParams = new ScanParams();
            scanParams.match(match);
            Jedis jedis = shardedJedis.getShard(domain);
            ScanResult<Map.Entry<String, String>> scanResult;
            List<Map.Entry<String, String>> list = new ArrayList<Map.Entry<String, String>>();
            do {
                scanResult = jedis.hscan(domain, String.valueOf(cursor), scanParams);
                list.addAll(scanResult.getResult());
                cursor = Integer.parseInt(scanResult.getStringCursor());
            } while (cursor > 0);
            return list;
        } catch (Exception ex) {
            logger.error("scanHSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }


    /**
     *    domain             value 
     *
     * @param domain
     * @return
     */

    public static List<String> hvals(String domain) {
        ShardedJedis shardedJedis = null;
        List<String> retList = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            retList = shardedJedis.hvals(domain);
        } catch (Exception ex) {
            logger.error("hvals error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return retList;
    }

    /**
     *    domain             key 
     *
     * @param domain
     * @return
     */

    public static Set<String> hkeys(String domain) {
        ShardedJedis shardedJedis = null;
        Set<String> retList = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            retList = shardedJedis.hkeys(domain);
        } catch (Exception ex) {
            logger.error("hkeys error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return retList;
    }

    /**
     *    domain      key   
     *
     * @param domain
     * @return
     */
    public static long lenHset(String domain) {
        ShardedJedis shardedJedis = null;
        long retList = 0;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            retList = shardedJedis.hlen(domain);
        } catch (Exception ex) {
            logger.error("hkeys error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return retList;
    }

    /**
     *       
     *
     * @param key
     * @param score
     * @param value
     * @return
     */
    public static boolean addSortSet(String key, long score, String value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.zadd(key, score, value);
            return true;
        } catch (Exception ex) {
            logger.error("setSortedSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    /**
     *       
     *
     * @param key
     * @param startScore
     * @param endScore
     * @param orderByDesc
     * @return
     */
    public static Set<String> getSortSet(String key, long startScore, long endScore, boolean orderByDesc) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            if (orderByDesc) {
                return shardedJedis.zrevrangeByScore(key, endScore, startScore);
            } else {
                return shardedJedis.zrangeByScore(key, startScore, endScore);
            }
        } catch (Exception ex) {
            logger.error("getSoredSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    /**
     *       
     *
     * @param key
     * @param startScore
     * @param endScore
     * @return
     */
    public static long countSortZSet(String key, long startScore, long endScore) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            Long count = shardedJedis.zcount(key, startScore, endScore);
            return count == null ? 0L : count;
        } catch (Exception ex) {
            logger.error("countSoredSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0L;
    }

    /**
     *       
     *
     * @param key
     * @return
     */
    public static long countSortZSet(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            Long count = shardedJedis.zcard(key);
            return count == null ? 0L : count;
        } catch (Exception ex) {
            logger.error("countSoredSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0L;
    }

    /**
     *       
     *
     * @param key
     * @param value
     * @return
     */
    public static boolean delSortSet(String key, String value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            long count = shardedJedis.zrem(key, value);
            return count > 0;
        } catch (Exception ex) {
            logger.error("delSortedSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }


    /**
     *       
     *
     * @param key
     * @param startRange
     * @param endRange
     * @param orderByDesc
     * @return
     */
    public static Set<String> getSortSetByRange(String key, int startRange, int endRange, boolean orderByDesc) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            if (orderByDesc) {
                return shardedJedis.zrevrange(key, startRange, endRange);
            } else {
                return shardedJedis.zrange(key, startRange, endRange);
            }
        } catch (Exception ex) {
            logger.error("getSoredSetByRange error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    /**
     *       
     *
     * @param key
     * @return
     */
    public static Double getScore(String key, String member) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.zscore(key, member);
        } catch (Exception ex) {
            logger.error("getSoredSet error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    public static boolean set(String key, String value, int second) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.setex(key, second, value);
            return true;
        } catch (Exception ex) {
            logger.error("set error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }


    public static boolean setTestKeyValue(String key, String value) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.set(key, value);
            return true;
        } catch (Exception ex) {
            logger.error("set error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    public static String get(String key, String defaultValue) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.get(key) == null ? defaultValue : shardedJedis.get(key);
        } catch (Exception ex) {
            logger.error("get error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return defaultValue;
    }

    public static boolean del(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.del(key);
            return true;
        } catch (Exception ex) {
            logger.error("del error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }

    public static boolean del(byte[] key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            shardedJedis.del(key);
            return true;
        } catch (Exception ex) {
            logger.error("del error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return false;
    }
   //  
    public static long incr(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            return shardedJedis.incr(key);
        } catch (Exception ex) {
            logger.error("incr error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0;
    }

    public static long decr(String key) {
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis();
            return shardedJedis.decr(key);
        } catch (Exception ex) {
            logger.error("incr error.", ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return 0;
    }

    /**
     *     set
     *
     * @param key     key
     * @param start       0  
     * @param end       
     * @return    
     */
    public static java.util.Set<java.lang.String> getPageSet(String key, long start, long end) {
        if (key == null || key.equals("")) {
            return null;
        }
        ShardedJedis shardedJedis = null;
        try {
            shardedJedis = JedisPoolHolder.getShardedJedis(true);
            return shardedJedis.zrevrange(key, start, end);
        } catch (Exception ex) {
            logger.error("LTRIM   [key=" + key + " start=" + start + " end=" + end + "]" + ex.getMessage(), ex);
            returnBrokenResource(shardedJedis);
        } finally {
            returnResource(shardedJedis);
        }
        return null;
    }

    private static void returnBrokenResource(ShardedJedis shardedJedis) {
        try {
//            shardedJedisPool.returnBrokenResource(shardedJedis);
            JedisPoolHolder.cleanup();
        } catch (Exception e) {
            logger.error("returnBrokenResource error.", e);
        }
    }

    private static void returnResource(ShardedJedis shardedJedis) {
        try {
//            JedisPoolHolder(shardedJedis);
            JedisPoolHolder.cleanup();
//            .returnResource(shardedJedis);
        } catch (Exception e) {
            logger.error("returnResource error.", e);
        }
    }
}

 
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.*;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;


public class JedisPoolHolder {
    private static final Logger logger = LoggerFactory.getLogger(JedisPoolHolder.class);
    private static ShardedJedisPool pool  ;
    private static ShardedJedisPool poolRead  ;
    private static List<String[]> jedisList=new ArrayList<String[]>();
    private static final ThreadLocal<Unit> holder = new ThreadLocal()
    {
        protected JedisPoolHolder.Unit initialValue() {
            return new JedisPoolHolder.Unit();
        }
    };

    private static final ThreadLocal<UnitRead> holderRead = new ThreadLocal()
    {
        protected JedisPoolHolder.UnitRead initialValue() {
            return new JedisPoolHolder.UnitRead();
        }
    };

    public  static ShardedJedis getShardedJedis(){
        return ((Unit)holder.get()).get();
    }

    public  static ShardedJedis getShardedJedis(boolean isRead){
        if(isRead){
            return ((UnitRead)holderRead.get()).get();
        }else{
            return ((Unit)holder.get()).get();
        }
    }

    public static void cleanup()
    {
        ((Unit)holder.get()).cleanup();
        holder.remove();
        ((UnitRead)holderRead.get()).cleanup();
        holderRead.remove();
    }

    public static void destroyJedisPool()
    {
        pool.destroy();
        poolRead.destroy();
    }

    static {
        String str =ConfigUtil.getValue("framework.redis.url");
        if(str.indexOf("#")>0){
            String[] array = str.split("#");
            List<JedisShardInfo> jdsInfoList= new ArrayList<JedisShardInfo>();
            List<JedisShardInfo> jdsInfoReaderList= new ArrayList<JedisShardInfo>();
            for(int i=0;i<array.length;i++){
                 getRedisServer(array[i]);
            }
            String[] masterArray  = new String[3];

            for(int j =0 ;j<jedisList.size();j++){
                if(j==0){
                    String[] masterHostAndPort = (String[])jedisList.get(j);
                    masterArray = masterHostAndPort;
                   Jedis master = new Jedis(masterHostAndPort[0],Integer.valueOf(masterHostAndPort[1]));

                    JedisShardInfo info = new JedisShardInfo(masterHostAndPort[0],Integer.valueOf(masterHostAndPort[1]));
                    if(masterHostAndPort[2]!=null){
                        info.setPassword(masterHostAndPort[2]);
                        master.auth(masterHostAndPort[2]);
                    }
                    jdsInfoList.add(info);
                    master.slaveofNoOne();
                    pool =new ShardedJedisPool(getConfig(getURI(array[0])), jdsInfoList);
                }else{
                    String[]  slaveHostAndPort = (String[])jedisList.get(j);
                    Jedis slave = new Jedis(slaveHostAndPort[0],Integer.valueOf(slaveHostAndPort[1]));
                    if(slaveHostAndPort[2]!=null){
                        slave.auth(slaveHostAndPort[2]);
                    }
                    slave.slaveof(masterArray[0],Integer.valueOf(masterArray[1]));
                    JedisShardInfo infoRead = new JedisShardInfo(slaveHostAndPort[0],Integer.valueOf(slaveHostAndPort[1]));
                    if(slaveHostAndPort[2]!=null){
                        infoRead.setPassword(slaveHostAndPort[2]);
                    }
                    jdsInfoReaderList.add(infoRead);
                    poolRead =new ShardedJedisPool(getConfig(getURI(array[0])), jdsInfoReaderList);
                }
            }
        }else{
            List<JedisShardInfo> jdsInfoList= new ArrayList<JedisShardInfo>();
            getRedisServer(str);
            JedisShardInfo info =null;
            String[] masterHostAndPort = (String[])jedisList.get(0);
            info = new JedisShardInfo(masterHostAndPort[0],Integer.valueOf(masterHostAndPort[1]));
            if(masterHostAndPort[2]!=null){
                info.setPassword(masterHostAndPort[2]);
            }
            jdsInfoList.add(info);
            pool =new ShardedJedisPool(getConfig(getURI(str)), jdsInfoList);

        }

    }

    private  static JedisPoolConfig getConfig(URI uri){
        int database = Integer.parseInt(uri.getPath().split("/", 2)[1]);
        String clientName = null;
        String sMaxActive = null; String sMaxWait = null; String sTestOnBorrow = null;
        String query = uri.getQuery();
        if (query != null) {
            String[] kvs = query.split("&");
            for (String kv : kvs) {
                String[] arr = kv.split("=");
                if (arr.length == 2)
                {
                    if ("clientName".equals(arr[0])) clientName = arr[1];
                    else if ("maxActive".equals(arr[0])) sMaxActive = arr[1];
                    else if ("maxWait".equals(arr[0])) sMaxWait = arr[1];
                    else if ("testOnBorrow".equals(arr[0])) sTestOnBorrow = arr[1];
                }
            }
        }
        JedisPoolConfig config = new JedisPoolConfig();
        if (sMaxActive != null) {
            config.setMaxTotal(Integer.parseInt(sMaxActive));
        }
        config.setBlockWhenExhausted(true);
        if (sMaxWait != null) {
            config.setMaxWaitMillis(Long.parseLong(sMaxWait));
        }
        if (sTestOnBorrow != null) {
            config.setTestOnBorrow("true".equals(sTestOnBorrow));
        }

        config.setTestWhileIdle(true);
        config.setMinEvictableIdleTimeMillis(60000L);
        config.setTimeBetweenEvictionRunsMillis(30000L);
        config.setNumTestsPerEvictionRun(-1);
        return config;
    }

    private static URI getURI(String str){
        URI uri;
        try
        {
            uri = new URI(str);
        } catch (URISyntaxException e) {
            throw new Error("framework.redis.url [" + str + "]     :" + e.getMessage());
        }
        return uri;
    }

    private static void getRedisServer(String str)
    {
        String[] hostAndPort =new String[3];
//        String str = ConfigHelper.loadString("framework.redis.url");
        URI uri = getURI(str);
        String host = uri.getHost();
        int port = uri.getPort();
        String password = null;
        if (uri.getUserInfo() != null) {
            password = uri.getUserInfo().split(":", 2)[1];
        }

        Jedis jedis = new Jedis(host,port);
        hostAndPort[0]=host;
        hostAndPort[1]=String.valueOf(port);
        hostAndPort[2]=password;
        try {
            jedis.connect();
        } catch (Exception e){
            JedisPoolHolder.logger.error("error ", e);
            JedisPoolHolder.logger.info("  server "+ port+"  down");
        }
        if(jedis.isConnected()){
            jedisList.add(hostAndPort);
            jedis.disconnect();
        }else{
            JedisPoolHolder.logger.info("  server "+ port+"  down");
        }

    }

    private static class Unit
    {
//        Jedis jedis;
        ShardedJedis jedis;
        void cleanup()
        {
            if (this.jedis != null)
            {
                try
                {
//                    JedisHolder.pool.returnResource(this.jedis);
                    pool.returnResource(this.jedis);
                } catch (RuntimeException e) {
                    try {
                        JedisPoolHolder.pool.returnBrokenResource(this.jedis);
                    } catch (RuntimeException e2) {
                        JedisPoolHolder.logger.error("error close Jedis", e2);
                    }
                }
                this.jedis = null;
            }
        }
        public ShardedJedis get(){
            if (this.jedis != null) return this.jedis;
            return this.jedis = (ShardedJedis)pool.getResource();
        }
    }

    private static class UnitRead
    {
        //        Jedis jedis;
        ShardedJedis jedis;
        void cleanup()
        {
            if (this.jedis != null)
            {
                try
                {
//                    JedisHolder.pool.returnResource(this.jedis);
                    poolRead.returnResource(this.jedis);
                } catch (RuntimeException e) {
                    try {
                        JedisPoolHolder.poolRead.returnBrokenResource(this.jedis);
                    } catch (RuntimeException e2) {
                        JedisPoolHolder.logger.error("error close Jedis", e2);
                    }
                }
                this.jedis = null;
            }
        }
        public ShardedJedis get(){
            if (this.jedis != null) return this.jedis;
            return this.jedis = (ShardedJedis)poolRead.getResource();
        }
    }
}

 
 
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.4.2</version>
</dependency>

 
プロファイル
#redis    
#framework.redis.url=redis://:mypass@localhost:6379/0?clientName=open&maxActive=100&maxWait=4000
#redis     #   
framework.redis.url=redis://localhost:6379/0?clientName=scheduler&maxActive=100&maxWait=4000

 
 
分散ロックの適用
if(RedisUtil.acquireLock(lockKey, 1000)) {
            log.info("       ");
}