此时情绪此时天,无事小神仙
好好生活,平平淡淡每一天

编辑

Redis工具类

Redis引入jar包

 

Redis工具类

package net.wwwyibu.filter;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;
import org.json.JSONException;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import net.sf.json.util.PropertySetStrategy;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.jedis.Tuple;

/**
 * @author 马家立
 * @version 创建时间:2020-7-29 16:54:56
 * @Description:TODO Redis工具类
 * @Description:TODO 菜鸟教程--https://www.runoob.com/redis/redis-tutorial.html
 * @Description:TODO w3cschool教程--https://www.w3cschool.cn/redis/redis-commands.html
 */
public class RedisUtil {
    private static Logger log = Logger.getLogger(RedisUtil.class);

    /**
     * --获取redis的ip
     */
    private static String redisIp = getRedisIp();

    /**
     * --非切片客户端链接
     */
    private Jedis jedis;
    /**
     * --非切片链接池
     */
    private JedisPool jedisPool;
    /**
     * --切片客户端链接
     */
    private ShardedJedis shardedJedis;
    /**
     * --切片客户端链接池
     */
    private ShardedJedisPool shardedJedisPool;

    /**
     * --构造函数
     */
    public RedisUtil() {
        initialJedisPool();
        initialShardedJedisPool();
    }

    public Jedis getJedis() {
        if (jedis == null) {
            initialJedisPool();
        }
        return jedis;
    }

    public void setJedis(Jedis jedis) {
        this.jedis = jedis;
    }

    public ShardedJedis getShardedJedis() {
        if (shardedJedis == null) {
            initialShardedJedisPool();
        }
        return shardedJedis;
    }

