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

Posted dgwblog

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Jedis连接池(实际项目可用)相关的知识,希望对你有一定的参考价值。

POM依赖

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <slf4j.version>1.7.25</slf4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>

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文件

<?xml version="1.0" encoding="UTF-8" ?>

<configuration scan="true" scanPeriod="3 seconds">
    <!--设置日志输出为控制台-->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{userId}] [%X{requestId}] %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <!--设置日志输出为文件-->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>logFile.log</File>
        <rollingPolicy  class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>logFile.%d{yyyy-MM-dd_HH-mm}.log.zip</FileNamePattern>
        </rollingPolicy>

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

    <root>
        <level value="DEBUG"/>
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>


</configuration>

以上是关于Jedis连接池(实际项目可用)的主要内容,如果未能解决你的问题,请参考以下文章

jedis连接redis

Jedis连接池:JedisPool及连接池工具类搭建

jedis的连接池

Redis Jedsi使用方法

Jedis连接池配置参数

Redis:实例结合源码分析Jedis连接池原理以及Jedis连接池的实现