redis Jedis存取list对象和map

来源:互联网 发布:两个字符串相似度算法 编辑:程序博客网 时间:2024/05/16 09:35
1,redis缓存配置类
Java代码  收藏代码
  1. public class RedisCache {  
  2.     protected static Logger logger = Logger.getLogger(RedisCache.class);  
  3.     public final static String VIRTUAL_COURSE_PREX = "_lc_vc_";  
  4.       
  5.       
  6.     private RedisCacheConfig redisCacheConfig;  
  7.     private JedisPool jedisPool = null;  
  8.       
  9.     public RedisCacheConfig getRedisCacheConfig() {  
  10.         return redisCacheConfig;  
  11.     }  
  12.   
  13.     public void setRedisCacheConfig(RedisCacheConfig redisCacheConfig) {  
  14.         this.redisCacheConfig = redisCacheConfig;  
  15.     }  
  16.   
  17.     public RedisCache(){  
  18.           
  19.     }  
  20.       
  21.     /** 
  22.      * 初始化Redis连接池 
  23.      */  
  24.     private void initialPool(){  
  25.         JedisPoolConfig poolConfig = redisCacheConfig.getPoolConfig();  
  26.         String[] serverArray = redisCacheConfig.getServers().split(",");  
  27.         for(int i = 0; i < serverArray.length; i++){  
  28.             try {  
  29.                 JedisPoolConfig config = new JedisPoolConfig();  
  30.                 config.setMaxTotal(poolConfig.getMaxTotal());  
  31.                 config.setMaxIdle(poolConfig.getMaxIdle());  
  32.                 config.setMaxWaitMillis(poolConfig.getMaxWaitMillis());  
  33.                 config.setTestOnBorrow(poolConfig.getTestOnBorrow());  
  34.                 config.setTestOnReturn(poolConfig.getTestOnReturn());  
  35.                   
  36.                 jedisPool = new JedisPool(config, serverArray[i], redisCacheConfig.getPort(), redisCacheConfig.getTimeout());  
  37.                 break;  
  38.             } catch (Exception e) {  
  39.                 logger.error("initialPool create JedisPool(" + serverArray[i] + ") error : "+e);  
  40.             }  
  41.         }  
  42.           
  43.     }  
  44.       
  45.     /** 
  46.      * 在多线程环境同步初始化 
  47.      */  
  48.     private synchronized void poolInit() {  
  49.         if (jedisPool == null) {    
  50.             initialPool();  
  51.         }  
  52.     }  
  53.    
  54.        
  55.     /** 
  56.      * 同步获取Jedis实例 
  57.      * @return Jedis 
  58.      */  
  59.     public synchronized Jedis getJedis() {  
  60.         if (jedisPool == null) {  
  61.             poolInit();  
  62.         }  
  63.         Jedis jedis = null;  
  64.         try {  
  65.             if (jedisPool != null) {  
  66.                 jedis = jedisPool.getResource();  
  67.                 jedis.auth(redisCacheConfig.getAuth());  
  68.             }  
  69.         } catch (Exception e) {  
  70.             logger.error("Get jedis error : "+e);  
  71.             e.printStackTrace();  
  72.         }finally{  
  73.             returnResource(jedis);  
  74.         }  
  75.         return jedis;  
  76.     }  
  77.       
  78.     /** 
  79.      * 释放jedis资源 
  80.      * @param jedis 
  81.      */  
  82.     public void returnResource(final Jedis jedis) {  
  83.         if (jedis != null && jedisPool !=null) {  
  84.             jedisPool.returnResource(jedis);  
  85.         }  
  86.     }  
  87.   
  88.     /** 
  89.      * 得到Key 
  90.      * @param key 
  91.      * @return 
  92.      */  
  93.     public String buildKey(String key){  
  94.         return VIRTUAL_COURSE_PREX + key;  
  95.     }  
  96.     /** 
  97.      * 设置 String 
  98.      * @param key 
  99.      * @param value 
  100.      */  
  101.     public void setString(String key ,String value){  
  102.         try {  
  103.             value = StringUtil.isNullOrEmpty(value) ? "" : value;  
  104.             getJedis().set(buildKey(key),value);  
  105.         } catch (Exception e) {  
  106.             logger.error("Set key error : "+e);  
  107.         }  
  108.     }  
  109.        
  110.     /** 
  111.      * 设置 过期时间 
  112.      * @param key 
  113.      * @param seconds 以秒为单位 
  114.      * @param value 
  115.      */  
  116.     public void setString(String key ,int seconds,String value){  
  117.         try {  
  118.             value = StringUtil.isNullOrEmpty(value) ? "" : value;  
  119.             getJedis().setex(buildKey(key), seconds, value);  
  120.         } catch (Exception e) {  
  121.             logger.error("Set keyex error : "+e);  
  122.         }  
  123.     }  
  124.        
  125.     /** 
  126.      * 获取String值 
  127.      * @param key 
  128.      * @return value 
  129.      */  
  130.     public String getString(String key){  
  131.         String bKey = buildKey(key);  
  132.         if(getJedis() == null || !getJedis().exists(bKey)){  
  133.             return null;  
  134.         }  
  135.         return getJedis().get(bKey);  
  136.     }  
  137.     /** 
  138.      * 设置 list 
  139.      * @param <T> 
  140.      * @param key 
  141.      * @param value 
  142.      */  
  143.     public <T> void setList(String key ,List<T> list){  
  144.         try {  
  145.             getJedis().set(key.getBytes(),ObjectTranscoder.serialize(list));  
  146.         } catch (Exception e) {  
  147.             logger.error("Set key error : "+e);  
  148.         }  
  149.     }  
  150.     /** 
  151.      * 获取list 
  152.      * @param <T> 
  153.      * @param key 
  154.      * @return list 
  155.      */  
  156.     public <T> List<T> getList(String key){  
  157.         String bKey = buildKey(key);  
  158.         if(getJedis() == null || !getJedis().exists(key.getBytes())){  
  159.             return null;  
  160.         }  
  161.         byte[] in = getJedis().get(key.getBytes());    
  162.         List<T> list = (List<T>) ObjectTranscoder.deserialize(in);    
  163.         return list;  
  164.     }  
  165.     /** 
  166.      * 设置 map 
  167.      * @param <T> 
  168.      * @param key 
  169.      * @param value 
  170.      */  
  171.     public <T> void setMap(String key ,Map<String,T> map){  
  172.         try {  
  173.             getJedis().set(key.getBytes(),ObjectTranscoder.serialize(map));  
  174.         } catch (Exception e) {  
  175.             logger.error("Set key error : "+e);  
  176.         }  
  177.     }  
  178.     /** 
  179.      * 获取list 
  180.      * @param <T> 
  181.      * @param key 
  182.      * @return list 
  183.      */  
  184.     public <T> Map<String,T> getMap(String key){  
  185.         String bKey = buildKey(key);  
  186.         if(getJedis() == null || !getJedis().exists(key.getBytes())){  
  187.             return null;  
  188.         }  
  189.         byte[] in = getJedis().get(key.getBytes());    
  190.         Map<String,T> map = (Map<String, T>) ObjectTranscoder.deserialize(in);    
  191.         return map;  
  192.     }  
  193. }  

