Redis 一致性哈希(使用 TreeMap 实现)

package com.heatdeath.dev_basic.redis;

import com.heatdeath.dev_basic.utils.PropertiesUtil;
import com.heatdeath.dev_basic.utils.SerializerAndDeserializerUtil;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.*;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.*;


public class RedisFacadeNew {

    private final static String CHARSET = "UTF-8";
    private final static String INST_PREFIX = "RedisInst-";

    private JedisPool masterJedisPool;

    private static PropertiesUtil propUtil = PropertiesUtil.load("application.properties");
    private static Integer instNum = Integer.valueOf(propUtil.get("redis.instanceNum"));

    private final static Object lock = new Object();

    private RedisFacadeNew() {
    }

    private static volatile SortedMap<Long, RedisFacadeNew> nodes;
    private static final int NODE_NUM = 100;

    // 注意:初始化redis失败需要直接退出,否则可能引用到空的实例
    public static RedisFacadeNew getInstance(String key) throws BeansException {
        if (nodes == null) {
            synchronized (lock) {
                if (nodes == null) {
                    nodes = new TreeMap<>();
                    for (int i = 0; i < instNum; i++) {
                        RedisFacadeNew rf = new RedisFacadeNew();
                        String instName = INST_PREFIX + i;
                        rf.masterJedisPool = (JedisPool) SpringBeanUtil.getBean(instName);

                        for (int n = 0; n < NODE_NUM; n++) {
                            nodes.put(hash("Redis-" + i + "-Node-" + n), rf);
                        }
                    }
                }
            }
        }
        return getShardInfo(key);
    }

    private static RedisFacadeNew getShardInfo(String key) {
        SortedMap<Long, RedisFacadeNew> tail = nodes.tailMap(hash(key));
        if (tail.size() == 0)
            return nodes.get(nodes.firstKey());
        return tail.get(tail.firstKey());
    }

    /**
     * MurMurHash算法,是非加密HASH算法,性能很高,
     * 比传统的CRC32,MD5,SHA-1(这两个算法都是加密HASH算法,复杂度本身就很高,带来的性能上的损害也不可避免)
     * 等HASH算法要快很多,而且据说这个算法的碰撞率很低.
     * http://murmurhash.googlepages.com/
     */
    private static Long hash(String key) {

        ByteBuffer buf = ByteBuffer.wrap(key.getBytes());
        int seed = 0x1234ABCD;

        ByteOrder byteOrder = buf.order();
        buf.order(ByteOrder.LITTLE_ENDIAN);

        long m = 0xc6a4a7935bd1e995L;
        int r = 47;

        long h = seed ^ (buf.remaining() * m);

        long k;
        while (buf.remaining() >= 8) {
            k = buf.getLong();

            k *= m;
            k ^= k >>> r;
            k *= m;

            h ^= k;
            h *= m;
        }

        if (buf.remaining() > 0) {
            ByteBuffer finish = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
            finish.put(buf).rewind();
            h ^= finish.getLong();
            h *= m;
        }

        h ^= h >>> r;
        h *= m;
        h ^= h >>> r;

        buf.order(byteOrder);
        return h;
    }

