码迷,mamicode.com
首页 > 其他好文 > 详细

单机版 RedisUtils({基本操作封装工具类})【三】

时间:2019-01-12 18:03:38      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:file   apache   @param   util   final   cat   set   ase   ash   

<!--集成的RedisJAR-->
<!--引入jedis需的jar包-->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
<!--Spring整合jedis的依赖-->
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.7.1.RELEASE</version>
</dependency>
package com.dsj.gdbd.utils.jedis;

import com.dsj.gdbd.utils.serialize.SerializingUtil;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * s
 *
 * @描述: Redis缓存工具类.
 * @版本: V1.0
 */
public class RedisUtils {

    private static Logger logger = Logger.getLogger(RedisUtils.class);

    /**
     * 默认缓存时间
     */
    private static final int DEFAULT_CACHE_SECONDS = 60 * 60 * 1;// 单位秒 设置成一个钟

    /**
     * 连接池
     **/
    private static JedisSentinelPool jedisSentinelPool;

    /**
     * 释放redis资源
     *
     * @param jedis
     */
    private static void releaseResource(Jedis jedis) {
        if (jedis != null) {
            jedisSentinelPool.returnResource(jedis);
        }
    }

    /**
     * 删除Redis中的所有key
     *
     * @throws Exception
     */
    public static void flushAll() {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            jedis.flushAll();
        } catch (Exception e) {
            logger.error("Cache清空失败:" + e);
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 保存一个对象到Redis中(缓存过期时间:使用此工具类中的默认时间) . <br/>
     *
     * @param key    键 . <br/>
     * @param object 缓存对象 . <br/>
     * @return true or false . <br/>
     * @throws Exception
     */
    public static Boolean save(Object key, Object object) {
        return save(key, object, DEFAULT_CACHE_SECONDS);
    }

    /**
     * 保存一个对象到redis中并指定过期时间
     *
     * @param key     键 . <br/>
     * @param object  缓存对象 . <br/>
     * @param seconds 过期时间(单位为秒).<br/>
     * @return true or false .
     */
    public static Boolean save(Object key, Object object, int seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            jedis.set(SerializingUtil.serialize(key), SerializingUtil.serialize(object));
            jedis.expire(SerializingUtil.serialize(key), seconds);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("Cache保存失败:" + e);
            return false;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 根据缓存键获取Redis缓存中的值.<br/>
     *
     * @param key 键.<br/>
     * @return Object .<br/>
     * @throws Exception
     */
    public static Object get(Object key) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            byte[] obj = jedis.get(SerializingUtil.serialize(key));
            return obj == null ? null : SerializingUtil.deserialize(obj);
        } catch (Exception e) {
            logger.error("Cache获取失败:" + e);
            return null;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 根据缓存键清除Redis缓存中的值.<br/>
     *
     * @param key
     * @return
     * @throws Exception
     */
    public static Boolean del(Object key) {
        Jedis jedis = null;
        try {
            // System.out.println(key);
            jedis = jedisSentinelPool.getResource();
            jedis.del(SerializingUtil.serialize(key));
            return true;
        } catch (Exception e) {
            logger.error("Cache删除失败:" + e);
            return false;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 根据缓存键清除Redis缓存中的值.<br/>
     *
     * @param keys
     * @return
     * @throws Exception
     */
    public static Boolean del(Object... keys) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            jedis.del(SerializingUtil.serialize(keys));
            return true;
        } catch (Exception e) {
            logger.error("Cache删除失败:" + e);
            return false;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * @param key
     * @param seconds 超时时间(单位为秒)
     * @return
     */
    public static Boolean expire(Object key, int seconds) {

        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            jedis.expire(SerializingUtil.serialize(key), seconds);
            return true;
        } catch (Exception e) {
            logger.error("Cache设置超时时间失败:" + e);
            return false;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 添加一个内容到指定key的hash中
     *
     * @param key
     * @param field
     * @param value
     * @return
     */
    public static Boolean addHash(String key, Object field, Object value) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            jedis.hset(SerializingUtil.serialize(key), SerializingUtil.serialize(field), SerializingUtil.serialize(value));
            return true;
        } catch (Exception e) {
            logger.error("Cache保存失败:" + e);
            return false;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 从指定hash中拿一个对象
     *
     * @param key
     * @param field
     * @return
     */
    public static Object getHash(Object key, Object field) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            byte[] obj = jedis.hget(SerializingUtil.serialize(key), SerializingUtil.serialize(field));
            return SerializingUtil.deserialize(obj);
        } catch (Exception e) {
            logger.error("Cache读取失败:" + e);
            return null;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 从hash中删除指定filed的值
     *
     * @param key
     * @param field
     * @return
     */
    public static Boolean delHash(Object key, Object field) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            long result = jedis.hdel(SerializingUtil.serialize(key), SerializingUtil.serialize(field));
            return result == 1 ? true : false;
        } catch (Exception e) {
            logger.error("Cache删除失败:" + e);
            return null;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 拿到缓存中所有符合pattern的key
     *
     * @param pattern
     * @return
     */
    public static Set<byte[]> keys(String pattern) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            Set<byte[]> allKey = jedis.keys(("*" + pattern + "*").getBytes());
            return allKey;
        } catch (Exception e) {
            logger.error("Cache获取失败:" + e);
            return new HashSet<byte[]>();
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 获得hash中的所有key value
     *
     * @param key
     * @return
     */
    public static Map<byte[], byte[]> getAllHash(Object key) {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            Map<byte[], byte[]> map = jedis.hgetAll(SerializingUtil.serialize(key));
            return map;
        } catch (Exception e) {
            logger.error("Cache获取失败:" + e);
            return null;
        } finally {
            releaseResource(jedis);
        }
    }

    /**
     * 判断一个key是否存在
     *
     * @param key
     * @return
     */
    public static Boolean exists(Object key) {
        Jedis jedis = null;
        Boolean result = false;
        try {
            jedis = jedisSentinelPool.getResource();
            result = jedis.exists(SerializingUtil.serialize(key));
            return result;
        } catch (Exception e) {
            logger.error("Cache获取失败:" + e);
            return false;
        } finally {
            releaseResource(jedis);
        }
    }
    public void setJedisSentinelPool(JedisSentinelPool jedisSentinelPool) {
        RedisUtils.jedisSentinelPool = jedisSentinelPool;
    }

    public static JedisSentinelPool getJedisSentinelPool() {
        return jedisSentinelPool;
    }
}

 

单机版 RedisUtils({基本操作封装工具类})【三】

标签:file   apache   @param   util   final   cat   set   ase   ash   

原文地址:https://www.cnblogs.com/mlq2017/p/10260162.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!