2,spring配置
Java代码  收藏代码
  1. <!-- 声明redisCache -->  
  2.     <bean id="redisCache" class="com.cache.RedisCache" depends-on="redisCacheConfig">  
  3.         <property name="redisCacheConfig" ref="redisCacheConfig"></property>  
  4.     </bean>  
  5.     <bean id="redisCacheConfig" class="com.able.virtualcourse.cache.RedisCacheConfig" depends-on="jedisPoolConfig">  
  6.         <property name="servers"><value>${redis.servers}</value></property>  
  7.         <property name="port"><value>${redis.port}</value></property>  
  8.         <property name="auth"><value>${redis.auth}</value></property>  
  9.         <property name="timeout"><value>${redis.pool.timeout}</value></property>  
  10.         <property name="poolConfig" ref="jedisPoolConfig"></property>  
  11.     </bean>  
  12.     <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">  
  13.         <property name="maxTotal"><value>${redis.pool.maxTotal}</value></property>  
  14.         <property name="maxIdle"><value>${redis.pool.maxIdle}</value></property>  
  15.         <property name="maxWaitMillis"><value>${redis.pool.maxWait}</value></property>  
  16.         <property name="testOnBorrow"><value>${redis.pool.testOnBorrow}</value></property>  
  17.         <property name="testOnReturn"><value>${redis.pool.testOnReturn}</value></property>  
  18.     </bean>  

3,序列化工具类
Java代码  收藏代码
  1. public class ObjectTranscoder {  
  2.     public static byte[] serialize(Object value) {    
  3.         if (value == null) {    
  4.             throw new NullPointerException("Can't serialize null");    
  5.         }    
  6.         byte[] rv=null;    
  7.         ByteArrayOutputStream bos = null;    
  8.         ObjectOutputStream os = null;    
  9.         try {    
  10.             bos = new ByteArrayOutputStream();    
  11.             os = new ObjectOutputStream(bos);    
  12.             os.writeObject(value);    
  13.             os.close();    
  14.             bos.close();    
  15.             rv = bos.toByteArray();    
  16.         } catch (IOException e) {    
  17.             throw new IllegalArgumentException("Non-serializable object", e);    
  18.         } finally {    
  19.             try {  
  20.                  if(os!=null)os.close();  
  21.                  if(bos!=null)bos.close();  
  22.             }catch (Exception e2) {  
  23.              e2.printStackTrace();  
  24.             }    
  25.         }    
  26.         return rv;    
  27.     }    
  28.   
  29.     public static Object deserialize(byte[] in) {    
  30.         Object rv=null;    
  31.         ByteArrayInputStream bis = null;    
  32.         ObjectInputStream is = null;    
  33.         try {    
  34.             if(in != null) {    
  35.                 bis=new ByteArrayInputStream(in);    
  36.                 is=new ObjectInputStream(bis);    
  37.                 rv=is.readObject();    
  38.                 is.close();    
  39.                 bis.close();    
  40.             }    
  41.         } catch (Exception e) {    
  42.             e.printStackTrace();  
  43.          }finally {    
  44.              try {  
  45.                  if(is!=null)is.close();  
  46.                  if(bis!=null)bis.close();  
  47.              } catch (Exception e2) {  
  48.                  e2.printStackTrace();  
  49.              }  
  50.          }  
  51.         return rv;    
  52.     }