    /**
     * 非线程安全设置String型缓存值
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) throws Exception {
        if (StringUtils.isBlank(key) || StringUtils.isBlank(value)) {
            return;
        }

        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            byte[] realKey = key.getBytes(CHARSET);
            byte[] realValue = value.getBytes(CHARSET);
            jedis.set(realKey, realValue);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
    }

    /**
     * 非线程安全获得String类型缓存值
     *
     * @param key
     * @return String
     */
    public String get(String key) throws Exception {
        if (StringUtils.isBlank(key)) {
            return null;
        }
        Jedis jedis = null;
        jedis.set()
        boolean flag = false;
        try {
            jedis = getResource();
            byte[] realKey = key.getBytes(CHARSET);
            byte[] valueByteArray = jedis.get(realKey);
            if (!ArrayUtils.isEmpty(valueByteArray)) {
                return new String(valueByteArray, "UTF-8");
            }
            return null;
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
    }

    public Boolean exists(String key) throws Exception {
        Boolean result = false;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.exists(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }

        return result;
    }

    public String type(String key) throws Exception {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.type(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }

        return result;
    }

    /**
     * 在某段时间后失效
     */
    public Long expire(String key, int seconds) throws Exception {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.expire(key, seconds);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    /**
     * 在某个时间点失效
     */
    public Long expireAt(String key, long time) throws Exception {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.expireAt(key, time);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long ttl(String key) throws Exception {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.ttl(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public boolean setbit(String key, long offset, boolean value) {
        boolean result = false;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.setbit(key, offset, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    private Jedis getResource() {
        Jedis jedis = masterJedisPool.getResource();
        if (jedis == null) {
            throw new NullPointerException("null_jedis_instance");
        }
        return jedis;
    }

    public boolean getbit(String key, long offset) {
        boolean result = false;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.getbit(key, offset);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public long setrange(String key, long offset, String value) {
        long result = 0;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.setrange(key, offset, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String getrange(String key, long startOffset, long endOffset) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.getrange(key, startOffset, endOffset);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String getSet(String key, String value) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.getSet(key, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long setnx(String key, String value) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.setnx(key, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String setex(String key, int seconds, String value) {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.setex(key, seconds, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long decrBy(String key, long integer) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.decrBy(key, integer);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long decr(String key) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.decr(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long incrBy(String key, long integer) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.incrBy(key, integer);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long incr(String key) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.incr(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long append(String key, String value) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.append(key, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String substr(String key, int start, int end) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.substr(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long hset(String key, String field, String value) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hset(key, field, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String hget(String key, String field) {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.hget(key, field);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long hsetnx(String key, String field, String value) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hsetnx(key, field, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String hmset(String key, Map<String, String> hash) {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.hmset(key, hash);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public List<String> hmget(String key, String... fields) {
        List<String> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.hmget(key, fields);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long hincrBy(String key, String field, long value) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hincrBy(key, field, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Boolean hexists(String key, String field) {
        Boolean result = false;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hexists(key, field);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long del(String key) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.del(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }


    public Long hdel(String key, String field) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.hdel(key, field);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long hlen(String key) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hlen(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> hkeys(String key) {
        Set<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hkeys(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public List<String> hvals(String key) {
        List<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hvals(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Map<String, String> hgetAll(String key) {
        Map<String, String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.hgetAll(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    /**
     * 在redis list尾部增加一个String
     */
    public Long rpush(String key, String string) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.rpush(key, string);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    /**
     * 在redis list头部增加一个String
     */
    public Long lpush(String key, String string) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.lpush(key, string);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long llen(String key) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.llen(key);

        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public List<String> lrange(String key, long start, long end) {
        List<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.lrange(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String ltrim(String key, long start, long end) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.ltrim(key, start, end);

        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String lIndex(String key, long index) {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.lindex(key, index);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String lset(String key, long index, String value) {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.lset(key, index, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long lrem(String key, long count, String value) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.lrem(key, count, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    /**
     * 从redis list头部取出一个key
     */
    public String lpop(String key) {
        String result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.lpop(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    /**
     * 从redis list尾部取出一个key
     */
    public String rpop(String key) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.rpop(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long sadd(String key, String member) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.sadd(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> smembers(String key) {
        Set<String> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.smembers(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long srem(String key, String member) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.srem(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String spop(String key) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.spop(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long scard(String key) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.scard(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Boolean sismember(String key, String member) {
        Boolean result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.sismember(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public String srandmember(String key) {
        String result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.srandmember(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zadd(String key, double score, String member) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zadd(key, score, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> zrange(String key, int start, int end) {
        Set<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zrange(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zrem(String key, String member) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zrem(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Double zincrby(String key, double score, String member) {
        Double result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zincrby(key, score, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zrank(String key, String member) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zrank(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zrevrank(String key, String member) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrevrank(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> zrevrange(String key, int start, int end) {
        Set<String> result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.zrevrange(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<Tuple> zrangeWithScores(String key, int start, int end) {
        Set<Tuple> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zrangeWithScores(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<Tuple> zrevrangeWithScores(String key, int start, int end) {
        Set<Tuple> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zrevrangeWithScores(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zcard(String key) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zcard(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Double zscore(String key, String member) {
        Double result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zscore(key, member);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public List<String> sort(String key) {
        List<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.sort(key);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public List<String> sort(String key, SortingParams sortingParameters) {
        List<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.sort(key, sortingParameters);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zcount(String key, double min, double max) {
        Long result = null;
        boolean flag = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.zcount(key, min, max);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> zrangeByScore(String key, double min, double max) {
        Set<String> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrangeByScore(key, min, max);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> zrevrangeByScore(String key, double max, double min) {
        Set<String> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrevrangeByScore(key, max, min);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> zrangeByScore(String key, double min, double max,
                                     int offset, int count) {
        Set<String> result = null;
        boolean flag = false;
        Jedis jedis = null;

        try {
            jedis = getResource();
            result = jedis.zrangeByScore(key, min, max, offset, count);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<String> zrevrangeByScore(String key, double max, double min,
                                        int offset, int count) {
        Set<String> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrevrangeByScore(key, max, min, offset, count);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<Tuple> zrangeByScoreWithScores(String key, double min, double max) {
        Set<Tuple> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrangeByScoreWithScores(key, min, max);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
                                                 double min) {
        Set<Tuple> result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.zrevrangeByScoreWithScores(key, max, min);

        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<Tuple> zrangeByScoreWithScores(String key, double min,
                                              double max, int offset, int count) {
        Set<Tuple> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrangeByScoreWithScores(key, min, max, offset, count);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Set<Tuple> zrevrangeByScoreWithScores(String key, double max,
                                                 double min, int offset, int count) {
        Set<Tuple> result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zrevrangeByScoreWithScores(key, max, min, offset, count);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zremrangeByRank(String key, int start, int end) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            result = jedis.zremrangeByRank(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long zremrangeByScore(String key, double start, double end) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.zremrangeByScore(key, start, end);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }

    public Long linsert(String key, LIST_POSITION where, String pivot,
                        String value) {
        Long result = null;
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            result = jedis.linsert(key, where, pivot, value);
        } catch (Exception e) {
            flag = true;
            throw new RuntimeException(e);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
        return result;
    }


    /**
     * 非线程安全设置对象型缓存值
     *
     * @param key
     * @param value
     */
    public void setObject(String key, Object value) {
        if (StringUtils.isBlank(key) || value == null) {
            return;
        }

        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            byte[] realKey = key.getBytes(CHARSET);
            byte[] realValue = SerializerAndDeserializerUtil.serialize(value);
            jedis.set(realKey, realValue);
        } catch (Exception ex) {
            flag = true;
            throw new RuntimeException(ex);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
    }

    /**
     * 非线程安全获取对象型缓存值
     *
     * @param key
     * @return Object
     */
    public Object getObject(String key) {
        if (StringUtils.isBlank(key)) {
            return null;
        }

        Jedis jedis = null;
        boolean flag = false;

        try {
            jedis = getResource();
            byte[] realKey = key.getBytes(CHARSET);
            byte[] valueByteArray = jedis.get(realKey);
            if (!ArrayUtils.isEmpty(valueByteArray)) {
                return SerializerAndDeserializerUtil.deserialize(valueByteArray);
            } else {
                return null;
            }
        } catch (Exception ex) {
            flag = true;
            throw new RuntimeException(ex);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
    }

    public void returnResource(ShardedJedisPool shardedJedisPool,
                               ShardedJedis shardedJedis, boolean broken) {
        shardedJedis.close();
    }

    public void returnResource(JedisPool jedisPool, Jedis jedis, boolean broken) {
        jedis.close();
    }

    /**
     * 批量获取缓存值(一次不要超过20个)
     *
     * @param key
     */
    public List<String> mget(String... key) {
        Jedis jedis = null;
        boolean flag = false;
        try {
            jedis = getResource();
            return jedis.mget(key);
        } catch (Exception ex) {
            flag = true;
            throw new RuntimeException(ex);
        } finally {
            this.returnResource(masterJedisPool, jedis, flag);
        }
    }
}

spring-redis.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxTotal" value="${redis.pool.maxActive}"/>
        <property name="maxIdle" value="${redis.pool.maxIdle}"/>
        <property name="maxWaitMillis" value="${redis.pool.maxWait}"/>
        <property name="testOnBorrow" value="${redis.pool.testOnBorrow}"/>
        <property name="testOnReturn" value="${redis.pool.testOnReturn}"/>
        <property name="testWhileIdle" value="${redis.pool.testWhileIdle}"/>
    </bean>

    <bean id="RedisInst-0" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1" value="${redis0.ip}" type="java.lang.String"/>
        <constructor-arg index="2" value="${redis0.port}" type="int"/>
        <constructor-arg index="3" value="${redis.timeout}" type="int"/>
    </bean>

    <bean id="RedisInst-1" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1" value="${redis1.ip}" type="java.lang.String"/>
        <constructor-arg index="2" value="${redis1.port}" type="int"/>
        <constructor-arg index="3" value="${redis.timeout}" type="int"/>
    </bean>

    <bean id="RedisInst-2" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1" value="${redis2.ip}" type="java.lang.String"/>
        <constructor-arg index="2" value="${redis2.port}" type="int"/>
        <constructor-arg index="3" value="${redis.timeout}" type="int"/>
    </bean>

    <bean id="RedisInst-3" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1" value="${redis3.ip}" type="java.lang.String"/>
        <constructor-arg index="2" value="${redis3.port}" type="int"/>
        <constructor-arg index="3" value="${redis.timeout}" type="int"/>
    </bean>

    <bean id="RedisInst-4" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig"/>
        <constructor-arg index="1" value="${redis4.ip}" type="java.lang.String"/>
        <constructor-arg index="2" value="${redis4.port}" type="int"/>
        <constructor-arg index="3" value="${redis.timeout}" type="int"/>
    </bean>

</beans>

配置文件属性获取工具类

package com.heatdeath.dev_basic.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * The type Properties util.
 */
@Slf4j
public class PropertiesUtil {

    private static final Map<String, PropertiesUtil> map = new ConcurrentHashMap<>();

    private Properties pros;

    private PropertiesUtil(Properties pros) {
        this.pros = pros;
    }

    /**
     * Load properties util.
     *
     * @param filePath the file path
     * @return the properties util
     */
    public static PropertiesUtil load(String filePath) {
        if (!map.containsKey(filePath)) {
            synchronized (map) {
                if (!map.containsKey(filePath)) {
                    log.debug("加载" + filePath + "配置文件");
                    ClassLoader loader = Thread.currentThread().getContextClassLoader();
                    try (InputStream input = loader.getResourceAsStream(filePath);
                         InputStreamReader reader = new InputStreamReader(input, "UTF-8")) {
                        Properties pros = new Properties();
                        pros.load(reader);
                        map.put(filePath, new PropertiesUtil(pros));
                    } catch (IOException e) {
                        //为书写方便, 不抛出异常,结果返回null
                        log.error("加载" + filePath + "配置文件异常", ExceptionUtils.getRootCauseMessage(e));
                    }
                }
            }
        }
        return map.get(filePath);
    }

    /**
     * Get string.
     *
     * @param key the key
     * @return the string
     */
    public String get(String key) {
        return pros.getProperty(key);
    }

    /**
     * Gets pro value format.
     *
     * @param key the key
     * @param obj the obj
     * @return the pro value format
     */
    public String getProValueFormat(String key, Object... obj) {
        String str = pros.getProperty(key);
        return MessageFormat.format(str, obj);
    }

    /**
     * Gets value or default.
     *
     * @param key          the key
     * @param defaultValue the default value
     * @return the value or default
     */
    public String getValueOrDefault(String key, String defaultValue) {
        return pros.getProperty(key, defaultValue);
    }
}


对象序列化与反序列化工具类

package com.heatdeath.dev_basic.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 序列化、反序列化 工具类
 */
public class SerializerAndDeserializerUtil {

    /**
     * 将对象 Object 序列化为 byte[] 字节数组
     *
     * @param object the object
     * @return the byte [ ]
     * @throws Exception the exception
     */
    public static byte[] serialize(Object object) throws Exception {
        ObjectOutputStream objectOutputStream;
        ByteArrayOutputStream byteArrayOutputStream;
        byteArrayOutputStream = new ByteArrayOutputStream();
        objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 将 byte[] 字节数组 反序列化为 对象 Object
     *
     * @param bytes the bytes
     * @return the object
     * @throws Exception the exception
     */
    public static Object deserialize(byte[] bytes) throws Exception {
        ByteArrayInputStream byteArrayInputStream;
        // 反序列化
        byteArrayInputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(byteArrayInputStream);
        return ois.readObject();
    }
}

猜你喜欢

转载自blog.csdn.net/heatdeath/article/details/80548211
今日推荐