jedis实战总结(含泛型工具类及分布式锁)

1、 什么是jedis?

Redis不仅是使用命令来操作,现在基本上主流的语言都有客户端支持,比如java、C、C#、C++、php、Node.js、Go等。在官方网站里列一些Java的客户端,有Jedis、Redisson、Jredis、JDBC-Redis、等其中官方推荐使用Jedis和Redisson。 在企业中用的最多的就是Jedis,下面我们就重点学习下Jedis。
Jedis同样也是托管在github上,地址:https://github.com/xetorthio/jedis
参考文档:http://xetorthio.github.io/jedis/

2、 工程搭建测试

Maven 依赖添加:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
    <type>jar</type>
    <scope>compile</scope>
</dependency>

测试:

jedis连接池连接redis服务器

Spring整合jedisPool

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

    <!-- 连接池配置 -->
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <!-- 最大连接数 -->
        <property name="maxTotal" value="30" />
        <!-- 最大空闲连接数 -->
        <property name="maxIdle" value="10" />
        <!-- 每次释放连接的最大数目 -->
        <property name="numTestsPerEvictionRun" value="1024" />
        <!-- 释放连接的扫描间隔(毫秒) -->
        <property name="timeBetweenEvictionRunsMillis" value="30000" />
        <!-- 连接最小空闲时间 -->
        <property name="minEvictableIdleTimeMillis" value="1800000" />
        <!-- 连接空闲多久后释放, 当空闲时间>该值 且 空闲连接>最大空闲连接数 时直接释放 -->
        <property name="softMinEvictableIdleTimeMillis" value="10000" />
        <!-- 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1 -->
        <property name="maxWaitMillis" value="1500" />
        <!-- 在空闲时检查有效性, 默认false -->
        <property name="testWhileIdle" value="true" />
        <!-- 连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true -->
        <property name="blockWhenExhausted" value="false" />
    </bean>

    <!-- redis单机 通过连接池 -->
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool"
        destroy-method="close">
        <constructor-arg name="poolConfig" ref="jedisPoolConfig" />
        <constructor-arg name="host" value="192.168.242.130" />
        <constructor-arg name="port" value="6379" />
    </bean>
</beans>

测试代码

@Test
    public void testJedisPool() {
        JedisPool pool = (JedisPool) applicationContext.getBean("jedisPool");
        Jedis jedis = null;
        try {
            jedis = pool.getResource();

            jedis.set("name", "lisi");
            String name = jedis.get("name");
            System.out.println(name);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            if (jedis != null) {
                // 关闭连接
                jedis.close();
            }
        }
    }

3、Redis数据类型

String

赋值:语法:SET key value
取值:语法:GET key
取值并赋值:GETSET key value
设置/获取多个键值:MSET key value [key value …]
MGET key [key …]
删除:DEL key**重点内容**

数值增减
递增数字:INCR key
增加指定的整数:INCRBY key increment   // incrby num 2
递减数值:DECR key
减少指定的整数:DECRBY key decrement

其他命令
向尾部追加值:APPEND key value  //(APPEND的作用是向键值的末尾追加value。如果键不存在则将该键的值设置为value,即相当于 SET key value。返回值是追加后字符串的总长度。)
获取字符串长度:STRLEN key

Hash 散列类型

1)  使用string的问题
假设有User对象以JSON序列化的形式存储到Redis中,User对象有id,username、password、age、name等属性,存储的过程如下: 保存、更新: 
User对象 –> json(string) --> redis 
如果在业务上只是更新age属性,其他的属性并不做更新我应该怎么做呢? 如果仍然采用上边的方法在传输、处理时会造成资源浪费,下边讲的hash可以很好的解决这个问题。
2)  redis hash介绍
hash叫散列类型,它提供了字段和字段值的映射。字段值只能是字符串类型,不支持散列类型、集合类型等其它类型。如下:
![这里写图片描述](https://img-blog.csdn.net/2018071418131098?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzE2NzUzMzQx/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
3)  使用:
赋值
HSET key field value  // HSET命令不区分插入和更新操作,当执行插入操作时HSET命令返回1,当执行更新操作时返回0。例子:hset user username zhangsan
一次可以设置多个字段值:HMSET key field value [field value ...] 
当字段不存在时赋值 :HSETNX key field value  // hsetnx user age 30 (存在时不会更新)

