最近需要封装一个操作redis的工具类,不知道怎么向redis中存储对象,想到过用java反射去做。在网上搜索了一下,发现可以用序列化对象的方式去存储。再此我整理了一下

使用Java操作Redis需要jedis-2.1.0.jar

如果需要使用Redis连接池的话,还需commons-pool-1.5.4.jar

以下是我借鉴之后整理的代码,简单封装。

一、redis连接池

RedisConnectionPool

package dao.redisUtil;

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

public class RedisConnectionPool {


    //Redis服务器IP
    private static String IP = "localhost";

    //Redis的端口号
    private static int PORT = 6379;

    //访问密码
//    private static String AUTH = "admin";

    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = 1024;

    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = 200;

    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = 10000;

    private static int TIMEOUT = 10000;

    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = true;

    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis连接池
     */
    static {
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxActive(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWait(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);

            jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取Jedis实例
     * @return
     */
    public synchronized static Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null) {
            jedisPool.returnResource(jedis);
        }
    }
}

二、序列化对象方法

SerializeUtil

package dao.redisUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @author Administrator
 * 序列化对象工具类
 */
public class SerializeUtil {
    public static byte[] serialize(Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            // 序列化
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            byte[] bytes = baos.toByteArray();
            return bytes;
        } catch (Exception e) {

        }
        return null;
    }

    public static Object unserialize( byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            // 反序列化
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {

        }
        return null;
    }
}

三、封装redis增删改查基础操作

RedisOperation

package dao.redisUtil;


import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 实现redis操作
 */
public class RedisOperation{
    //获取redis操作实例
    private Jedis jedis=RedisConnectionPool.getJedis();

    public String set(String key, HashMap<String,String> map) {
        return jedis.hmset(key,map);
    }

    public String set(byte[] key, HashMap<byte[], byte[]> map) {
        return jedis.hmset(key,map);
    }

    public String set(String key, List<String> list) {
        Long aLong=-1l;
        for (String value:list
             ) {
            aLong = jedis.lpush(key,value);
        }
        return aLong<=0?"error":"OK";
    }

    public String set(byte[] key, List<byte[]> list) {
        Long aLong=-1l;
        for (byte[] value:list
                ) {
            aLong=jedis.lpush(key,value);
        }
        return aLong<=0?"error":"OK";
    }

    public String set(String key, String value) {
        return jedis.set(key,value);
    }

    public String set(byte[] key, byte[] value) {
        return jedis.set(key, value);
    }

    public String set(String key, Set<String> set) {
        Long aLong=-1l;
        for (String value:set
             ) {
            aLong=jedis.sadd(key,value);
        }
        return aLong<=0?"error":"OK";
    }

    public String set(byte[] key, Set<byte[]> set) {
        Long aLong=-1l;
        for (byte[] value:set
                ) {
            aLong=jedis.sadd(key,value);
        }
        return aLong<=0?"error":"OK";
    }

    //redis写入对象,用序列化对象的方式
    public String set(String key, Object Obj) {
       return  jedis.set(key.getBytes(),SerializeUtil.serialize(Obj));
    }

    public Object get(String key) {
        Object object=null;
        //获取value的类型
        String type=jedis.type(key);
        //根据不同类型调用不同的获取方法
        if(type.toLowerCase().equals("map")){
            object=jedis.hgetAll(key);
        }else if(type.toLowerCase().equals("set")){
            object=jedis.smembers(key);
        }else if(type.toLowerCase().equals("list")){
            object=jedis.lrange(key,0,-1);
        }else if (type.toLowerCase().equals("string")){
            byte[] bytes=jedis.get(key.getBytes());
            object=SerializeUtil.unserialize(bytes);
            if(object==null){
                object=jedis.get(key);
            }
        }
        return object;
    }

    public Object get(byte[] key) {
        return null;
    }

    public Long delete(String key) {
        return jedis.del(key);
    }

    public String update(String key,Object value){
        //先删除原有数据
        Long along = jedis.del(key);
        if(along<0){
            return "error";
        }
        //再重新添加
        if(value instanceof Map){
            set(key,(Map)value);
        }else if(value instanceof Set){
            set(key,(Set) value);
        }else if(value instanceof List){
            set(key,(List) value);
        }else if(value instanceof String){
            set(key,(String)value);
        }else {
            set(key,value);
        }
        return "OK";
    }
}