redis单机连接池

一、配置文件

1. db.properties配置文件
#IP地址 redis.ip
= 127.0.0.1 #端口号 redis.port=6379 #最大连接数 redis.max.total=20 #最大空闲数 redis.max.idle=10 #最小空闲数 redis.min.idle=2 #效验使用可用连接 redis.test.borrow=true #效验归还可用连接 redis.test.return=false

2. pom.xml文件
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
 

二、java代码

public class RedisPool {
    private static JedisPool pool ; //jedis连接池
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total","20")); //最大连接数
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle","10")); //最大空闲状态
    private static Integer minIdle =Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle","2")); //最小空闲状态

    private static Boolean testOnBorrow =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow","true")); //验证从连接池拿出的jedis实例,一定可用
    private static Boolean testOnReturn =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return","true")); //验证还回连接池的jedis实例,一定可用

    private static String redisIp =PropertiesUtil.getProperty("redis.ip"); //最小空闲状态
    private static Integer redisPort =Integer.parseInt(PropertiesUtil.getProperty("redis.port")); //最小空闲状态


    private static void initPool(){
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);

        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);

        config.setBlockWhenExhausted(true); //连接耗尽时是否阻塞,false抛出异常;true阻塞到超时。默认true

        pool = new JedisPool(config,redisIp,redisPort,1000*2);
    }

    static{
        initPool();
    }

    public static Jedis getJedis(){
        return pool.getResource(); 
    }

    /**
     * redis不正常不可用,将其废弃,最新版本直接将此连接销毁jedis.close();
     * @param jedis
     */
    public static void returnBrokenResource(Jedis jedis){
            pool.returnBrokenResource(jedis); //最新版本已废弃
    }

    public static void returnResource(Jedis jedis){
            pool.returnResource(jedis); //最新版本已废弃
    }
}

三。redis相关类介绍

  (1)JedisPool

    JedisPool保证资源在一个可控范围内,并且提供了线程安全,Jedis连接就是资源,JedisPool管理的就是Jedis连接。此类只有三个方法普通方法,大量的构造器,构造器根据不同的连接配置信息,生成对应的资源池。可以很好地重复利用Jedis,减少new的次数,从而提高效率。

  (2)JedisPoolConfig

    资源池的配置信息,JedisPoolConfig只有一个构造器,大部分配置信息都在继承的类GenericObjectPoolConfigBaseObjectPoolConfig中。配置最大连接数,最大/小空闲等待数,是否效验生成/归还的连接有效等等。JedisPool其中JedisPoolConfig即是JedisPool构造器所要出入的配置对象,根据JedisPoolConfig配置信息,进行资源池管理。

基本配置如下:

setBlockWhenExhausted(boolean blockWhenExhausted)
当池中的资源耗尽时是否进行阻塞,设置false直接报错,true表示会一直等待,直到有可用资源

setEvictionPolicyClassName(String evictionPolicyClassName)
设置逐出策略,默认策略为
"org.apache.commons.pool2.impl.DefaultEvictionPolicy"

setFairness(boolean fairness)
当从池中获取资源或者将资源还回池中时 是否使用java.util.concurrent.locks.ReentrantLock.ReentrantLock 的公平锁机制,默认为false

setJmxEnabled
设置是否启用JMX,默认true

setJmxNameBase(String jmxNameBase)
设置JMX基础名

setJmxNamePrefix(String jmxNamePrefix)
设置JMX前缀名,默认值pool

setLifo(boolean lifo)
设置连接对象是否后进先出,默认true

setMaxIdle(int maxIdle)
设置最大空闲连接数,默认为8

setMaxTotal(int maxTotal)
设置最大连接数,默认18个

setMaxWaitMillis(long maxWaitMillis)
获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1

setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis)
设置连接最小的逐出间隔时间,默认1800000毫秒

setMinIdle(int minIdle)
设置无连接时池中最小的连接个数,默认连接0

setNumTestsPerEvictionRun(int numTestsPerEvictionRun)
每次逐出检查时,逐出连接的个数

setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断

setTestOnBorrow(boolean testOnBorrow)
从池中获取连接时是否测试连接的有效性,默认false

setTestOnCreate(boolean testOnCreate)
在连接对象创建时测试连接对象的有效性,默认false

setTestOnReturn(boolean testOnReturn)
在连接对象返回时,是否测试对象的有效性,默认false

setTestWhileIdle(boolean testWhileIdle)
在连接池空闲时是否测试连接对象的有效性,默认false

setTimeBetweenEvictionRunsMillis(
long timeBetweenEvictionRunsMillis)
设置连接对象有效性扫描间隔,设置为-1,则不运行逐出线程
View Code

  (3)Jedis

  Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件。Jedis有大量的方法,都是进行redis数据库的crud操作。Jedis是有JedisPool连接池创建的。

import com.mmall.common.RedisPool;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;

/**
 * 封装单机redis常用API方法
 */
@Slf4j
public class RedisPoolUtil {


    /**
     * 设置对应key的有效期
     * @param key
     * @param exTime 有效期,单位秒
     * @return
     */
    public static Long expire(String key, int exTime){
        Jedis jedis = null;
        Long result = null;
        try{
            jedis = RedisPool.getJedis();
            result = jedis.expire(key,exTime);
        }catch (Exception e){
            log.error("set key:{} exTime:{} value:{} error",key,exTime,e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    /**
     * string 添加,存在有效期exTime
     * @param key 键
     * @param value 值
     * @param exTime 有效期,单位秒
     * @return
     */
    public static String setEx(String key, String value, int exTime){
        Jedis jedis = null;
        String result = null;
        try{
            jedis = RedisPool.getJedis();
            result = jedis.setex(key,exTime,value);
        }catch (Exception e){
            log.error("set key:{} exTime:{} value:{} error",key,exTime,value,e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    /**
     * string 添加
     * @param key
     * @param value
     * @return
     */
    public static String set(String key, String value){
        Jedis jedis = null;
        String result = null;
        try{
            jedis = RedisPool.getJedis();
            result = jedis.set(key,value);
        }catch (Exception e){
            log.error("set key:{} value:{} error",key,value,e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    /**
     * string 获取
     * @param key
     * @return
     */
    public static String get(String key){
        Jedis jedis = null;
        String result = null;
        try{
            jedis = RedisPool.getJedis();
            result = jedis.get(key);
        }catch (Exception e){
            log.error("get key:{} error",key,e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    /**
     * stirng 删除
     * @param key
     * @return
     */
    public static Long del(String key){
        Jedis jedis = null;
        Long result = null;
        try{
            jedis = RedisPool.getJedis();
            result = jedis.del(key);
        }catch (Exception e){
            log.error("get key:{} error",key,e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }
}
View Code
posted @ 2019-10-15 21:40  王大军  阅读(1347)  评论(2编辑  收藏  举报