取值
一次只能获取一个字段值:HGET key field
一次可以获取多个字段值:HMGET key field [field ...]
获取所有字段值:HGETALL key

删除字段
删除一个或多个字段:HDEL key field [field ...]
增加数字:HINCRBY key field increment  // hincrby user age 2
判断字段是否存在:HEXISTS key field  // hexists user age 
只获取字段名或字段值:HKEYS key 、 HVALS key
获取字段数量:HLEN key

List

Redis的list是采用来链表来存储的,所以对于redis的list数据类型的操作,是操作list的两端数据来操作的。
添加:
向列表左边增加元素:LPUSH key value [value ...]  // lpush list:1 1 2 3
向列表右边增加元素:RPUSH key value [value ...]

设置指定索引的元素值:LSET key index value  //(会覆盖掉原先的值)

向列表中插入元素:LINSERT key BEFORE|AFTER pivot value     // linsert list after 3 4 

将元素从一个列表转移到另一个列表中: RPOPLPUSH source destination
// rpoplpush list:1 newlist

查看:
LRANGE命令是列表类型最常用的命令之一,获取列表中的某一片段,将返回start、stop之间的所有元素(包含两端的元素),索引从0开始。索引可以是负数,如:“-1”代表最后边的一个元素。
LRANGE key start stop  // lrange list:1 0 2
从列表两端弹出元素:LPOP key  、  RPOP key
获取列表中元素的个数: LLEN key  // llen list:1

获得指定索引的元素值:LINDEX key index


删除
删除列表中指定的值:LREM key count value // LREM命令会删除列表中前count个值为value的元素,返回实际删除的元素个数。根据count值的不同,该命令的执行方式会有所不同: 当count>0时, LREM会从列表左边开始删除。 当count<0时, LREM会从列表后边开始删除。 当count=0时, LREM删除所有值为value的元素。 

只保留列表指定片段:LTRIM key start stop

Set

添加: 
SADD key  member [member ...]  、 SREM key member [member ...]

获得
集合中的所有元素 :smembers set
判断元素是否在集合中:SISMEMBER key member
获得集合中元素的个数:SCARD key
从集合中弹出一个元素:SPOP key //随机
运算命令
差集:SDIFF key [key ...]   //可以多个集合求差集
交集:SINTER key [key ...] 
并集:SUNION key [key ...]

Sortedset

又叫zset。Sortedset是有序集合,可排序的,且是唯一。Sortedset和set的不同之处,是会给set中的元素添加一个分数,然后通过这个分数进行排序。
向有序集合中加入一个元素和该元素的分数:ZADD key score member [score member ...]
增加某个元素的分数:ZINCRBY  key increment member


获取元素的分数:zscore scoreboard lisi 
获得排名在某个范围的元素列表:ZRANGE key start stop [WITHSCORES]   
按照元素分数从大到小的顺序返回索引:ZREVRANGE key start stop [WITHSCORES] 
获取元素的排名:ZRANK key member  //从小到大
获取元素的排名:ZREVRANK key member  //从大到小
获得指定分数范围的元素:ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]
获得集合中元素的数量:ZCARD key
获得指定分数范围内的元素个数:ZCOUNT key min max


删除元素:ZREM key member [member ...]
按照排名范围删除元素:ZREMRANGEBYRANK key start stop
按照分数范围删除元素:ZREMRANGEBYSCORE key min max //zrange scoreboard 0 2

4、常用命令:

keys
返回满足给定pattern 的所有key
// keys mylist*
Exists
确认一个key 是否存在
Del
删除一个key
Rename
重命名key // rename key key_new
Type
返回值的类型
设置key的生存时间
Redis在实际使用过程中更多的用作缓存,然而缓存的数据一般都是需要设置生存时间的,即:到期后数据销毁。
EXPIRE key seconds 设置key的生存时间(单位:秒)key在多少秒后会自动删除
TTL key 查看key生于的生存时间
PERSIST key 清除生存时间
PEXPIRE key milliseconds 生存时间设置单位为:毫秒

5、jedis实用工具类

网上有个jedis工具比如:
https://blog.csdn.net/pengyu432/article/details/73467118
,但是我使用的时候总会出错。原因是它把List数据数据转换成二进制数组去存储,但是转换又经常出错。
List<Object>
还会存在如下两个问题:
1、当并发从redis没有取得数据,会去并发写list导致list里面的数据大量重复。
2、list对象存储不是泛型,导致存和取都得自己去转型,很麻烦。