    public void setShardedJedis(ShardedJedis shardedJedis) {
        this.shardedJedis = shardedJedis;
    }
    /**
     * @Title:getIp
     * @Description:TODO 获取redis的ip
     * @author:马家立
     * @date:2020-7-29 17:00:51
     * @return String
     */
    static String getRedisIp() {
        try {
            return InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return "127.0.0.1";
    }


    /**
     * @Title:initialJedisPool
     * @Description:TODO 初始化非切片客户端链接
     * @author:马家立
     * @date:2020-7-30 16:39:05 void
     */
    private void initialJedisPool() {
        // Jedis连接池配置
        JedisPoolConfig config = new JedisPoolConfig();
        /**
         * --控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
         * --最大连接数:如果赋值为-1,则表示不限制;如果pool已经分配了maxActive(最大连接数)个jedis实例,则此时pool的状态为exhausted(耗尽)。
         */
        config.setMaxActive(300);
        // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
        config.setMaxIdle(100);
        // 设置最大阻塞时间:表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
        config.setMaxWait(1000 * 5);
        // 在borrow(引入)一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
        config.setTestOnBorrow(false);
        jedisPool = new JedisPool(config, redisIp, 6379);
        setJedis(jedisPool.getResource());
    }

    /**
     * @Title:initialShardedJedisPool
     * @Description:TODO 初始化切片客户端链接
     * @author:马家立
     * @date:2020-7-30 16:39:29 void
     */
    private void initialShardedJedisPool() {
        // Jedis连接池配置
        JedisPoolConfig config = new JedisPoolConfig();
        /**
         * --控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
         * --最大连接数:如果赋值为-1,则表示不限制;如果pool已经分配了maxActive(最大连接数)个jedis实例,则此时pool的状态为exhausted(耗尽)。
         */
        config.setMaxActive(300);
        // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
        config.setMaxIdle(100);
        // 设置最大阻塞时间:表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
        config.setMaxWait(1000 * 5);
        // 在borrow(引入)一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
        config.setTestOnBorrow(false);
        // slave链接
        List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
        shards.add(new JedisShardInfo(redisIp, 6379));
        shardedJedisPool = new ShardedJedisPool(config, shards);
        setShardedJedis(shardedJedisPool.getResource());
    }

    /**
     * @Title:jedisMethod
     * @Description:TODO jedis相关方法
     * @author:马家立
     * @date:2020-7-30 16:53:10 void
     */
    public void jedisMethod() {
        jedis = getJedis();
        // 清空链接数据
        jedis.flushDB();
        jedis.echo("foo");
        // 交集
        System.out.println(jedis.sinter("" + "", "sets2"));
        // 并集
        System.out.println(jedis.sunion("sets1", "sets2"));
        // 差集
        System.out.println(jedis.sdiff("sets1", "sets2"));
        System.out.println(jedis.mset("mset1", "mvalue1", "mset2", "mvalue2", "mset3", "mvalue3", "mset4", "mvalue4"));
        System.out.println(jedis.mget("mset1", "mset2", "mset3", "mset4"));
        System.out.println(jedis.del(new String[] {"foo", "foo1", "foo3"}));
    }
    /**
     * @Description:TODO String类型开始
     */
    void String_Type_Start() {}

    /**
     * @Title:set
     * @Description:TODO 储存某个Key和值
     * @author:马家立
     * @date:2020-7-28 15:07:56
     * @param Key--存储的key
     * @param value--存储的值
     * @return boolean
     */
    public boolean set(String Key, String value) {
        try {
            getShardedJedis().set(Key, value);
            // 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
            shardedJedisPool.returnBrokenResource(getShardedJedis());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            // 否则调用returnResource()返回正常链接
            shardedJedisPool.returnResource(getShardedJedis());
            return false;
        }
    }
    
    /**
     * @Title:setex
     * @Description:TODO 存储某个Key和值并设置超时时间
     * @author:马家立
     * @date:2020-7-28 15:06:25
     * @param Key--存储的key
     * @param time--超时时间(秒)
     * @param value--存储的值
     * @return boolean
     */
    public boolean setex(String Key, int time, String value) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            jedis.setex(Key, time, value);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:expire
     * @Description:TODO 设置 key 的过期时间,key 过期后将不再可用。单位以秒计。
     * @author:马家立
     * @date:2020-7-29 16:46:39
     * @param Key
     * @param time
     * @return boolean
     */
    public boolean expire(String Key, int time) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // 设置成功返回 1 。 当 key 不存在或者不能为 key 设置过期时间时(比如在低于 2.1.3 版本的 Redis 中你尝试更新 key 的过期时间)返回 0 。
            jedis.expire(Key, time);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:setObject
     * @Description:TODO 存储某个Key和Object对象值
     * @author:马家立
     * @date:2020-7-28 15:14:12
     * @param key--存储的key
     * @param value--存储的Object对象值
     * @return boolean
     */
    public boolean setObject(String key, Object value) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            log.info("set = " + key + " 转化前 value=" + value);
            String objectJson = "";
            if ((value instanceof String) || (value instanceof JSONObject)) {// 如果传进来的是String或者JSONObject,不进行转换
                objectJson = value + "";
            } else {// 是普通对象,进行beanToJson转化
                JSONObject jsonObject = JSONObject.fromObject(value);
                objectJson = jsonObject.toString();
            }
            log.info("Inkeys = " + key + " 转化后InValue=" + objectJson);
            jedis = getShardedJedis();
            jedis.set(key, objectJson);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.info("setObject缓存方法出错");
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }
    
    /**
     * @Title:get
     * @Description:TODO 获取某个key的value
     * @author:马家立
     * @date:2020-7-28 15:03:05
     * @param Key--redis存储的key
     * @return String
     */
    public String get(String Key) {
        String end = null;
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            end = jedis.get(Key);
            return end;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }
    
    /**
     * @Title:getObject
     * @Description:TODO 获取某个key的对象value
     * @author:马家立
     * @date:2020-7-28 15:16:32
     * @param key----存储的key
     * @param clas--该key对应的对象值
     * @return Object
     */
    public Object getObject(String key, Class clas) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            String value = jedis.get(key);
            // 根据json字符串解析class对象
            return jsonToBean(value, clas);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.info("getObject缓存方法出错");
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:del
     * @Description:TODO 删除某个key
     * @author:马家立
     * @date:2020-7-28 18:07:36
     * @param Key--被删除的key
     * @return boolean
     */
    public boolean del(String Key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            jedis.del(Key);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:exists
     * @Description:TODO 判断某个key是否存在
     * @author:马家立
     * @date:2020-7-28 18:08:44
     * @param key--要判断的key
     * @return boolean
     */
    public boolean exists(String key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            return jedis.exists(key);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }
    
    /**
     * @Title:existsttl
     * @Description:TODO 给定 key 的剩余生存时间(单位:s)
     * @author:马家立
     * @date:2020-7-29 16:08:14
     * @param key
     * @return Long
     */
    public Long existsttl(String key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            Long i = jedis.ttl(key);
            return i;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return -1L;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }
    /**
     * @Description:TODO Hash类型开始
     */
    void Hash_Type_Start() {}


    /**
     * @Title:setHash
     * @Description:TODO 储存某个Key和hash对象值
     * @author:马家立
     * @date:2020-7-28 15:28:36
     * @param key--存储的key
     * @param map--存储的hash对象值
     * @return boolean
     */
    public boolean setHash(String key, Map<String, String> map) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            jedis.hmset(key, map);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.info("setHash缓存方法出错");
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:setHashKey
     * @Description:TODO 储存某个Key中hash对象值中的key值:如果哈希表不存在,创建一个新的哈希表并进行 HSET操作;如果字段已经存在于哈希表中,旧值将被覆盖。
     * @author:马家立
     * @date:2020-7-28 15:29:56
     * @param key--存储的hash的key
     * @param inkey--hash对象中的key
     * @param value--hash对象中的key对应存储的值
     * @return boolean
     */
    public boolean setHashKey(String key, String inkey, String value) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // 如果字段是哈希表中的一个新建字段,并且值设置成功,返回 1 。 如果哈希表中域字段已经存在且旧值已被新值覆盖,返回 0
            jedis.hset(key, inkey, value);
            // jedis.disconnect();
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.info("setHash缓存方法出错");
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }
    
