码迷,mamicode.com
首页 > 编程语言 > 详细

java- 简单redis 封装

时间:2014-09-15 21:17:29      阅读:914      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   color   io   使用   java   ar   文件   

jedis 简单使用并不复杂,但是考虑到效率问题,还是需要用到 jedispool,简单封装一下,方便调用,mark 一下。

1.由于没有封装自己的序列化接口,所以这块需要我们自己实现

 1 package com.lixiaodao.common.redis;
 2 
 3 public interface Serializer<T> {
 4     
 5     String serialize(T value);
 6     
 7     T deserialize(String value,Class<T> clazz);
 8     
 9 }
10 
11 
12 -----------------------------------------------------------------------------
13 // Gson 的一种简单实现方式
14 
15 package com.lixiaodao.common.redis;
16 
17 import com.google.gson.Gson;
18 
19 public class JsonSerializer<T> implements Serializer<T> {
20     
21     private Gson gson = new Gson();
22 
23     @Override
24     public String serialize(T value) {
25         return gson.toJson(value);
26     }
27 
28     @Override
29     public T deserialize(String json, Class<T> clazz) {
30         return gson.fromJson(json, clazz);
31     }
32 
33 }

 2 .redispool配置类

  1 package com.lixiaodao.common.redis;
  2 
  3 import java.io.InputStreamReader;
  4 
  5 import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
  6 
  7 import redis.clients.jedis.JedisPoolConfig;
  8 
  9 import com.google.gson.Gson;
 10 
 11 public class RedisPoolConfig extends GenericObjectPoolConfig {
 12 
 13     private RedisConfig master;
 14     private RedisConfig slave;
 15 
 16     private static Gson gson = new Gson();
 17 
 18     private RedisPoolConfig() {
 19     }
 20 
 21     /**
 22      * 读取配置文件
 23      * @param fileName
 24      * @return
 25      */
 26     public static RedisPoolConfig loadConfig(String fileName) {
 27         return gson.fromJson(new InputStreamReader(RedisPoolConfig.class
 28                 .getClassLoader().getResourceAsStream(fileName)),
 29                 RedisPoolConfig.class);
 30     }
 31 
 32     class RedisConfig {
 33         private String ip;
 34         private int port;
 35         private int timeout;
 36         private String password;
 37         private int database;
 38 
 39         private JedisPoolConfig poolConfig;
 40 
 41         public JedisPoolConfig getPoolConfig() {
 42             if (poolConfig == null) {
 43                 poolConfig = new JedisPoolConfig();
 44             }
 45             return poolConfig;
 46         }
 47 
 48         public String getIp() {
 49             return ip;
 50         }
 51 
 52         public int getPort() {
 53             return port;
 54         }
 55 
 56         public int getTimeout() {
 57             return timeout;
 58         }
 59 
 60         public String getPassword() {
 61             return password;
 62         }
 63 
 64         public int getDatabase() {
 65             return database;
 66         }
 67 
 68         public void setIp(String ip) {
 69             this.ip = ip;
 70         }
 71 
 72         public void setPort(int port) {
 73             this.port = port;
 74         }
 75 
 76         public void setTimeout(int timeout) {
 77             this.timeout = timeout;
 78         }
 79 
 80         public void setPassword(String password) {
 81             this.password = password;
 82         }
 83 
 84         public void setDatabase(int database) {
 85             this.database = database;
 86         }
 87 
 88         public void setPoolConfig(JedisPoolConfig poolConfig) {
 89             this.poolConfig = poolConfig;
 90         }
 91 
 92     }
 93 
 94     public RedisConfig getMaster() {
 95         return master;
 96     }
 97 
 98     public RedisConfig getSlave() {
 99         return slave;
100     }
101 
102     public void setMaster(RedisConfig master) {
103         this.master = master;
104     }
105 
106     public void setSlave(RedisConfig slave) {
107         this.slave = slave;
108     }
109 }

3.主从连接池 (master 用于 写,slave 用于读,分散压力)

 

package com.lixiaodao.common.redis;

import com.lixiaodao.common.redis.RedisPoolConfig.RedisConfig;

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

public class RedisSlaveMasterPool {
    private JedisPool master;
    private JedisPool slave;
    
    public RedisSlaveMasterPool(RedisPoolConfig config){
        RedisConfig masterConfig = config.getMaster();
        master = new JedisPool(masterConfig.getPoolConfig(), masterConfig.getIp(),masterConfig.getPort());
        RedisConfig slaveConfig = config.getSlave();
        slave = new JedisPool(slaveConfig.getPoolConfig(), slaveConfig.getIp(),slaveConfig.getPort());
    }
    
    /**
     * 销毁 jedis 连接池
     */
    public void destory(){
        master.destroy();
        slave.destroy();
    }
    