如下是我的工具类。我没用到set及Sortedset因此没写。但都是一样的。自己需要加上就行。
使用分布式锁+双重检测 保证list数据不重复。具体看setList()、setObjectList()函数。
支持泛型,让数据存取变得方便很多。
使用com.fasterxml.jackson包实现将对象转换成Json字符串存储。

import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xskk8.common.config.Global;
import com.xskk8.common.utils.JsonUtils;
import com.xskk8.common.utils.SpringContextHolder;
import com.xskk8.common.utils.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;

public class MyJedisUtils {

    private static Logger logger = LoggerFactory.getLogger(MyJedisUtils.class);

    private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class);

    public static final String KEY_PREFIX = Global.getConfig("redis.keyPrefix");




    /**
     * 获取字符串
     * @param key 键
     * @return 值
     */
    public static Long incr(String key) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        Long value = 0L;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis!=null && jedis.exists(key)) {
                value = jedis.incr(key);
                logger.debug(key+" 加1结果:"+value);
            }
        } catch (Exception e) {
            logger.warn("获取缓存失败 :get {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取字符串
     * @param key 键
     * @return 值
     */
    public static String get(String key) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        String value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis!=null && jedis.exists(key)) {
                value = jedis.get(key);
                value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
            }
        } catch (Exception e) {
            logger.warn("获取缓存失败 :get {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取 对象 缓存
     * @param key 键
     * @return 值
     */
    public static <T> T getObject(String key,Class<T> beanType) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        T value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis!=null && jedis.exists(key)) {
                value = JsonUtils.jsonToPojo(jedis.get(key), beanType);
            }
        } catch (Exception e) {
            logger.warn("获取对象 缓存失败:getObject {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }


    /**
     * 设置字符串缓存
     * @param key 键
     * @param value 值 
     * @param cacheSeconds 超时时间,0为不超时   秒
     * @return
     */
    public static String set(String key, String value, int cacheSeconds) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        String result = null;
        Jedis jedis = null;
        if(StringUtils.isBlank(value)){
            return "";
        }
        try {
            jedis = getResource();
            result = jedis.set(key, value);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
            logger.warn("缓存字符串失败 : set {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置缓存过期时间
     * @param key 键
     * @param cacheSeconds 超时时间,0为不超时   秒
     * @return
     */
    public static String setExpire(String key, int cacheSeconds) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
            logger.warn("设置缓存过期时间失败 : set {} = {}", key, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }


    /**
     * 设置 对象 缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static <T> String setObject(String key, T value, int cacheSeconds) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        String result = null;
        Jedis jedis = null;
        if(value==null){
            return "";
        }
        try {
            jedis = getResource();
            String objectToJson = JsonUtils.objectToJson(value);
            logger.debug(objectToJson);
            result = jedis.set(key, objectToJson);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
            logger.warn("缓存对象失败 : setObject {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }


    /**
     * 获取  List字符串 缓存
     * @param key 键
     * @return 值
     */
    public static List<String> getList(String key) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        List<String> value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                value = jedis.lrange(key, 0, -1);
            }
        } catch (Exception e) {
            logger.warn("获取list字符串缓存失败 :getList {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取 List对象 缓存
     * @param key 键
     * @return 值
     */
    public static <T>List<T> getObjectList(String key , Class<T> beanType) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        List<T> value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                List<String> list = jedis.lrange(key, 0, -1);
                value = Lists.newArrayList();
                for (String s : list){
                    value.add(JsonUtils.jsonToPojo(s,beanType));
                }
            }
        } catch (Exception e) {
            logger.warn("获取list对象缓存失败:getObjectList {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 设置List字符串 缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static long setList(String key, List<String> value, int cacheSeconds) {
        if(StringUtils.isBlank(key) || value==null){
            return 0;
        }
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            if(jedis.setnx(LOCK+key,key)==1) {
                try {
                    if (jedis.exists(key)) {
                        return 0;
                    }

                    for(String s:value){                
                        result += jedis.rpush(key,s);
                    }
                    if (cacheSeconds != 0) {
                        jedis.expire(key, cacheSeconds);
                    }
                }catch (Exception e) {
                    logger.warn("设置List字符串 缓存失败:setList {} = {}", key, value, e);
                }finally {
                    jedis.del(LOCK+key);
                }
            }
        } catch (Exception e) {
            logger.warn("设置List字符串 缓存失败:setList {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }


    public static String LOCK="lock:";

    /**
     * 设置List对象缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static <T> long setObjectList(String key, List<T> value, int cacheSeconds) {
        if(StringUtils.isBlank(key) || value==null){
            return 0;
        }
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            //为了防止多线程并发写导致数据重复的情况。需要用分布式锁
            if(jedis.setnx(LOCK+key,key)==1) {
                try {
                    if (jedis.exists(key)) {
                        return 0;
                    }
                    for (T o : value){
                        String objectToJson = JsonUtils.objectToJson(o);
                        logger.debug(objectToJson);
                        jedis.rpush(key,objectToJson );
                        result++;
                    }
                    if (cacheSeconds != 0) {
                        jedis.expire(key, cacheSeconds);
                    }
                }catch (Exception e) {
                    logger.warn("设置List字符串 缓存失败:setList {} = {}", key, value, e);
                } finally {
                    jedis.del(LOCK+key);
                }
            }

        } catch (Exception e) {
            logger.warn("设置List对象缓存失败:setObjectList {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }


    /**
     * 删除缓存
     * @param key 
     * @return
     */
    public static void delet(String key) {
        if(StringUtils.isBlank(key)){
            return;
        }
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
        } catch (Exception e) {
            logger.warn("删除缓存失败:delet {}", key, e);
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 向 List字符串 缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long listAdd(String key, String... value) {
        if(StringUtils.isBlank(key) || value==null){
            return 0;
        }

        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.rpush(key, value);
        } catch (Exception e) {
            logger.warn("向 List字符串 缓存中添加值 失败:listAdd {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 缓存是否存在
     * @param key 键
     * @return
     */
    public static boolean exists(String key) {
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.exists(key);
            logger.debug("exists {}", key);
        } catch (Exception e) {
            logger.warn("exists {}", key, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向List对象缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static <T> long listObjectAdd(String key, T... value) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            for (T o : value){
                result+=jedis.rpush(key,JsonUtils.objectToJson(o));
            }
        } catch (Exception e) {
            logger.warn("向List对象缓存中添加值失败:listObjectAdd {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }


    /**
     * 获取String Map缓存
     * @param key 键
     * @return 值
     */
    public static Map<String, String> getMap(String key ) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        Map<String, String> value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                value = jedis.hgetAll(key);
            }
        } catch (Exception e) {
            logger.warn("获取String Map缓存失败:getMap {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取 对象  Map 所有缓存
     * @param key 键
     * @return 值
     */
    public static <T> Map<String, T> getObjectMap(String key,Class<T> beanType) {
        if(StringUtils.isBlank(key)){
            return null;
        }
        Map<String, T> value = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                Map<String, String> map = jedis.hgetAll(key);
                if(map!=null){
                    for (Map.Entry<String, String> e : map.entrySet()){
                        value.put(e.getKey(),JsonUtils.jsonToPojo(e.getValue(), beanType));
                    }
                }
            }
        } catch (Exception e) {
            logger.warn("获取 对象 Map缓存 失败"
                    + ":getObjectMap {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取String  Map中某个属性 都返回   缓存
     * @param key 键
     * @return 值
     */
    public static String getMap(String key,String field) {
        if(StringUtils.isBlank(key)|| StringUtils.isBlank(field)){
            return null;
        }
        String value="";
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {

                value= jedis.hget(key, field);
            }
        } catch (Exception e) {
            logger.warn("获取 对象 Map中某个属性  缓存" + ":getMap {} = {}", key,value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取List<对象>  Map中某个属性 都返回   缓存
     * @param key 键
     * @return 值
     */
    public static <T> List<T> getMapList(String key,String field,Class<T> beanType) {
        if(StringUtils.isBlank(key)|| StringUtils.isBlank(field)){
            return null;
        }
        List<T> value=null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                String s= jedis.hget(key, field);
                value=JsonUtils.jsonToList(s, beanType);
            }
        } catch (Exception e) {
            logger.warn("获取 对象 Map中某个属性  缓存" + ":getObjectMap {} = {}", key,value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 获取List<对象>  Map中某个属性 都返回   缓存
     * @param key 键
     * @return 值
     */
    public static <T> T getMapObject(String key,String field,Class<T> beanType) {
        if(StringUtils.isBlank(key)|| StringUtils.isBlank(field)){
            return null;
        }
        T value=null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                String hget = jedis.hget(key, field);
                logger.debug(hget);
                value=JsonUtils.jsonToPojo(hget, beanType);
            }
        } catch (Exception e) {
            logger.warn("获取 对象 Map中某个属性  缓存" + ":getObjectMap {} = {}", key,value, e);
        } finally {
            returnResource(jedis);
        }
        return value;
    }

    /**
     * 设置Map缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static String setMap(String key, Map<String, String> value, int cacheSeconds) {
        if(StringUtils.isBlank(key)|| value==null){
            return "";
        }
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            result = jedis.hmset(key, value);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
            logger.debug("setMap {} = {}", key, value);
        } catch (Exception e) {
            logger.warn("setMap {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 设置 对象Map 缓存
     * @param key 键
     * @param value 值
     * @param cacheSeconds 超时时间,0为不超时
     * @return
     */
    public static <T> String setObjectMap(String key, Map<String, T> value, int cacheSeconds) {
        if(StringUtils.isBlank(key)|| value==null){
            return "";
        }
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            if (jedis.exists(key)) {
                jedis.del(key);
            }
            Map<String, String> map = Maps.newHashMap();
            for (Map.Entry<String, T> e : value.entrySet()){
                map.put(e.getKey(), JsonUtils.objectToJson(e.getValue()));
            }
            result = jedis.hmset(key, map);
            if (cacheSeconds != 0) {
                jedis.expire(key, cacheSeconds);
            }
        } catch (Exception e) {
            logger.warn(" 设置 对象Map 缓存  失败:setObjectMap {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向Map缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static String mapPut(String key, Map<String, String> value) {
        if(StringUtils.isBlank(key)|| value==null){
            return "";
        }
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hmset(key, value);
            logger.debug("mapPut {} = {}", key, value);
        } catch (Exception e) {
            logger.warn("mapPut {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 向Map缓存中添加值
     * @param key 键
     * @param value 值
     * @return
     */
    public static <T> String mapObjectPut(String key, Map<String, T> value) {
        if(StringUtils.isBlank(key)|| value==null){
            return "";
        }
        String result = null;
        Jedis jedis = null;
        try {
            jedis = getResource();
            Map<String, String> map = Maps.newHashMap();
            for (Map.Entry<String, T> e : value.entrySet()){
                map.put(e.getKey(), JsonUtils.objectToJson(e.getValue()));
            }
            result = jedis.hmset(key, map);
        } catch (Exception e) {
            logger.warn("mapObjectPut {} = {}", key, value, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 移除Map缓存中的值
     * @param key 键
     * @param value 值
     * @return
     */
    public static long mapRemove(String key, String mapKey) {
        long result = 0;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hdel(key, mapKey);
            logger.debug("mapRemove {}  {}", key, mapKey);
        } catch (Exception e) {
            logger.warn("mapRemove {}  {}", key, mapKey, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 判断redis是否正常
     * @param key 键
     * @param value 值
     * @return
     */
    public static String testRedisAlive() {
        String result = "";
        Jedis jedis = null;
        try {
            jedis = getResource();
            result=jedis.ping();
        } catch (Exception e) {
            logger.warn(e.getMessage());
        } finally {
            returnResource(jedis);
        }
        return result;
    }


    /**
     * 判断Map缓存中的Key是否存在
     * @param key 键
     * @param value 值
     * @return
     */
    public static boolean mapExists(String key, String mapKey) {
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getResource();
            result = jedis.hexists(key, mapKey);
            logger.debug("mapExists {}  {}", key, mapKey);
        } catch (Exception e) {
            logger.warn("mapExists {}  {}", key, mapKey, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }




    /**
     * 获取资源
     * @return
     * @throws JedisException
     */
    public static Jedis getResource() throws JedisException {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
//          logger.debug("getResource.", jedis);
        } catch (JedisException e) {
            logger.warn("getResource.", e);
            returnBrokenResource(jedis);
            throw e;
        }
        return jedis;
    }

    /**
     * 归还资源
     * @param jedis
     * @param isBroken
     */
    public static void returnBrokenResource(Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnBrokenResource(jedis);
        }
    }
    /**
     * 释放资源
     * @param jedis
     * @param isBroken
     */
    public static void returnResource(Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }

}

猜你喜欢

转载自blog.csdn.net/qq_16753341/article/details/81046012