Jedis 操作 Redis 工具类

配置类

pom.xml 

pom.xml 里配置依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.5.2</version>
</dependency>

application.properties

spring 属性文件 application.properties 里配置 redis 配置项

REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=xxxxxxx
#超时时间,毫秒 REDIS_TIMEOUT=1000 #最大连接数 REDIS_MAXTOTAL=1000 #最大空闲连接数 REDIS_MAXIDLE=100 #最小空闲连接数 REDIS_MINIDLE=100 #获取连接时的最大等待毫秒数 REDIS_MAXWAITMILLIS=100 #默认缓存过期时间,单位秒 REDIS_DEFAULT_TIMEOUT=7200

常量配置类

@Configuration
public class Constants {

    public static String REDIS_HOST;
    public static int REDIS_PORT;
    public static String REDIS_PASSWORD;
    public static int REDIS_TIMEOUT;
    public static int REDIS_MAXTOTAL;
    public static int REDIS_MAXIDLE;
    public static int REDIS_MINIDLE;
    public static int REDIS_MAXWAITMILLIS;
    public static int REDIS_DEFAULT_TIMEOUT;
    
    @Value("${REDIS_HOST}")
    public void setREDIS_HOST(String rEDIS_HOST) {
        REDIS_HOST = rEDIS_HOST;
    }

    @Value("${REDIS_PORT}")
    public void setREDIS_PORT(int rEDIS_PORT) {
        REDIS_PORT = rEDIS_PORT;
    }
    
    @Value("${REDIS_PASSWORD}")
    public void setREDIS_PASSWORD(String rEDIS_PASSWORD) {
        REDIS_PASSWORD = rEDIS_PASSWORD;
    }

    @Value("${REDIS_TIMEOUT}")
    public void setREDIS_TIMEOUT(int rEDIS_TIMEOUT) {
        REDIS_TIMEOUT = rEDIS_TIMEOUT;
    }

    @Value("${REDIS_MAXTOTAL}")
    public void setREDIS_MAXTOTAL(int rEDIS_MAXTOTAL) {
        REDIS_MAXTOTAL = rEDIS_MAXTOTAL;
    }

    @Value("${REDIS_MAXIDLE}")
    public void setREDIS_MAXIDLE(int rEDIS_MAXIDLE) {
        REDIS_MAXIDLE = rEDIS_MAXIDLE;
    }

    @Value("${REDIS_MINIDLE}")
    public void setREDIS_MINIDLE(int rEDIS_MINIDLE) {
        REDIS_MINIDLE = rEDIS_MINIDLE;
    }

    @Value("${REDIS_MAXWAITMILLIS}")
    public void setREDIS_MAXWAITMILLIS(int rEDIS_MAXWAITMILLIS) {
        REDIS_MAXWAITMILLIS = rEDIS_MAXWAITMILLIS;
    }

    @Value("${REDIS_DEFAULT_TIMEOUT}")
    public void setREDIS_DEFAULT_TIMEOUT(int rEDIS_DEFAULT_TIMEOUT) {
        REDIS_DEFAULT_TIMEOUT = rEDIS_DEFAULT_TIMEOUT;
    }
}

工厂类

Jedis工厂类(枚举)

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.zcdog.market.util.Constants;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException;

public enum JedisFactory {

    INSTANCE;

    private static Logger logger = LoggerFactory.getLogger(JedisFactory.class);

    private volatile JedisPool pool;

    /**
     * 获取Jedis连接
     * @return
     */
    public Jedis getConnection() {
        if (pool == null) {
            synchronized (INSTANCE) {
                if (pool == null) {
                    logger.debug("init jedis pool." + Thread.currentThread().getName());
                    JedisPoolConfig poolConfig = new JedisPoolConfig();
                    poolConfig.setMaxTotal(Constants.REDIS_MAXTOTAL);
                    poolConfig.setMaxIdle(Constants.REDIS_MAXIDLE);
                    poolConfig.setMinIdle(Constants.REDIS_MINIDLE);
                    poolConfig.setMaxWaitMillis(Constants.REDIS_MAXWAITMILLIS);
                    if (Constants.REDIS_PASSWORD != null && !"".equals(Constants.REDIS_PASSWORD)) {
                        pool = new JedisPool(poolConfig, Constants.REDIS_HOST, Constants.REDIS_PORT, Constants.REDIS_TIMEOUT, Constants.REDIS_PASSWORD);
                    }else {
                        pool = new JedisPool(poolConfig, Constants.REDIS_HOST, Constants.REDIS_PORT, Constants.REDIS_TIMEOUT);
                    }
                }
            }
        }
        return pool.getResource();
    }

    /**
     * 处理Jedis连接异常
     * 记录日志并返回连接是否中断
     * @param jedisException
     * @return
     */
    public boolean handleJedisException(Exception jedisException) {
        if (jedisException instanceof JedisConnectionException) {
            logger.error("Redis connection lost.", jedisException);
        } else if (jedisException instanceof JedisDataException) {
            if ((jedisException.getMessage() != null) && (jedisException.getMessage().indexOf("READONLY") != -1)) {
                logger.error("Redis connection is read-only slave.", jedisException);
            } else {
                return false;
            }
        } else {
            logger.error("Jedis happen exception.", jedisException);
        }
        return true;
    }

