Jedis连接池(实际项目可用)

POM依赖


        UTF-8
        1.7.25
    

    
        
            junit
            junit
            3.8.1
            test
        
        
            org.slf4j
            slf4j-api
            ${slf4j.version}
        
        
            org.slf4j
            slf4j-log4j12
            1.7.25
        
        
        
            redis.clients
            jedis
            3.2.0
        
    

RedisPool

package utils;

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

public class RedisPool {
    //声明成static的原因:保证jedis连接池在tomcat启动时就加载出来
    //jedis连接池
    private static JedisPool pool;
    private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.maxTotal", "20"));
    private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.maxIdle", "10"));
    private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.minIdle", "2"));
    private static Integer maxWaitMillis = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.maxWaitMillis", "2"));
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.pool.testOnBorrow", "true"));
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.pool.testOnReturn", "true"));
    private static Integer timeBetweenEvictionRunsMillis = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.timeBetweenEvictionRunsMillis", "2"));
    private static Boolean testWhileIdle =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.pool.testWhileIdle", "true"));
    private static Integer numTestsPerEvictionRun = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.numTestsPerEvictionRun", "2"));
    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.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        config.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
        config.setTestWhileIdle(testWhileIdle);
        config.setNumTestsPerEvictionRun(numTestsPerEvictionRun);

        //连接池耗尽的时候,是否阻塞,false会抛出异常,true阻塞直到超时,会抛出超时异常,默认为true
        config.setBlockWhenExhausted(true);

        //这里超时时间是2s
        pool = new JedisPool(config, redisIp, redisPort, 1000*2);

    }

    static {
        initPool();
    }

    //从连接池中拿取一个实例
    public static Jedis getJedis() {
        return pool.getResource();
    }

    //将正常实例放回jedis连接池
    public static void returnResource(Jedis jedis) {
        pool.close();
    }

    //将破损实例放回jedis连接池
    public static void returnBrokenResource(Jedis jedis) {
        pool.close();
    }

}

RedisPoolUtil

package utils;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

public class RedisPoolUtil {
    
    private static Logger log = LoggerFactory.getLogger(RedisPoolUtil.class);

    //重新设置有效期
    //参数只有key和有效期,因为只需要根据key设置有效期即可
    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("setex key:{} error", key, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    //exTime单位是s,设置session有效时间
    //当用户初次登录的时候,需要设置有限期,存在redis session中
    //后续如果用户再次请求登录,则只需要调用expire,重新设置有效期即可
    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("setex key:{} value:{} error", key, value, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    public static String set(String key, String value) {
        Jedis jedis = null;
        //jedis返回的结果
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            //设置key-value
            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;
    }

    public static String get(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            //根据key获取value值
            result = jedis.get(key);
        } catch (Exception e) {
            log.error("set key:{} error", key, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    public static Long del(String key) {
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            //根据key删除key-value
            result = jedis.del(key);
        } catch (Exception e) {
            log.error("set key:{} error", key, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }
}

redis 配置文件

#最大活动对象数     
redis.pool.maxTotal=1000
#最大能够保持idel状态的对象数      
redis.pool.maxIdle=100
#最小能够保持idel状态的对象数   
redis.pool.minIdle=50
#当池内没有返回对象时,最大等待时间    
redis.pool.maxWaitMillis=10000
#当调用borrow Object方法时,是否进行有效性检查    
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查    
redis.pool.testOnReturn=true
#“空闲链接”检测线程,检测的周期,毫秒数。如果为负值,表示不运行“检测线程”。默认为-1.  
redis.pool.timeBetweenEvictionRunsMillis=30000
#向调用者输出“链接”对象时,是否检测它的空闲超时;  
redis.pool.testWhileIdle=true
# 对于“空闲链接”检测线程而言,每次检测的链接资源的个数。默认为3.  
redis.pool.numTestsPerEvictionRun=50
#redis服务器的IP
redis.ip=127.0.0.1
#redis服务器的Port
redis.port=6379
i

日志配置文件

logback.xml文件




    
    class="ch.qos.logback.core.ConsoleAppender">
        
            %d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{userId}] [%X{requestId}] %logger - %msg%n
        
    

    
    class="ch.qos.logback.core.rolling.RollingFileAppender">
        logFile.log
        class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            logFile.%d{yyyy-MM-dd_HH-mm}.log.zip
        

        class="ch.qos.logback.classic.PatternLayout">
            %d{HH:mm:ss,SSS} [%thread] %-5level %logger{32} - %msg%n
        
    

    
        
        
        
    


你可能感兴趣的:(Jedis连接池(实际项目可用))