Maven项目中redis(jedis)的配置和使用

来源:互联网 发布:mac蓝屏之后开不了机了 编辑:程序博客网 时间:2024/06/07 13:59

上一篇博客简单阐述java远程连接redis遇到的问题,这一篇博客详细阐述远程连接redis的相关配置。
要想在Java中连接Redis,并进行操作,由两种方式,一种是spring data redis,它是由spring集成的,不支持集群,一种是官方推荐的jedis,支持集群,其他功能差不多一样,
这里我大致介绍jedis操作实例,以下是使用Jedis的具体步骤:
在javaweb项目(使用了Maven)的pom.xml文件中添加以下依赖

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

注意:如果不是使用Maven的项目下载包导入项目即可。
创建redisUtil工具类来封装jedis的相关配置和方法:
创建工具类的思路:
1>创建jedisPool(JedisPool的配置参数大部分是由JedisPoolConfig的对应项来赋值的)
2>获取Jedis实例需要从JedisPool中获取
3>用完Jedis实例需要返回给JedisPool
4>如果Jedis在使用过程中出错,那么也需要返回给JedisPool

其中jedisPool 继承Pool< Jedis > ,查看源码可知创建jedisPool所需要的各种参数,一一配置即可。
其中JedisPoolConfig继承GenericObjectPoolConfig对一些参数的默认设置如下:

setTestWhileIdle(true);setMinEvictableIdleTimeMillis(60000);setTimeBetweenEvictionRunsMillis(30000);setNumTestsPerEvictionRun(-1);

redisUtil工具类具体代码:

public class RedisUtil {    private static Logger logger = Logger.getLogger(RedisUtil.class);    private static JedisPool pool = null;    /**     * 构建redis连接池     *      * @param ip     * @param port     * @return JedisPool     */    public static JedisPool getPool() {        if (pool == null) {            // jedispool为null则初始化,            JedisPoolConfig config = new JedisPoolConfig();            // 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;            // 如果赋值为-1,则表示不限制;如果pool已经分配了maxTotal个jedis实例,则此时pool的状态为exhausted(耗尽).            config.setMaxTotal(500);            // 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例            config.setMaxIdle(5);            // 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;            config.setMaxWaitMillis(1000 * 10);            // 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;            config.setTestOnBorrow(true);            pool = new JedisPool(config, localhost, 6379, 10000, "123");            //10000是protocol.timeout 默认值2000        }        return pool;    }    /**     * 获取数据     *      * @param key     * @return     */    public static String get(String key) {        String value = null;        JedisPool pool = null;        Jedis jedis = null;        try {            pool = getPool();            jedis = pool.getResource();            value = jedis.get(key);        } catch (Exception e) {            // TODO: handle exception            // 释放redis对象            pool.returnBrokenResource(jedis);            logger.error("jedis error is" + "e.printStackTrace()");            logger.error("fail to get data from jedis ", e);        } finally {            // 返还到连接池             pool.returnResource(jedis);        }        return value;    }    /**     * 给key赋值,并生命周期设置为seconds     *      * @param key     * @param seconds     *            生命周期 秒为单位     * @param value     */    public static void setx(String key, int seconds, String value) {        JedisPool pool = null;        Jedis jedis = null;        try {            pool = getPool();            jedis = pool.getResource();            jedis.setex(key, seconds, value);        } catch (Exception e) {            // 释放redis对象            pool.returnBrokenResource(jedis);            logger.error("fail to set key and seconds", e);        } finally {            // 返还到连接池            pool.returnResource(jedis);        }    }    /**     * 根据key值来删除已经存在的key-value;     *      * @param key     * @return     */    public static int removex(String key) {        int temp = 0;        JedisPool pool = null;        Jedis jedis = null;        try {            pool = getPool();            jedis = pool.getResource();            temp = jedis.del(key).intValue();        } catch (Exception e) {            // TODO: handle exception            pool.returnBrokenResource(jedis);            logger.error("fail to delete the key-value according to the key", e);        } finally {            //返回redis实例            pool.returnResource(jedis);        }        return temp;    }}

其中在使用完jedis实例时候,进行了资源的返回:pool.returnResource(jedis)
jedis在使用过程出现错误,也进行了资源的返回:pool.returnBrokenResource(jedis)

补充jedis版本带来的问题:
jedis包括2.4.1,2.5.1等高版本的JedisPoolConfig是没有maxActive和maxWait属性的
改动如下:

maxActive->maxTotalmaxWait->maxWaitMillis

redisUtil工具类做好了,使用的时候直接使用其中的方法就可以~
通过自己写jedisPool的配置,深刻领悟到看源码的重要性!!!

原创粉丝点击