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>

原文地址:https://www.cnblogs.com/dgwblog/p/12302029.html

时间: 2024-10-02 06:27:24

Jedis连接池(实际项目可用)的相关文章

jedis连接池爆满导致的服务不可用

生产环境was线程数300,jedis连接池连接数100. 在业务高峰期,查看日志发现大量could not get a resource from a pool的异常,抓取javacore文件发现was线程大量进入parked状态,查看jedis源码发现连接池底层使用common-pool实现,而common-pool其中有这样一段代码: if (p == null) { if (borrowMaxWaitMillis < 0) { p = idleObjects.takeFirst(); }

Java与redis交互、Jedis连接池JedisPool

Java与redis交互比较常用的是Jedis. 先导入jar包: commons-pool2-2.3.jar jedis-2.7.0.jar 基本使用: public class RedisTest1 { public static void main(String[] args) { Jedis jedis = new Jedis("localhost",6379); jedis.set("username","chichung"); jed

jedis连接池详解(Redis)

原子性(atomicity): 一个事务是一个不可分割的最小工作单位,事务中包括的诸操作要么都做,要么都不做. Redis所有单个命令的执行都是原子性的,这与它的单线程机制有关: Redis命令的原子性使得我们不用考虑并发问题,可以方便的利用原子性自增操作INCR实现简单计数器功能; 单机模式: package com.ljq.utils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import

Jedis连接池的使用

所需jar:jedis-2.1.0.jar和commons-pool-1.5.4.jar Jedis操作步骤如下: 1->获取Jedis实例需要从JedisPool中获取: 2->用完Jedis实例需要返还给JedisPool: 3->如果Jedis在使用过程中出错,则也需要还给JedisPool: 代码如下: package com.ljq.utils; import redis.clients.jedis.Jedis; import redis.clients.jedis.Jedis

Jedis连接池的使用(转)

http://www.cnblogs.com/linjiqin/archive/2013/06/14/3135248.html 所需jar:jedis-2.1.0.jar和commons-pool-1.5.4.jar Jedis操作步骤如下:1->获取Jedis实例需要从JedisPool中获取:2->用完Jedis实例需要返还给JedisPool:3->如果Jedis在使用过程中出错,则也需要还给JedisPool: [java] view plaincopy package com.

Jedis(连接池)常见操作

Jedis的最为常见的操作.主要包括常用的列表(list).集合(set).有序集合(sorted set).哈希表(hash)等数据结构,以及其他特性支持. 参考资料:http://hello-nick-xu.iteye.com/blog/search?query=Jedis <一>. 使用list: 可以使用列表模拟队列(queue).堆栈(stack),并且支持双向的操作(L或者R). 1. 右边入队: Java代码   jedis.rpush("userList",

Jedis连接池

原文地址:https://www.cnblogs.com/djlindex/p/11602882.html

HttpClient 4.3连接池参数配置及源码解读

目前所在公司使用HttpClient 4.3.3版本发送Rest请求,调用接口.最近出现了调用查询接口服务慢的生产问题,在排查整个调用链可能存在的问题时(从客户端发起Http请求->ESB->服务端处理请求,查询数据并返回),发现原本的HttpClient连接池中的一些参数配置可能存在问题,如defaultMaxPerRoute.一些timeout时间的设置等,虽不能确定是由于此连接池导致接口查询慢,但确实存在可优化的地方,故花时间做一些研究.本文主要涉及HttpClient连接池.请求的参数

再淡spring jdbc 连接池断开重连设置

先看一段错误日志: ### Error querying database. Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed. ### The error may exist in file ----] ### The error may involve ..... ### The error occ