    /**
     * @Title:hget
     * @Description:TODO 读取某个hash表中的某个key所对应的value值
     * @author:马家立
     * @date:2020-7-28 17:58:03
     * @param key--存储的hash的key
     * @param inkey--hash中的key
     * @return String
     */
    public String hget(String key, String inkey) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            return jedis.hget(key, inkey);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:hkeys
     * @Description:TODO 获取哈希表中的key
     * @author:马家立
     * @date:2020-7-28 18:00:44
     * @param key--存储的hash的key
     * @return Set<String>
     */
    public Set<String> hkeys(String key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            return jedis.hkeys(key);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:hgetAll
     * @Description:TODO 获取哈希表中,所有的字段和值。
     * @author:马家立
     * @date:2020-7-29 16:33:24
     * @param key
     * @return Map<String,String>
     */
    public Map<String, String> hgetAll(String key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            return jedis.hgetAll(key);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }
    /**
     * @Title:delHash
     * @Description:TODO 删除哈希表 key中的一个或多个指定字段,不存在的字段将被忽略
     * @author:马家立
     * @date:2020-7-28 15:48:32
     * @param key--存储的hash的key
     * @param inkey--hash中的key
     * @return boolean
     */
    public boolean delHash(String key, String inkey) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            jedis.hdel(key, inkey);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Description:TODO List类型开始
     */
    void List_Type_Start() {}

    /**
     * @Title:lpush
     * @Description:TODO 将一个或多个值插入到列表头部。 如果 key不存在,一个空列表会被创建并执行 LPUSH 操作。 当 key存在但不是列表类型时,返回一个错误。
     * @author:马家立
     * @date:2020-7-29 16:16:34
     * @param Key
     * @param value
     * @return boolean
     */
    public boolean lpush(String Key, String value) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // value可为数组
            jedis.lpush(Key, value);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * 
     * @Title:rpush
     * @Description:TODO 将一个或多个值插入到列表的尾部(最右边)。如果列表不存在,一个空列表会被创建并执行 RPUSH 操作。 当列表存在但不是列表类型时,返回一个错误。
     * @author:马家立
     * @date:2020-7-29 16:34:58
     * @param key
     * @param value
     * @return boolean
     */
    public boolean rpush(String key, String value) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            jedis.rpush(key, value);
            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * @Title:lpop
     * @Description:TODO 移除并返回列表的第一个元素
     * @author:马家立
     * @date:2020-7-29 16:39:22
     * @param key
     * @return String 列表的第一个元素。 当列表 key 不存在时,返回 nil
     */
    public String lpop(String key) {
        String value = null;
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            value = jedis.lpop(key);
            return value;
        } catch (Exception e) {
            error = true;
            e.printStackTrace(); log.error(e.getMessage(), e);
            return value;
        } finally {
            if(jedis!=null){
                if(shardedJedisPool!=null){
                    if(error){// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    }else{// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * @Title:rpop
     * @Description:TODO 移除并返回列表的最后一个元素
     * @author:马家立
     * @date:2020-7-29 16:39:22
     * @param key
     * @return String 列表的最后一个元素。 当列表 key 不存在时,返回 nil
     */
    public String rpop(String key) {
        String value = null;
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            value = jedis.rpop(key);
            return value;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return value;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }
    
    /**
     * @Title:lrem
     * @Description:TODO 根据参数 COUNT 的值,移除列表中与参数 VALUE 相等的元素。
     * @Description:TODO COUNT 的值可以是以下几种:
     * @Description:TODO count > 0 : 从表头开始向表尾搜索,移除与 VALUE 相等的元素,数量为 COUNT 。
     * @Description:TODO count < 0 : 从表尾开始向表头搜索,移除与 VALUE 相等的元素,数量为 COUNT 的绝对值。
     * @Description:TODO count = 0 : 移除表中所有与 VALUE 相等的值。
     * @author:马家立
     * @date:2020-7-29 16:27:09
     * @param Key
     * @param value
     * @return String
     */
    public String lrem(String Key, int count, String value) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            jedis.lrem(Key, count, value);
            return "0";
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return "-1";
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * @Title:lrange
     * @Description:TODO 读取某个key并以并返回start~end区间中的list数据
     * @author:马家立
     * @date:2020-7-29 16:19:08
     * @param Key
     * @param start
     * @param end
     * @return List<String>
     */
    public List<String> lrange(String Key, int start, int end) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // 若jedis.lrange(Key, 0, -1)则返回list所有数据
            return jedis.lrange(Key, start, end);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * @Title:ltrim
     * @Description:TODO 保留指定区间内的元素,不在指定区间之内的元素都将被删除。
     * @author:马家立
     * @date:2020-7-29 16:23:39
     * @param Key
     * @param start
     * @param end
     * @return boolean
     */
    public boolean ltrim(String Key, int start, int end) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            /**
             * -- 若jedis.lrange(Key, 0, -1)则返回list所有数据 --若命令执行成功时,返回 ok 。
             */
            return "ok".equals(jedis.ltrim(Key, start, end)) ? true : false;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * @Title:getListSize
     * @Description:TODO 获取List的长度
     * @author:马家立
     * @date:2020-7-29 15:36:44
     * @param key
     * @return long
     */
    public long getListSize(String key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        long length = 0L;
        try {
            jedis = getShardedJedis();
            length = jedis.llen(key);
            return length;
        } catch (Exception e) {
            error = true;
            log.error("llen error", e);
            return length;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }
    }

    /**
     * @Title:queueExists
     * @Description:TODO 判断队列是否存在
     * @author:马家立
     * @date:2020-7-29 16:06:49
     * @param name
     * @return boolean
     */
    public boolean queueExists(String name) {
        if(exists(name)) {
            //key存在,获得长度
            return getListSize(name) > 0 ? true : false;
        }
        return false;
    }

    /**
     * @Description:TODO Set类型开始
     */
    void Set_Type_Start() {}

    /**
     * @Description:TODO Sorted Set类型开始
     */
    void SortedSet_Type_Start() {}

    /**
     * @Title:zadd
     * @Description:TODO 储存一个对象到Sorted-Sets
     * @author:马家立
     * @date:2020-7-28 16:02:54
     * @param key--存储的Set集合的key
     * @param score--分数
     * @param member--成员
     * @return boolean
     */
    public boolean zadd(String key, double score, String member) {
        log.info("zadd--------key:" + key + ",score:" + score + ",member:" + member);
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            Long end = jedis.zadd(key, score, member);
            log.info("zadd--------end jedis.zadd:" + end);

            return true;
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return false;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
                // jedis.disconnect();
            }
        }
    }

    /**
     * @Title:zrevrangeWithScores
     * @Description:TODO 从小到大取出Sorted-Sets
     * @author:马家立
     * @date:2020-7-28 16:06:31
     * @param key--存储的Set集合的key
     * @param start--开始分值
     * @param end--结束分值
     * @return Set<Tuple>
     */
    public Set<Tuple> zrevrangeWithScores(String key, int start, int end) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // jedis.zrevrangeWithScores(key, 0, -1);0,-1:返回所有
            return jedis.zrevrangeWithScores(key, start, end);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:zrangeWithScores
     * @Description:TODO 从大到小取出Sorted-Sets
     * @author:马家立
     * @date:2020-7-28 16:43:27
     * @param key--存储的Set集合的key
     * @param start--开始分值
     * @param end--结束分值
     * @return Set<Tuple>
     */
    public Set<Tuple> zrangeWithScores(String key, int start, int end) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // jedis.zrangeWithScores(key, 0, -1);0,-1:返回所有
            return jedis.zrangeWithScores(key, start, end);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:zrange
     * @Description:TODO 从小到大取出Sorted-Sets
     * @author:马家立
     * @date:2020-7-28 17:53:21
     * @param key--存储的Set集合的key
     * @param start--开始分值
     * @param end--结束分值
     * @return Set<String>
     */
    public Set<String> zrange(String key, int start, int end) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            return jedis.zrange(key, start, end);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:zrangeByScore
     * @Description:TODO 返回所有符合条件start < score <= end的成员;
     * @author:马家立
     * @date:2020-7-28 17:54:04
     * @param key--存储的Set集合的key
     * @param start--开始分值
     * @param end--结束分值
     * @return Set<String>
     */
    public Set<String> zrangeByScore(String key, Double start, Double end) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            return jedis.zrangeByScore(key, start, end);
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return null;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:zrem
     * @Description:TODO 从Sorted-Sets中移除的一个或多个成员,不存在的成员将被忽略。
     * @author:马家立
     * @date:2020-7-28 18:02:12
     * @param key--存储的Set集合的key
     * @param inkey--Set集合中的key
     * @return String
     */
    public String zrem(String key, String inkey) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            // 被成功移除的成员的数量,不包括被忽略的成员。
            System.out.println(jedis.zrem(key, inkey));
            return "0";
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return "-1";
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:zremrangebyscore
     * @Description:TODO 从Sorted-Sets 中移除指定分数(score)区间内的所有成员
     * @author:马家立
     * @date:2020-7-28 18:05:39
     * @param key--存储的Set集合的key
     * @param start--开始分值
     * @param end--结束分值
     * @return String
     */
    public String zremrangebyscore(String Key, Double start, Double end) {

        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        try {
            jedis = getShardedJedis();
            System.out.println(jedis.zremrangeByScore(Key, start, end));
            return "0";
        } catch (Exception e) {
            error = true;
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return "-1";
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
            // jedis.disconnect();
        }
    }

    /**
     * @Title:getsortedSetSize
     * @Description:TODO 获取Sorted Set的长度
     * @author:马家立
     * @date:2020-7-29 16:01:52
     * @param key--获取SortedSet集合的key
     * @return long
     */
    public long getSortedSetSize(String key) {
        ShardedJedis jedis = null;
        boolean error = false;// 标记缓存操作过程是否出现异常
        long length = 0L;
        try {
            jedis = getShardedJedis();
            length = jedis.zcard(key);
            return length;
        } catch (Exception e) {
            error = true;
            log.error("llen error", e);
            return length;
        } finally {
            if (jedis != null) {
                if (shardedJedisPool != null) {
                    if (error) {// 如果操作过程出现异常,调用returnBrokenResource()返回有问题的链接
                        shardedJedisPool.returnBrokenResource(jedis);
                    } else {// 否则调用returnResource()正常返回链接
                        shardedJedisPool.returnResource(jedis);
                    }
                }
            }
        }

    }

    /**
     * @Title:jsonToBean
     * @Description:TODO 根据json字符串解析class对象
     * @author:马家立
     * @date:2020-7-28 15:18:36
     * @param jsonString--json字符串
     * @param clas--class对象
     * @return Object
     */
    public static Object jsonToBean(String jsonString, Class<?> clas) {
        JSONObject jo = JSONObject.fromObject(jsonString);
        JsonConfig cfg = new JsonConfig();
        Map<String, Object> classMap = new HashMap<String, Object>();
        cfg.setClassMap(classMap);
        cfg.setRootClass(clas);
        cfg.setPropertySetStrategy(PropertySetStrategy.DEFAULT);
        return JSONObject.toBean(jo, cfg);
    }

    public static void main(String[] args) throws JSONException, IOException {
        // RedisUtil redis = new RedisUtil();
        // redis.setHashKey("yayaya", "1", "haha");
        // redis.setHashKey("yayaya", "2", "hehe");
        // redis.setHashKey("yayaya", "3", "lala");
        // // redis.expire("yayaya", 10);
        // Set<String> hgets = redis.hkeys("yayaya");
        // for (String string : hgets) {
        // String value = redis.hget("yayaya", string);
        // System.out.println("string:" + string + ",value:" + value);
        // }
        List<String> values = new ArrayList<String>();
        String[] ss = values.toArray(new String[values.size()]);
    }
}
RedisUtils
posted @ 2021-01-18 15:49  踏步  阅读(104)  评论(2编辑  收藏  举报