java端在使用jedispool 连接redis的时候,在高并发的时候经常卡死,或报连接异常,JedisConnectionException,或者getResource 异常等各种问题

在使用jedispool 的时候一定要注意两点

1、 在获取 jedisPool和jedis的时候加上线程同步,保证不要创建过多的jedispool 和 jedis

2、 用完Jedis实例后需要返还给JedisPool

整理了一下redis工具类,通过大量测试和高并发测试的。

package com.util;
 
import org.apache.log4j.Logger;
 
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
 
/**
 * Redis 工具类
 * @author think
 */
public class RedisUtil {
     
    protected static Logger logger = Logger.getLogger(RedisUtil.class);
     
    //Redis服务器IP
    private static String ADDR_ARRAY = FileUtil.getPropertyValue("/properties/redis.properties""server");
     
    //Redis的端口号
    private static int PORT = FileUtil.getPropertyValueInt("/properties/redis.properties""port");
     
    //访问密码
//    private static String AUTH = FileUtil.getPropertyValue("/properties/redis.properties", "auth");
     
    //可用连接实例的最大数目,默认值为8;
    //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
    private static int MAX_ACTIVE = FileUtil.getPropertyValueInt("/properties/redis.properties""max_active");;
     
    //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
    private static int MAX_IDLE = FileUtil.getPropertyValueInt("/properties/redis.properties""max_idle");;
     
    //等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
    private static int MAX_WAIT = FileUtil.getPropertyValueInt("/properties/redis.properties""max_wait");;
 
    //超时时间
    private static int TIMEOUT = FileUtil.getPropertyValueInt("/properties/redis.properties""timeout");;
     
    //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
    private static boolean TEST_ON_BORROW = FileUtil.getPropertyValueBoolean("/properties/redis.properties""test_on_borrow");;
     
    private static JedisPool jedisPool = null;
     
    /**
     * redis过期时间,以秒为单位
     */
    public final static int EXRP_HOUR = 60*60;          //一小时
    public final static int EXRP_DAY = 60*60*24;        //一天
    public final static int EXRP_MONTH = 60*60*24*30;   //一个月
     
    /**
     * 初始化Redis连接池
     */
    private static void initialPool(){
        try {
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_ACTIVE);
            config.setMaxIdle(MAX_IDLE);
            config.setMaxWaitMillis(MAX_WAIT);
            config.setTestOnBorrow(TEST_ON_BORROW);
            jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[0], PORT, TIMEOUT);
        catch (Exception e) {
            logger.error("First create JedisPool error : "+e);
            try{
                //如果第一个IP异常,则访问第二个IP
                JedisPoolConfig config = new JedisPoolConfig();
                config.setMaxTotal(MAX_ACTIVE);
                config.setMaxIdle(MAX_IDLE);
                config.setMaxWaitMillis(MAX_WAIT);
                config.setTestOnBorrow(TEST_ON_BORROW);
                jedisPool = new JedisPool(config, ADDR_ARRAY.split(",")[1], PORT, TIMEOUT);
            }catch(Exception e2){
                logger.error("Second create JedisPool error : "+e2);
            }
        }
    }
     
     
    /**
     * 在多线程环境同步初始化
     */
    private static synchronized void poolInit() {
        if (jedisPool == null) { 
            initialPool();
        }
    }
 
     
    /**
     * 同步获取Jedis实例
     * @return Jedis
     */
    public synchronized static Jedis getJedis() { 
        if (jedisPool == null) { 
            poolInit();
        }
        Jedis jedis = null;
        try 
            if (jedisPool != null) { 
                // 从池中获取一个Jedis对象
                jedis = jedisPool.getResource();
            }
        catch (Exception e) { 
            logger.error("Get jedis error : "+e);
        }finally{
            returnResource(jedis);
        }
        return jedis;
    
     
     
    /**
     * 释放jedis资源
     * @param jedis
     */
    public static void returnResource(final Jedis jedis) {
        if (jedis != null && jedisPool !=null) {
            jedisPool.returnResource(jedis);
        }
    }
     
     
    /**
     * 设置 String
     * @param key
     * @param value
     */
    public static void setString(String key ,String value){
        try {
            value = StringUtil.isEmpty(value) ? "" : value;
            getJedis().set(key,value);
        catch (Exception e) {
            logger.error("Set key error : "+e);
        }
    }
     
    /**
     * 设置 过期时间
     * @param key
     * @param seconds 以秒为单位
     * @param value
     */
    public static void setString(String key ,int seconds,String value){
        try {
            value = StringUtil.isEmpty(value) ? "" : value;
            getJedis().setex(key, seconds, value);
        catch (Exception e) {
            logger.error("Set keyex error : "+e);
        }
    }
     
    /**
     * 获取String值
     * @param key
     * @return value
     */
    public static String getString(String key){
        if(getJedis() == null || !getJedis().exists(key)){
            return null;
        }
        return getJedis().get(key);
    }
     
}

jedispool 连 redis的更多相关文章

  1. Jedis/JedisPool和Redis数据类型与特性

    1.介绍Jedis Jedis 是 Redis 的 java 版本客户端,使用Jedis可以连接 Redis的数据库,Jedis连接方式有三种Jedis/JedisPool 连接.ShardedJed ...

  2. spring boot redis缓存JedisPool使用

    spring boot redis缓存JedisPool使用 添加依赖pom.xml中添加如下依赖 <!-- Spring Boot Redis --> <dependency> ...

  3. redis 工具类 单个redis、JedisPool 及多个redis、shardedJedisPool与spring的集成配置

    http://www.cnblogs.com/edisonfeng/p/3571870.html http://javacrazyer.iteye.com/blog/1840161 http://ww ...

  4. 三:Redis连接池、JedisPool详解、Redisi分布式

    单机模式: package com.ljq.utils; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; ...

  5. redis设置密码以及jedisPool设置密码

    转: redis设置密码以及jedisPool设置密码 2019年01月02日 20:24:43 宇文荒雪 阅读数:1118   版权声明:本文为博主原创文章,未经博主允许不得转载. https:// ...

  6. Java与redis交互、Jedis连接池JedisPool

    Java与redis交互比较常用的是Jedis. 先导入jar包: commons-pool2-2.3.jar jedis-2.7.0.jar 基本使用: public class RedisTest ...

  7. redis连接池(JedisPool)资源归还及timeout详解

    转载. https://blog.csdn.net/yaomingyang/article/details/79043019 一.连接池资源类详解都在注释上 package redis.v1.clie ...

  8. redis连接池——JedisPool和JedisCluster的介绍与使用

    目录 Jedis使用方式的介绍 Redis连接池介绍 创建连接池配置文件 单机版的Redis连接池 集群版的Redis连接池 总结 Jedis使用方式的介绍 Jedis就是Java实现的操作Redis ...

  9. (二)Redis之Jedis概念和HelloWorld实现以及JedisPool的使用

    一.Jedis概念 实际开发中,我们需要用Redis的连接工具连接Redis然后操作Redis, 对于主流语言,Redis都提供了对应的客户端: 官网:https://redis.io/clients ...

随机推荐

  1. CMD查看进程ID并查杀进程

    开始-运行,输入CMD打开命令行界面,输入命令netstat -ano 结束该进程C:\>taskkill /f /t /im Wiz.exe 根据进程ID杀 >taskkill /F / ...

  2. pip install mysql-connector 安装出错

    一.MySQL Connector/Python 2.2.3 的变化: 之前 mysql 官方说MySQL Connector/Python 是纯python语言写的,但是呢! 这个问题在2.2.3中 ...

  3. 【死磕Java并发】-----J.U.C之AQS:CLH同步队列

    此篇博客全部源代码均来自JDK 1.8 在上篇博客[死磕Java并发]-–J.U.C之AQS:AQS简单介绍中提到了AQS内部维护着一个FIFO队列,该队列就是CLH同步队列. CLH同步队列是一个F ...

  4. 使用digitalocean搭建v·p·s

    这几天digitalocean开始猛卡,一顿操作之后连不上了=_=遂复习了一下怎么搭vps 准备工作 事先准备好Putty,直接百度搜索下载即可(也可直接使用digitalocean的access c ...

  5. python中sorted方法和列表的sort方法使用详解

    一.基本形式 列表有自己的sort方法,其对列表进行原址排序,既然是原址排序,那显然元组不可能拥有这种方法,因为元组是不可修改的. 排序,数字.字符串按照ASCII,中文按照unicode从小到大排序 ...

  6. jquery $.each 和for 怎么跳出循环(终止本次循环)

    1.for循环中我们使用continue:终止本次循环计入下一个循环,使用break终止整个循环. 2.而在jquery中 $.each则对应的使用return true  和return false ...

  7. Makefile 12——改善编译效率

    从Makefile的角度看,一个可以改善编译效率的地方与其中的隐式规则有关.为了了解make的隐式规则,我们把之前的simple项目的Makefile做一点更改,删除生成.o文件的规则(与隐式规则相对 ...

  8. 巧用set比较大小,缩短时间复杂度

    struct Node { long long a; long long b; long long c; long long num; int i; bool operator < (const ...

  9. 《TCP/IP图解》读书笔记

    看这本书的目的: 了解计算机之间是怎么通信的 熟悉TCP/IP协议 后面就这两个目的进行展开,要达到这两个目的,读这本书,学到了哪些知识. 一.计算机之间是怎么通信的 先来了解下面几个概念,中继器,二 ...

  10. swift百度地图api

    swift使用百度地图api遇到的坑 之前在Android上用过百度地图,以为大概类似,也没仔细看文档,结果被自己坑了 注意事项,http://developer.baidu.com/map/inde ...