   /**
    * 返回Jedis连接到连接池
    * 根据连接状态调用不同的返回方法
    * @param jedis
    * @param exceptionFlag
    */
    public void closeResource(Jedis jedis, boolean exceptionFlag) {
        try {
            if (exceptionFlag) {
                pool.returnBrokenResource(jedis);
            } else if (!exceptionFlag && jedis != null) {
                pool.returnResource(jedis);
            }
        } catch (Exception e) {
            logger.error("Return back jedis failed, will close the jedis.", e);
            try {
                jedis.quit();
            } catch (Exception ex) {
                logger.error("Jedis quit error.", ex);
            }
            try {
                jedis.disconnect();
            } catch (Exception exd) {
                logger.error("Jedis disconnect error.", exd);
            }
        }
    }
}

工具类

Jedis工具类,如果没有适用的方法,可自行添加,仅作示例。

更多可参考:Jedis工具类

import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;

public class RedisUtils {

    private static Logger logger = LoggerFactory.getLogger(RedisUtils.class);

    private static Jedis getConnection() {
        return JedisFactory.INSTANCE.getConnection();
    }

    public static void closeResource(Jedis jedis, boolean exceptionFlag) {
        JedisFactory.INSTANCE.closeResource(jedis, exceptionFlag);
    }

    public static boolean handleJedisException(Exception jedisException) {
        return JedisFactory.INSTANCE.handleJedisException(jedisException);
    }

    public static void save(String key, String value) {
        save(key, value, Constants.REDIS_DEFAULT_TIMEOUT);
    }

    public static void save(String key, String value, int expires) {
        Jedis jedis = null;
        boolean exceptionFlag = false;
        try {
            jedis = getConnection();
            if (key == null || "".equals(key)) {
                return;
            }
            jedis.setex(key, expires, value);
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("save redis error:", e);
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static String get(String key) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        String value = null;
        try {
            jedis = getConnection();
            value = jedis.get(key);
            return value;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("get redis error :", e);
            return value;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static void delete(String key) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            if (key == null || "".equals(key)) {
                return;
            }
            jedis = getConnection();
            jedis.del(key);
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("delete redis error:", e);
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static List<String> mget(String[] keys) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            List<String> list = null;
            jedis = getConnection();
            list = jedis.mget(keys);
            return list;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            return null;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static String hget(String key, String field) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        String value = null;
        try {
            jedis = getConnection();
            value = jedis.hget(key, field);
            return value;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            return value;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static String setnx(String key, String value) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        String result = null;
        try {
            jedis = getConnection();
            result = jedis.set(key, value, "NX", "EX", 300L);
            return result;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            return result;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static void hsetTransaction(String key1, String field1, String value1, String key2, String field2,
            String value2, int timeout) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            jedis = getConnection();
            Transaction multi = jedis.multi();
            multi.hset(key1, field1, value1);
            multi.expire(key1, Constants.REDIS_DEFAULT_TIMEOUT);

            multi.hset(key2, field2, value2);
            multi.expire(key2, timeout);
            multi.exec();
            logger.info("[redis] hsetTransaction success key1: {} field1: {} key2: {} field2: {}", key1, field1, key2,
                    field2);
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("  hset hsetTransaction error :", e);
        } finally {
            closeResource(jedis, exceptionFlag);
        }

    }

    public static void hsetTransactionWithDeleteV2(String key1, String field1, String value1, String key2,
            String field2, String value2, int timeout, String deleteKey) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            jedis = getConnection();
            Transaction multi = jedis.multi();
            multi.hset(key1, field1, value1);
            multi.expire(key1, Constants.REDIS_DEFAULT_TIMEOUT);

            multi.hset(key2, field2, value2);
            multi.expire(key2, timeout);
            multi.del(deleteKey);
            multi.exec();
            logger.info("[redis] hsetTransactionWithDelete success key1: {} field1: {} key2: {} field2: {}", key1,
                    field1, key2, field2);
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("  hsetTransactionWithDelete redis error :", e);
        } finally {
            closeResource(jedis, exceptionFlag);
        }

    }

    public static Map<?, ?> hgetall(String key) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        Map<?, ?> value = null;
        try {
            jedis = getConnection();
            value = jedis.hgetAll(key);
            return value;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("  hgetall redis error :", e);
            return value;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static void hset(String key, String field, String value) {
        hset(key, field, value, Constants.REDIS_DEFAULT_TIMEOUT);
    }

    public static void hset(String key, String field, String value, int expireTime) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            jedis = getConnection();
            jedis.hset(key, field, value);
            jedis.expire(key, expireTime);
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("  hset redis error :", e);
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static void hdelete(String key, String field) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            jedis = getConnection();
            jedis.hdel(key, field);
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("  hdel redis error :", e);
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static boolean hexist(String key, String field) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            jedis = getConnection();
            boolean flag = jedis.hexists(key, field);
            return flag;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("hexist redis error:", e);
            return false;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static int hlen(String key) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        try {
            jedis = getConnection();
            return jedis.hlen(key).intValue();
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("  hlen redis error :", e);
            return 0;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

    public static Set<String> hkeys(String key) {
        boolean exceptionFlag = false;
        Jedis jedis = null;
        Set<String> skey = null;
        try {
            jedis = getConnection();
            skey = jedis.hkeys(key);
            return skey;
        } catch (Exception e) {
            exceptionFlag = handleJedisException(e);
            logger.error("hkeys redis error:", e);
            return skey;
        } finally {
            closeResource(jedis, exceptionFlag);
        }
    }

}

 

posted @ 2016-12-06 15:13  一线大码  Views(541)  Comments(0Edit  收藏  举报