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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM