一、配置文件

1. db.properties配置文件
#IP地址
redis.ip = 127.0.0.1
#端口号
redis.port=
#最大连接数
redis.max.total=
#最大空闲数
redis.max.idle=
#最小空闲数
redis.min.idle=
#效验使用可用连接
redis.test.borrow=true
#效验归还可用连接
redis.test.return=false 2. pom.xml文件
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
 

二、java代码

public class RedisPool {
private static JedisPool pool ; //jedis连接池
private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total","")); //最大连接数
private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle","")); //最大空闲状态
private static Integer minIdle =Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle","")); //最小空闲状态 private static Boolean testOnBorrow =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow","true")); //验证从连接池拿出的jedis实例,一定可用
private static Boolean testOnReturn =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return","true")); //验证还回连接池的jedis实例,一定可用 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.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn); config.setBlockWhenExhausted(true); //连接耗尽时是否阻塞,false抛出异常;true阻塞到超时。默认true pool = new JedisPool(config,redisIp,redisPort,*);
} static{
initPool();
} public static Jedis getJedis(){
return pool.getResource();
} /**
* redis不正常不可用,将其废弃,最新版本直接将此连接销毁jedis.close();
* @param jedis
*/
public static void returnBrokenResource(Jedis jedis){
pool.returnBrokenResource(jedis); //最新版本已废弃
} public static void returnResource(Jedis jedis){
pool.returnResource(jedis); //最新版本已废弃
}
}

三。redis相关类介绍

  (1)JedisPool

    JedisPool保证资源在一个可控范围内,并且提供了线程安全,Jedis连接就是资源,JedisPool管理的就是Jedis连接。此类只有三个方法普通方法,大量的构造器,构造器根据不同的连接配置信息,生成对应的资源池。可以很好地重复利用Jedis,减少new的次数,从而提高效率。

  (2)JedisPoolConfig

    资源池的配置信息,JedisPoolConfig只有一个构造器,大部分配置信息都在继承的类GenericObjectPoolConfigBaseObjectPoolConfig中。配置最大连接数,最大/小空闲等待数,是否效验生成/归还的连接有效等等。JedisPool其中JedisPoolConfig即是JedisPool构造器所要出入的配置对象,根据JedisPoolConfig配置信息,进行资源池管理。

基本配置如下:

setBlockWhenExhausted(boolean blockWhenExhausted)
当池中的资源耗尽时是否进行阻塞,设置false直接报错,true表示会一直等待,直到有可用资源 setEvictionPolicyClassName(String evictionPolicyClassName)
设置逐出策略,默认策略为
"org.apache.commons.pool2.impl.DefaultEvictionPolicy" setFairness(boolean fairness)
当从池中获取资源或者将资源还回池中时 是否使用java.util.concurrent.locks.ReentrantLock.ReentrantLock 的公平锁机制,默认为false setJmxEnabled
设置是否启用JMX,默认true setJmxNameBase(String jmxNameBase)
设置JMX基础名 setJmxNamePrefix(String jmxNamePrefix)
设置JMX前缀名,默认值pool setLifo(boolean lifo)
设置连接对象是否后进先出,默认true setMaxIdle(int maxIdle)
设置最大空闲连接数,默认为8 setMaxTotal(int maxTotal)
设置最大连接数,默认18个 setMaxWaitMillis(long maxWaitMillis)
获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认- setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis)
设置连接最小的逐出间隔时间,默认1800000毫秒 setMinIdle(int minIdle)
设置无连接时池中最小的连接个数,默认连接0 setNumTestsPerEvictionRun(int numTestsPerEvictionRun)
每次逐出检查时,逐出连接的个数 setSoftMinEvictableIdleTimeMillis(softMinEvictableIdleTimeMillis);
对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 setTestOnBorrow(boolean testOnBorrow)
从池中获取连接时是否测试连接的有效性,默认false setTestOnCreate(boolean testOnCreate)
在连接对象创建时测试连接对象的有效性,默认false setTestOnReturn(boolean testOnReturn)
在连接对象返回时,是否测试对象的有效性,默认false setTestWhileIdle(boolean testWhileIdle)
在连接池空闲时是否测试连接对象的有效性,默认false setTimeBetweenEvictionRunsMillis(
long timeBetweenEvictionRunsMillis)
设置连接对象有效性扫描间隔,设置为-,则不运行逐出线程

  (3)Jedis

  Jedis是Redis官方推荐的Java连接开发工具。要在Java开发中使用好Redis中间件。Jedis有大量的方法,都是进行redis数据库的crud操作。Jedis是有JedisPool连接池创建的。