    /**
     * 从 池子中 获取一个 redis 写权限的实例
     * @return
     */
    public Jedis getWriteJedis(){
        return master.getResource();
    }
    
    public Jedis getReadJedis(){
        return slave.getResource();
    }
    
    /**
     * 释放连接 资源
     * @param jedis
     */
    public void returnReadRedis(Jedis jedis){
        slave.returnResource(jedis);
    }
    
    /**
     * 释放连接资源
     * @param jedis
     */
    public void returnWriteRedis(Jedis jedis){
        master.returnResource(jedis);
    }
    
}

 

4. 客户端简单 封装(大部分方法没有写。。。嘿嘿)

 

 1 package com.lixiaodao.common.redis;
 2 
 3 import redis.clients.jedis.Jedis;
 4 
 5 /**
 6  * redisclient
 7  * @author Cookie
 8  *客户端在 new 的时候,去得到jedis 实例,现用现拿,延迟去拿,用完了就释放。。。。
 9  * @param <T>
10  */
11 public class RedisClient<T> {
12 
13     private static final int DEFAULT_DB_INDEX = 0;
14 
15     private RedisSlaveMasterPool pool;
16     private Serializer<T> serializer;
17     private int dbIndex;
18 
19     public RedisClient(RedisSlaveMasterPool pool, Serializer<T> serializer) {
20         this(pool, serializer, DEFAULT_DB_INDEX);
21     }
22 
23     public RedisClient(RedisSlaveMasterPool pool, Serializer<T> serializer,
24             int dbIndex) {
25         super();
26         this.pool = pool;
27         this.serializer = serializer;
28         this.dbIndex = dbIndex;
29     }
30 
31     public Jedis getWriteJedis() {
32         Jedis jedis = pool.getWriteJedis();
33         try {
34             jedis.select(dbIndex);
35         } catch (Exception e) {
36             pool.returnWriteRedis(jedis);
37         }
38         return jedis;
39     }
40 
41     public Jedis getReadJedis() {
42         Jedis jedis = pool.getReadJedis();
43         try {
44             jedis.select(dbIndex);
45         } catch (Exception e) {
46             pool.getReadJedis();
47         }
48         return jedis;
49     }
50 
51     public void set(String key, T value) {
52         Jedis jedis = getWriteJedis();
53         try {
54             jedis.set(key, serializer.serialize(value));
55         } finally {
56             pool.returnWriteRedis(jedis);
57         }
58     }
59 
60     public T get(String key,Class<T> clazz) {
61         Jedis jedis = getReadJedis();
62         T value = null;
63         try {
64             String cached = jedis.get(key);
65             if (cached != null) {
66                 value = serializer.deserialize(cached, clazz);
67             }
68         } finally {
69             pool.returnReadRedis(jedis);
70         }
71         return value;
72     }
73 }

5  .定义工厂 ,方便调用

 1 package com.lixiaodao.common.redis;
 2 
 3 
 4 public class RedisClientFactory {
 5     
 6     /**
 7      * 客户端工厂 单粒
 8      */
 9     public static final RedisClientFactory INSTANCE = new RedisClientFactory();
10     
11     private static final String FILE_NAME = "jedis.json"; 
12     
13     private RedisSlaveMasterPool pool;
14     
15     private RedisClientFactory() {
16         // 初始化连接池
17         RedisPoolConfig poolConfig = RedisPoolConfig.loadConfig(FILE_NAME);
18         // 生产 实例
19         pool = new RedisSlaveMasterPool(poolConfig);
20     }
21     
22     public <T> RedisClient<T> createRedisClient(){
23         JsonSerializer<T> serializer = new JsonSerializer<T>();
24         return new RedisClient<T>(pool, serializer);
25     }
26     
27     public <T> RedisClient<T> createRedisClient(int dbIndex){
28         JsonSerializer<T> serializer = new JsonSerializer<T>();
29         return new RedisClient<T>(pool, serializer,dbIndex);
30     } 
31     
32     public void destroy(){
33         pool.destory();
34     }
35 }

 此外 还一个定义异常、统一key 生成规则。。。。

 忘了说一句: jedis.json 要放到 根目录下

{
    ‘master‘:{
        ‘ip‘:‘127.0.0.1‘,
        ‘port‘:6379,
        ‘maxTotal‘:200,
        ‘maxIdle‘:20,
        ‘timeout‘:2000,
        ‘password‘:‘‘,
        ‘database‘:0
    },
    ‘slave‘:{
        ‘ip‘:‘127.0.0.1‘,
        ‘port‘:6379,
        ‘maxTotal‘:200,
        ‘maxIdle‘:20,
        ‘timeout‘:2000
    }
}

 

java- 简单redis 封装

标签:des   style   blog   color   io   使用   java   ar   文件   

原文地址:http://www.cnblogs.com/lixiaodao-java/p/3973544.html

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