Redis 连接池配置(在 Spring Boot 框架中)

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

/**
 * redis 连接池
 * @date 2018年1月17日 上午9:29:03
 */
@Component
public class RedisConnectPools {

    private static Logger log = LogManager.getLogger(RedisConnectPools.class);

    private static JedisPool pool = null;
    
    @Autowired
    private RedisConfig redisConfig;

    private void init() throws JedisConnectionException {

        JedisPoolConfig config = new JedisPoolConfig();
        // 控制一个 pool 可分配多少个 jedis 实例,通过 pool.getResource() 来获取;
        // 如果赋值为 -1,则表示不限制;如果 pool 已经分配了 maxActive个jedis 实例,则此时 pool 的状态为 exhausted (耗尽)。
        config.setMaxTotal(2000);
        // 控制一个 pool 最多有多少个状态为 idle (空闲的)的 jedis 实例。
        config.setMaxIdle(50);
        // 表示当 borrow (引入)一个 jedis 实例时,最大的等待时间,如果超过等待时间,则直接抛出 JedisConnectionException;
        config.setMaxWaitMillis(1000 * 100);
        // 在 borrow 一个 jedis 实例时,是否提前进行 validate 操作;如果为 true,则得到的 jedis 实例均是可用的;
        config.setTestOnBorrow(true);
        pool = new JedisPool(config, redisConfig.getIp(), redisConfig.getPort(), 1000 * 100, redisConfig.getPsw());
    }

    /**
     * 获取redis连接池对象
     *
     * @return
     */
    public JedisPool getPool() {
        if (pool == null) {
            init();
        }
        return pool;
    }

    /**
     * 获取Jedis对象
     *
     * @param dataBaseIndex 库索引
     * @return
     */
    public Jedis getJedisObj(int dataBaseIndex) {

        JedisPool pool = null;
        Jedis jedis = null;
        pool = getPool();
        jedis = pool.getResource();
        jedis.select(dataBaseIndex);

        log.info("redis连接池,Active:{},Idle:{},Waiters:{}",
                pool.getNumActive(), pool.getNumIdle(), pool.getNumWaiters());
        return jedis;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值