redis缓存

来源:互联网 发布:男生用什么护肤品知乎 编辑:程序博客网 时间:2024/06/05 15:13
package com.xx.redis;import java.util.List;import java.util.ResourceBundle;import com.alibaba.fastjson.JSON;import redis.clients.jedis.Jedis;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPoolConfig;public class RedisClient {    public static JedisPool jedisPool; // 池化管理jedis链接池    static {        // 读取相关的配置:redis.properties        ResourceBundle resourceBundle = ResourceBundle.getBundle("redis");        int maxActive = Integer.parseInt(resourceBundle.getString("redis.pool.maxActive"));        int maxIdle = Integer.parseInt(resourceBundle.getString("redis.pool.maxIdle"));        int maxWait = Integer.parseInt(resourceBundle.getString("redis.pool.maxWait"));        String ip = resourceBundle.getString("redis.ip");        int port = Integer.parseInt(resourceBundle.getString("redis.port"));        JedisPoolConfig config = new JedisPoolConfig();        // 设置最大连接数        config.setMaxTotal(maxActive);        // 设置最大空闲数        config.setMaxIdle(maxIdle);        // 设置超时时间        config.setMaxWaitMillis(maxWait);        // 初始化连接池        jedisPool = new JedisPool(config, ip, port);    }    /**     * 向缓存中设置字符串内容     *      * @param key     *            key     * @param value     *            value     * @return     * @throws Exception     */    public static boolean set(String key, String value) {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            jedis.set(key, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            jedisPool.returnResource(jedis);        }    }    /**     * 向缓存中设置对象     *      * @param key     * @param value     * @return     */    public static boolean set(String key, Object value) {        Jedis jedis = null;        try {            String objectJson = JSON.toJSONString(value);            jedis = jedisPool.getResource();  // 从池中获取一个Jedis对象            jedis.set(key, objectJson);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            jedisPool.returnResource(jedis);//释放对象池        }    }    /**     * 删除缓存中得对象,根据key     *      * @param key     * @return     */    public static boolean del(String key) {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            jedis.del(key);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            jedisPool.returnResource(jedis);        }    }    /**     * 根据key 获取内容     *      * @param key     * @return     */    public static Object get(String key) {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            Object value = jedis.get(key);            return value;        } catch (Exception e) {            e.printStackTrace();            return false;        } finally {            jedisPool.returnResource(jedis);        }    }    /**     * 根据key 获取对象     *      * @param key     * @return     */    public static <T> T get1(String key, Class<T> clazz) {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            String value = jedis.get(key);            return JSON.parseObject(value, clazz);        } catch (Exception e) {            e.printStackTrace();            return null;        } finally {            jedisPool.returnResource(jedis);        }    }    /**     * 根据key 获取对象     *      * @param key     * @return     */    public static String getStr(String key) {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            return jedis.get(key);        } catch (Exception e) {            e.printStackTrace();            return null;        } finally {            jedisPool.returnResource(jedis);        }    }    /**     * 根据key 获取对象     *      * @param key     * @return     */    public static <T> List<T> getList(String key, Class<T> clazz) {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            String value = jedis.get(key);            return JSON.parseArray(value, clazz);        } catch (Exception e) {//          e.printStackTrace();            return null;        } finally {            try {                jedisPool.returnResource(jedis);            } catch (Exception e) {                System.out.println("");            }        }    }    public static void flushAll() {        Jedis jedis = null;        try {            jedis = jedisPool.getResource();            jedis.flushAll();        } catch (Exception e) {            e.printStackTrace();        } finally {            jedisPool.returnResource(jedis);        }    }}

redis.properties

redis.pool.maxActive=100redis.pool.maxIdle=20redis.pool.maxWait=3000redis.ip=localhostredis.port=6379
<dependency>    <groupId>net.sf.json-lib</groupId>    <artifactId>json-lib</artifactId>    <version>2.4</version>    <classifier>jdk15</classifier></dependency><dependency>    <groupId>redis.clients</groupId>    <artifactId>jedis</artifactId>    <version>2.6.2</version></dependency><dependency>    <groupId>com.alibaba</groupId>    <artifactId>fastjson</artifactId>    <version>1.2.12</version></dependency>

===================
另外一种实现:

package cache.redis;/** * @Description: RedisTemplate匿名内部类接口 * @author fanmintao * @date 2017年1月3日 */public interface Function<E, T> {    public T execute(E e);}
package cache.redis;import java.util.Map;import org.apache.log4j.Logger;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;import redis.clients.jedis.ShardedJedis;import redis.clients.jedis.ShardedJedisPool;import utils.FastJsonUtils;/** * @Description:redis使用的封装类 * @author fanmintao * @date 2017年1月3日 */@Componentpublic class RedisTemplate {    private static Logger log = Logger.getLogger(RedisTemplate.class);    // 有的工程需要,有的工程不需要。设置required=false,有就注入,没有就不注入。    @Autowired(required = false)    private ShardedJedisPool shardedJedisPool;    private <T> T execute(Function<ShardedJedis, T> function) {        ShardedJedis shardedJedis = null;        try {            // 从连接池中获取到jedis分片对象            shardedJedis = shardedJedisPool.getResource();            return function.execute(shardedJedis);        } catch (Exception e) {            e.printStackTrace();        } finally {            if (null != shardedJedis) {                // 关闭,检测连接是否有效,有效则放回到连接池中,无效则重置状态                shardedJedis.close();            }        }        return null;    }    /**     * 直接保存对象到redis中     *      * @param key     * @param obect     * @return     */    public String set(final String key, final Object object) {        return this.execute(new Function<ShardedJedis, String>() {            @Override            public String execute(ShardedJedis shardedJedis) {                String result=null;                try {                    result=shardedJedis.set(key, FastJsonUtils.obj2json(object));                } catch (Exception e) {                    log.error("保存对象到redis中发生异常",e);                }                return result;            }        });    }    /**     * 保存数据到redis中,生存时间单位是:秒     *      * @param key     * @param value     * @param seconds     * @return     */    public String set(final String key, final Object object, final Integer seconds) {        return this.execute(new Function<ShardedJedis, String>() {            @Override            public String execute(ShardedJedis shardedJedis) {                String result = set(key, object);                shardedJedis.expire(key, seconds);// 设置生存时间                return result;            }        });    }    /**     * 从redis中获取数据     *      * @param key     * @return     */    public String get(final String key) {        return this.execute(new Function<ShardedJedis, String>() {            @Override            public String execute(ShardedJedis shardedJedis) {                String result=null;                try {                    result=shardedJedis.get(key);                } catch (Exception e) {                    log.error("从redis中获取数据发生异常",e);                }                return result;            }        });    }    /**     * 从redis中直接获取缓存对象     *      * @param key     * @return     */    public <T> T get(String key, Class<T> clazz) {        String text = get(key);        T result = null;        try {            result = FastJsonUtils.json2obj(text, clazz);        } catch (Exception e) {            log.error("从redis中直接获取缓存对象发生错误",e);        }        return result;    }    public <T> Map<String, T> getMap(String key, Class<T> clazz) {        String jsonStr = get(key);        Map<String, T> result = null;        try {            result = FastJsonUtils.json2map(jsonStr, clazz);        } catch (Exception e) {            log.error("从redis中直接获取缓存对象发生错误",e);        }        return result;    }    /**     * 设置key生存时间,单位:秒     *      * @param key     * @param seconds     * @return     */    public Long expire(final String key, final Integer seconds) {        return this.execute(new Function<ShardedJedis, Long>() {            @Override            public Long execute(ShardedJedis shardedJedis) {                Long result=null;                try {                    result=shardedJedis.expire(key, seconds);                } catch (Exception e) {                    log.error("设置key生存时间发生错误",e);                }                return result;            }        });    }    /**     * 从redis中删除数据     *      * @param key     * @return     */    public Long del(final String key) {        return this.execute(new Function<ShardedJedis, Long>() {            @Override            public Long execute(ShardedJedis shardedJedis) {                Long result=null;                try {                    result=shardedJedis.del(key);                } catch (Exception e) {                    log.error("从redis中删除数据发生错误",e);                }                return result;            }        });    }    /**     * 判断key值是否存在     *      * @param key     * @return     */    public Boolean exists(final String key) {        return this.execute(new Function<ShardedJedis, Boolean>() {            @Override            public Boolean execute(ShardedJedis shardedJedis) {                Boolean result=false;                try {                    result=shardedJedis.exists(key);                } catch (Exception e) {                    log.error("判断key值是否存在发生错误",e);                }                return result;            }        });    }    /**     * 保存Hash数据到redis     *      * @param key field result     * @return     */    public Long hset(final String key, final String field, final Object object) {        return this.execute(new Function<ShardedJedis, Long>() {            public Long execute(ShardedJedis shardedJedis) {                Long result=null;                try {                    result=shardedJedis.hset(key, field, FastJsonUtils.obj2json(object));                } catch (Exception e) {                    log.error("保存Hash数据到redis发生错误",e);                }                return result;            }        });    }    /**     * 设置Hash的缓存过期时间     *      * @param key field result     * @return     */    public Long hset(final String key, final String field, final Object object,final Integer seconds) {        return this.execute(new Function<ShardedJedis, Long>() {            public Long execute(ShardedJedis shardedJedis) {                Long result=null;                try {                    result=hset(key, field, object);                    shardedJedis.expire(key, seconds);                } catch (Exception e) {                    log.error("设置Hash的缓存过期时间发生错误",e);                }                return result;            }        });    }    /**     * 从redis中获取Hash数据     *      * @param key      * @param field     * @return     */    public String hget(final String key, final String field) {        return this.execute(new Function<ShardedJedis, String>() {            @Override            public String execute(ShardedJedis shardedJedis) {                String result=null;                try {                    result=shardedJedis.hget(key, field);                } catch (Exception e) {                    log.error("从redis中获取Hash数据发生错误",e);                }                return result;            }        });    }    /**     * 从redis中删除Hash数据     *      * @param key      * @param field     * @return     */    public Long hdel(final String key, final String field) {        return this.execute(new Function<ShardedJedis, Long>() {            @Override            public Long execute(ShardedJedis shardedJedis) {                Long result=null;                try {                    result=shardedJedis.hdel(key, field);                } catch (Exception e) {                    log.error("从redis中删除Hash数据发生错误",e);                }                return result;            }        });    }    /**     * 从redis中获取Hash数据直接返回对象     *      * @param      * @param key      * @param field      * @param clazz     * @return     */    public <T> T hget(String key, String field, Class<T> clazz) {        String text = hget(key, field);        T result = null;        try {            result = FastJsonUtils.json2obj(text, clazz);        } catch (Exception e) {            log.error("从redis中获取Hash数据直接返回对象发生错误",e);        }        return result;    }    /**     * 判断key与field(hashKey)是否存在     *      * @param key      * @param field     * @return     */    public Boolean hexists(final String key,final String field) {        return this.execute(new Function<ShardedJedis, Boolean>() {            public Boolean execute(ShardedJedis shardedJedis) {                Boolean result=false;                try {                    result=shardedJedis.hexists(key, field);                } catch (Exception e) {                    log.error("判断key与field(hashKey)是否存在发生错误",e);                }                return result;            }        });    }}
package utils;import java.util.Date;  import java.util.List;  import java.util.Map;  import java.util.Map.Entry;  import com.alibaba.fastjson.JSON;  import com.alibaba.fastjson.JSONObject;  import com.alibaba.fastjson.TypeReference;  import com.alibaba.fastjson.serializer.SerializeConfig;  import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;  /**  * fastjson utils  *   * @author magic_yy  * @see https://github.com/alibaba/fastjson  * @see http://code.alibabatech.com/wiki/display/FastJSON  */  public class FastJsonUtils {    private static SerializeConfig mapping = new SerializeConfig();      static{          mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss"));      }      /**      * javaBean、list、map convert to json string      */      public static String obj2json(Object obj){  //      return JSON.toJSONString(obj,SerializerFeature.UseSingleQuotes);//使用单引号  //      return JSON.toJSONString(obj,true);//格式化数据,方便阅读          return JSON.toJSONString(obj,mapping);      }      /**      * json string convert to javaBean、map      */      public static <T> T json2obj(String jsonStr,Class<T> clazz){          return JSON.parseObject(jsonStr,clazz);      }      /**      * json array string convert to list with javaBean      */      public static <T> List<T> json2list(String jsonArrayStr,Class<T> clazz){          return JSON.parseArray(jsonArrayStr, clazz);      }      /**      * json string convert to map      */      public static <T> Map<String,Object> json2map(String jsonStr){          return json2obj(jsonStr, Map.class);      }      /**      * json string convert to map with javaBean      */      public static <T> Map<String,T> json2map(String jsonStr,Class<T> clazz){          Map<String,T> map = JSON.parseObject(jsonStr, new TypeReference<Map<String, T>>() {});          for (Entry<String, T> entry : map.entrySet()) {              JSONObject obj = (JSONObject) entry.getValue();              map.put(entry.getKey(), JSONObject.toJavaObject(obj, clazz));          }          return map;      }  }
redis.maxTotal=50redis.maxIdle=8redis.maxWait=1000redis.testOnBorrow=trueredis.timeout=100000redis.node1.ip=192.168.85.5redis.node1.port=6380#redis.node2.ip=192.168.163.100#redis.node2.port=6380#redis.node3.ip=192.168.163.101#redis.node3.port=6379
<beans xmlns="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:cache="http://www.springframework.org/schema/cache"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd    http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd">    <context:component-scan base-package="cache"/>    <aop:aspectj-autoproxy proxy-target-class="true" />     <!--  加载配置文件 -->    <!-- 构建连接池配置信息 -->    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">        <!-- 最大连接数 -->        <property name="maxTotal" value="${redis.maxTotal}" />        <!-- 最大空闲连接数 -->        <property name="maxIdle" value="${redis.maxIdle}" />        <!--最大等待时间 单位是ms  -->        <property name="maxWaitMillis" value="${redis.maxWait}" />        <!--获得连接时,是否对有效性进行验证  -->        <property name="testOnBorrow" value="${redis.testOnBorrow}" />    </bean>    <bean id="jedisShardInfo1" class="redis.clients.jedis.JedisShardInfo">        <constructor-arg index="0" value="${redis.node1.ip}" />        <constructor-arg index="1" value="${redis.node1.port}" />        <!-- 单位为ms -->        <constructor-arg index="2" value="${redis.timeout}" />    </bean>    <!-- <bean id="jedisShardInfo2" class="redis.clients.jedis.JedisShardInfo">        <constructor-arg index="0" value="${redis.node2.ip}" />        <constructor-arg index="1" value="${redis.node2.port}"            type="int" />    </bean> -->    <!-- <bean id="jedisShardInfo3" class="redis.clients.jedis.JedisShardInfo">        <constructor-arg index="0" value="${redis.node3.ip}" />        <constructor-arg index="1" value="${redis.node3.port}"            type="int" />    </bean> -->    <!-- 定义集群连接池 -->    <bean id="shardedJedisPool" class="redis.clients.jedis.ShardedJedisPool"        destroy-method="close">        <constructor-arg index="0" ref="jedisPoolConfig" />        <constructor-arg index="1">            <list>                <ref bean="jedisShardInfo1" />                <!-- <ref bean="jedisShardInfo2" />                <ref bean="jedisShardInfo3" /> -->            </list>        </constructor-arg>    </bean></beans>