redis学习笔记

redis的依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
</dependency>
redis和spring的整合——spring-cache.xml
<!--  redis配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="100"/><!-- 最大闲置 -->
        <property name="minIdle" value="10"/><!-- 最小闲置 -->
        <property name="testOnBorrow" value="true"/><!-- 可以获取 -->
<!--        <property name="testOnReturn" value="true"/>-->
    </bean>
<!-- redis 配置,也可以把配置挪到properties配置文件中,再读取 -->
    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg index="0" ref="jedisPoolConfig" />
        <!-- 端口,默认6379 -->
        <constructor-arg index="2" value="6379"  name="port" type="int"/>
        <constructor-arg index="3" value="5000"  name="timeout" type="int"/>
        <constructor-arg index="1" value="127.0.0.1" name="host" type="java.lang.String"/>
        <!-- 如果你需要配置密码,请打开这里。  -->
            <!--<constructor-arg index="4" value="xielong" name="password" type="java.lang.String"/>-->

    </bean>

redis缓存的公共类

<!-- redis 的缓存 -->
    <bean id="jedisManager" class="com.jedis.cache.JedisManager">
        <property name="jedisPool" ref="jedisPool"/>
    </bean>

1.JedisManager

public class JedisManager {

    private JedisPool jedisPool;
    public Jedis getJedis() {
        Jedis jedis = null;
        try {
            jedis = getJedisPool().getResource();
        } catch (JedisConnectionException e) {
            String message = StringUtils.trim(e.getMessage());
            if("Could not get a resource from the pool".equalsIgnoreCase(message)){
                System.out.println("++++++++++请检查你的redis服务++++++++");

                System.exit(0);//停止项目
            }
            throw new JedisConnectionException(e);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return jedis;
    }

    public void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
        /**
         * @deprecated starting from Jedis 3.0 this method will not be exposed.
         * Resource cleanup should be done using @see {@link redis.clients.jedis.Jedis#close()}
        if (isBroken){
            getJedisPool().returnBrokenResource(jedis);
        }else{
            getJedisPool().returnResource(jedis);
        }
        */
        jedis.close();
    }