import com.mmall.common.RedisPool;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis; /**
* 封装单机redis常用API方法
*/
@Slf4j
public class RedisPoolUtil { /**
* 设置对应key的有效期
* @param key
* @param exTime 有效期,单位秒
* @return
*/
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("set key:{} exTime:{} value:{} error",key,exTime,e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
} /**
* string 添加,存在有效期exTime
* @param key 键
* @param value 值
* @param exTime 有效期,单位秒
* @return
*/
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("set key:{} exTime:{} value:{} error",key,exTime,value,e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
} /**
* string 添加
* @param key
* @param value
* @return
*/
public static String set(String key, String value){
Jedis jedis = null;
String result = null;
try{
jedis = RedisPool.getJedis();
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;
} /**
* string 获取
* @param key
* @return
*/
public static String get(String key){
Jedis jedis = null;
String result = null;
try{
jedis = RedisPool.getJedis();
result = jedis.get(key);
}catch (Exception e){
log.error("get key:{} error",key,e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
} /**
* stirng 删除
* @param key
* @return
*/
public static Long del(String key){
Jedis jedis = null;
Long result = null;
try{
jedis = RedisPool.getJedis();
result = jedis.del(key);
}catch (Exception e){
log.error("get key:{} error",key,e);
RedisPool.returnBrokenResource(jedis);
return result;
}
RedisPool.returnResource(jedis);
return result;
}
}

redis单机连接池的更多相关文章

  1. redis运用连接池报错解决

    redis使用连接池报错解决redis使用十几小时就一直报异常 redis.clients.jedis.exceptions.JedisConnectionException: Could not g ...

  2. nodejs + redis/mysql 连接池问题

    nodejs + redis/mysql 连接池问题 需不需要连接池 连接池的作用主要是较少每次临时建立连接所带来的开销.初步一看,nodejs运行单线程上,它不能同时使用多个连接,乍一看是不需要连接 ...

  3. Redis Java连接池调研

    Redis Java连接池调研 线上服务,由于压力大报错RedisTimeOut,但是需要定位到底问题出现在哪里? 查看Redis慢日志,slowlog get 发现耗时最大的也是11000us也就是 ...

  4. python redis之连接池的原理

    python redis之连接池的原理 转载地址 什么是连接池 通常情况下, 当我们需要做redis操作时, 会创建一个连接, 并基于这个连接进行redis操作, 操作完成后, 释放连接, 一般情况下 ...

  5. Redis 配置连接池,redisTemplate 操作多个db数据库,切换多个db,解决JedisConnectionFactory的设置连接方法过时问题。(转)

    环境 springmvc jdk1.8 maven redis.properties配置文件 #redis setting redis.host=localhost redis.port=6379 r ...

  6. Redis缓存连接池管理

    import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.util.Assert;import ...

  7. java客户端Jedis操作Redis Sentinel 连接池

    pom配置: <dependency> <groupId>org.springframework.data</groupId> <artifactId> ...

  8. redis mysql 连接池 之 golang 实现

    1 mysql 连接池代码 package lib import ( "database/sql" "fmt" "strconv" &quo ...

  9. python操作Redis安装、支持存储类型、普通连接、连接池

    一.python操作redis安装和支持存储类型 安装redis模块 pip3 install redis 二.Python操作Redis之普通连接 redis-py提供两个类Redis和Strict ...

随机推荐

  1. P4781 拉格朗日插值

    #include <bits/stdc++.h> using namespace std; #define rep(i,a,n) for (int i=a;i<n;i++) #def ...

  2. MySQL新特性文档型数据库

    mongodb在文档型数据库这方面一直做的很好,也发展了很多年,MySQL作为一个比较大众的数据库也慢慢支持了该特性,下面介绍一下MySQL支持文档型数据库的简单操作. 环境: 主机名 IP 系统 软 ...

  3. ZOJ 2592 Think Positive ——(xjbg)

    做法是,先求出前缀和pre.然后枚举端点i,[i+1,n]中pre最小的找出来,减去pre[i-1]大于0,这是第一个条件:第二个条件是,从i开始的后缀和和i之前的最小的一个pre相加大于0.只要满足 ...

  4. 2016"百度之星" - 初赛(Astar Round2A)1001 All X(HDU5690)——找循环节|快速幂

    一个由m个数字x组成的新数字,问其能否mod k等于c. 先提供第一种思路,找循环节.因为每次多一位数都是进行(t*10+x)mod k(这里是同余模的体现),因为x,k都确定,只要t再一样得到的答案 ...

  5. 通过Nginx部署flask项目

    用Flask开发之后,很多人,喜欢用nohup python manage.py & 这样的形式,放到后台运行,其实这样只是个发开模式,很简陋,无法支持并发,进程监控等功能.所以采用nginx ...

  6. IdentityServer4入门二

    在 IdentityServer4入门一 我们准备好了一个认证的服务端,这里做一个需要保护的API服务 首先,向解决方案新增一个项目.我们同样使用入门一的方式新增一个asp.net core Web程 ...

  7. zabbix :web 界面显示的监控项值为0或者空

    [参考文章]:[错误汇总]zabbix_get 的值一直为 0 1. 问题现象 zabbix 版本:3.4: server 端部署在 192.168.145.134 ,agent 节点部署在 192. ...

  8. pod package 生成 Framework

    pod package 生成 Framework pod package 是 cocoapods 的一个插件,如果没有的话使用以下命令安装: sudo gem install cocoapods-pa ...

  9. Flask-SQLAlchemy操作

    Flask-SQLAlchemy   SQLAlchemy 一. 介绍 SQLAlchemy是一个基于Python实现的ORM框架.该框架建立在 DB API之上,使用关系对象映射进行数据库操作,简言 ...

  10. ForkJoinPool 源码分析

    ForkJoinPool ForkJoinPool 是一个运行 ForkJoinTask 任务.支持工作窃取和并行计算的线程池 核心参数+创建实例 // 工作者线程驻留任务队列索引位 static f ...