    public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        byte[] result = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            result = jedis.get(key);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
        return result;
    }

    public void deleteByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            Long result = jedis.del(key);
            LoggerUtils.fmtDebug(getClass(), "删除Session结果:%s" , result);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }

    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, int expireTime)
            throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.set(key, value);
            if (expireTime > 0)
                jedis.expire(key, expireTime);
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
    }

    public JedisPool getJedisPool() {
        return jedisPool;
    }

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    /**
     * 获取所有Session
     * @param dbIndex
     * @param redisShiroSession
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public Collection<Session> AllSession(int dbIndex, String redisShiroSession) throws Exception {
        Jedis jedis = null;
        boolean isBroken = false;
        Set<Session> sessions = new HashSet<Session>();
        try {
            jedis = getJedis();
            jedis.select(dbIndex);

            Set<byte[]> byteKeys = jedis.keys((JedisShiroSessionRepository.REDIS_SHIRO_ALL).getBytes());  
            if (byteKeys != null && byteKeys.size() > 0) {  
                for (byte[] bs : byteKeys) {  
                    Session obj = SerializeUtil.deserialize(jedis.get(bs),  
                             Session.class);  
                     if(obj instanceof Session){
                         sessions.add(obj);  
                     }
                }  
            }  
        } catch (Exception e) {
            isBroken = true;
            throw e;
        } finally {
            returnResource(jedis, isBroken);
        }
        return sessions;
    }
}

获取bean的工具类

public class SpringContextUtil implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    // 实现
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        try {
            return applicationContext.getBean(name);
        } catch (Exception e) {
            throw new RuntimeException("获取的Bean不存在!");
        }
    }

    public static <T> T getBean(String name, Class<T> requiredType)
            throws BeansException {
        return applicationContext.getBean(name, requiredType);
    }

    public static boolean containsBean(String name) {
        return applicationContext.containsBean(name);
    }

    public static boolean isSingleton(String name)
            throws NoSuchBeanDefinitionException {
        return applicationContext.isSingleton(name);
    }

    public static Class<? extends Object> getType(String name)
            throws NoSuchBeanDefinitionException {
        return applicationContext.getType(name);
    }

    public static String[] getAliases(String name)
            throws NoSuchBeanDefinitionException {
        return applicationContext.getAliases(name);
    }


}

redis缓存操作类

public class VCache {

    final static JedisManager J = SpringContextUtil.getBean("jedisManager", JedisManager.class);
    private VCache() {}

    /**
     * 简单的Get
     * @param <T>
     * @param key
     * @param requiredType
     * @return
     */
    public static <T> T get(String key , Class<T>...requiredType){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] skey = SerializeUtil.serialize(key);
            return SerializeUtil.deserialize(jds.get(skey),requiredType);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 简单的set
     * @param key
     * @param value
     */
    public static void set(Object key ,Object value){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] skey = SerializeUtil.serialize(key);
            byte[] svalue = SerializeUtil.serialize(value);
            jds.set(skey, svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
    }
    /**
     * 过期时间的
     * @param key
     * @param value
     * @param timer (秒)
     */
    public static void setex(Object key, Object value, int timer) {
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] skey = SerializeUtil.serialize(key);
            byte[] svalue = SerializeUtil.serialize(value);
            jds.setex(skey, timer, svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }

    }
    /**
     * 
     * @param <T>
     * @param mapkey map
     * @param key    map里的key
     * @param requiredType value的泛型类型
     * @return
     */
    public static <T> T getVByMap(String mapkey,String key , Class<T> requiredType){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] mkey = SerializeUtil.serialize(mapkey);
            byte[] skey = SerializeUtil.serialize(key);
            List<byte[]> result = jds.hmget(mkey, skey);
            if(null != result && result.size() > 0 ){
                byte[] x = result.get(0);
                T resultObj = SerializeUtil.deserialize(x, requiredType);
                return resultObj;
            }

        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 
     * @param mapkey map
     * @param key    map里的key
     * @param value   map里的value
     */
    public static void setVByMap(String mapkey,String key ,Object value){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] mkey = SerializeUtil.serialize(mapkey);
            byte[] skey = SerializeUtil.serialize(key);
            byte[] svalue = SerializeUtil.serialize(value);
            jds.hset(mkey, skey,svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }

    }
    /**
     * 删除Map里的值
     * @param mapKey
     * @param dkey
     * @return
     */
    public static Object delByMapKey(String mapKey ,String...dkey){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[][] dx = new byte[dkey.length][];
            for (int i = 0; i < dkey.length; i++) {
                dx[i] = SerializeUtil.serialize(dkey[i]);
            }
            byte[] mkey = SerializeUtil.serialize(mapKey);
            Long result = jds.hdel(mkey, dx);
            return result;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return new Long(0);
    }

    /**
     * 往redis里取set整个集合
     * 
     * @param <T>
     * @param setKey
     * @param start
     * @param end
     * @param requiredType
     * @return
     */
    public static <T> Set<T> getVByList(String setKey,Class<T> requiredType){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] lkey = SerializeUtil.serialize(setKey);
            Set<T> set = new TreeSet<T>();
            Set<byte[]> xx = jds.smembers(lkey);
            for (byte[] bs : xx) {
                T t = SerializeUtil.deserialize(bs, requiredType);
                set.add(t);
            }
            return set;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 获取Set长度
     * @param setKey
     * @return
     */
    public static Long getLenBySet(String setKey){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            Long result = jds.scard(setKey);
            return result;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 删除Set
     * @param dkey
     * @return
     */
    public static Long delSetByKey(String key,String...dkey){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            Long result = 0L;
            if(null == dkey){
                result = jds.srem(key);
            }else{
                result = jds.del(key);
            }
            return result;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return new Long(0);
    }
    /**
     * 随机 Set 中的一个值
     * @param key
     * @return
     */
    public static String srandmember(String key){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            String result = jds.srandmember(key);
            return result;
        } catch (Exception e){ 
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 往redis里存Set
     * @param setKey
     * @param value
     */
    public static void setVBySet(String setKey,String value){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            jds.sadd(setKey, value);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
    }
    /**
     * 取set 
     * @param key
     * @return
     */
    public static Set<String> getSetByKey(String key){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            Set<String> result = jds.smembers(key);
            return result;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;

    }


    /**
     * 往redis里存List
     * @param listKey
     * @param value
     */
    public static void setVByList(String listKey,Object value){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] lkey = SerializeUtil.serialize(listKey);
            byte[] svalue = SerializeUtil.serialize(value);
            jds.rpush(lkey, svalue);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
    }
    /**
     * 往redis里取list
     * 
     * @param <T>
     * @param listKey
     * @param start
     * @param end
     * @param requiredType
     * @return
     */
    public static <T> List<T> getVByList(String listKey,int start,int end,Class<T> requiredType){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] lkey = SerializeUtil.serialize(listKey);
            List<T> list = new ArrayList<T>();
            List<byte[]> xx = jds.lrange(lkey,start,end);
            for (byte[] bs : xx) {
                T t = SerializeUtil.deserialize(bs, requiredType);
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 获取list长度
     * @param listKey
     * @return
     */
    public static Long getLenByList(String listKey){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] lkey = SerializeUtil.serialize(listKey);
            Long result = jds.llen(lkey);
            return result;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return null;
    }
    /**
     * 删除
     * @param dkey
     * @return
     */
    public static Long delByKey(String...dkey){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[][] dx = new byte[dkey.length][];
            for (int i = 0; i < dkey.length; i++) {
                dx[i] = SerializeUtil.serialize(dkey[i]);
            }
            Long result = jds.del(dx);
            return result;
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return new Long(0);
    }
    /**
     * 判断是否存在
     * @param existskey
     * @return
     */
    public static boolean exists(String existskey){
        Jedis jds = null;
        boolean isBroken = false;
        try {
            jds = J.getJedis();
            jds.select(0);
            byte[] lkey = SerializeUtil.serialize(existskey);
            return jds.exists(lkey);
        } catch (Exception e) {
            isBroken = true;
            e.printStackTrace();
        } finally {
            returnResource(jds, isBroken);
        }
        return false;
    }
    /**
     * 释放
     * @param jedis
     * @param isBroken
     */
    public static void returnResource(Jedis jedis, boolean isBroken) {
        if (jedis == null)
            return;
//        if (isBroken)
//            J.getJedisPool().returnBrokenResource(jedis);
//        else
//          J.getJedisPool().returnResource(jedis);
//        版本问题
        jedis.close();
     }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值