Redis,JedisPool工具类
Redis,JedisPool工具类
导入相关依赖:
commons-pool2-2.3.jar
jedis-2.7.0.jar
1、JedisPool
package com.yj.test.javaBases.testJedis;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCommands;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class TestJedis {
public static final Logger logger = LoggerFactory.getLogger(TestJedis.class);
// Jedispool
JedisCommands jedisCommands;
JedisPool jedisPool;
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
String ip = "192.168.x.x";
int port = 6379;
int timeout = 2000;
public TestJedis() {
// 初始化jedis
// 设置配置
jedisPoolConfig.setMaxTotal(1024);
jedisPoolConfig.setMaxIdle(100);
jedisPoolConfig.setMaxWaitMillis(100);
jedisPoolConfig.setTestOnBorrow(false);//jedis 第一次启动时,会报错
jedisPoolConfig.setTestOnReturn(true);
// 初始化JedisPool
jedisPool = new JedisPool(jedisPoolConfig, ip, port, timeout);
//
Jedis jedis = jedisPool.getResource();
jedisCommands = jedis;
}
public void setValue(String key, String value) {
this.jedisCommands.set(key, value);
}
public String getValue(String key) {
return this.jedisCommands.get(key);
}
public static void main(String[] args) {
TestJedis testJedis = new TestJedis();
testJedis.setValue("testJedisKey", "testJedisValue");
logger.info("get value from redis:{}",testJedis.getValue("testJedisKey"));
}
}
详细配置解释代码
package com.test;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
//Redis服务器IP
private static String ADDR = "192.168.0.41";
//Redis的端口号
private static int PORT = 6379;
//访问密码
private static String AUTH = "admin";
//可用连接实例的最大数目,默认值为8;
//如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_TOTAL = 8;
//最小空闲连接数, 默认0
private static int MIN_IDLE=0;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
//最大空闲连接数, 默认8个
private static int MAX_IDLE = 8;
//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间, 默认-1
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = -1;
private static int TIMEOUT = 10000;
//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
private static boolean BLOCK_WHEN_EXHAUSTED = false;
//设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
private static String EVICTION_POLICY_CLASSNAME="org.apache.commons.pool2.impl.DefaultEvictionPolicy";
//是否启用pool的jmx管理功能, 默认true
private static boolean JMX_ENABLED=true;
//MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
private static String JMX_NAME_PREFIX="pool";
//是否启用后进先出, 默认true
private static boolean LIFO=true;
//逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
private static long MIN_EVICTABLE_IDLE_TIME_MILLIS=1800000L;
//对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断 (默认逐出策略)
private static long SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS=1800000L;
//每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
private static int NUM_TESTS_PER_EVICYION_RUN=3;
//在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
//在获取连接的时候检查有效性, 默认false
private static boolean TEST_ON_BORROW = false;
//在空闲时检查有效性, 默认false
private static boolean TEST_WHILEIDLE=false;
//逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
private static long TIME_BERWEEN_EVICTION_RUNS_MILLIS=-1;
private static JedisPool jedisPool = null;
/**
* 初始化Redis连接池
*/
static {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setBlockWhenExhausted(BLOCK_WHEN_EXHAUSTED);
config.setEvictionPolicyClassName(EVICTION_POLICY_CLASSNAME);
config.setJmxEnabled(JMX_ENABLED);
config.setJmxNamePrefix(JMX_NAME_PREFIX);
config.setLifo(LIFO);
config.setMaxIdle(MAX_IDLE);
config.setMaxTotal(MAX_TOTAL);
config.setMaxWaitMillis(MAX_WAIT);
config.setMinEvictableIdleTimeMillis(MIN_EVICTABLE_IDLE_TIME_MILLIS);
config.setMinIdle(MIN_IDLE);
config.setNumTestsPerEvictionRun(NUM_TESTS_PER_EVICYION_RUN);
config.setSoftMinEvictableIdleTimeMillis(SOFT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
config.setTestOnBorrow(TEST_ON_BORROW);
config.setTestWhileIdle(TEST_WHILEIDLE);
config.setTimeBetweenEvictionRunsMillis(TIME_BERWEEN_EVICTION_RUNS_MILLIS);
jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Jedis实例
* @return
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 释放jedis资源
* @param jedis
*/
public static void close(final Jedis jedis) {
if (jedis != null) {
jedis.close();
}
}
}
2、Jedis工具类
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisUtil {
//服务器IP地址
private static String ADDR = "ip";
//端口
private static int PORT = 6379;
//密码
private static String AUTH = "";
//连接实例的最大连接数
private static int MAX_ACTIVE = 1024;
//控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = 200;
//等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException
private static int MAX_WAIT = 10000;
//连接超时的时间
private static int TIMEOUT = 10000;
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = true;
private static JedisPool jedisPool = null;
//数据库模式是16个数据库 0~15
public static final int DEFAULT_DATABASE = 0;
/**
* 初始化Redis连接池
*/
static {
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, PORT, TIMEOUT, null, DEFAULT_DATABASE);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Jedis实例
*/
public synchronized static Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
System.out.println("redis--服务正在运行: " + resource.ping());
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public synchronized Jedis getJedisPublic() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
System.out.println("redis--服务正在运行: " + resource.ping());
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/***
*
* 释放资源
*/
public static void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
public static void main(String[] args) {
Jedis jedis = RedisUtil.getJedis();
jedis.lpush("site-list", "Runoob");
jedis.lpush("site-list", "Google");
jedis.lpush("site-list", "Taobao");
jedis.hset("OverDrive", "vehicle", "1");
jedis.hset("OverDrive", "car", "1");
jedis.expire("OverDrive", 60);
jedis.set("runoobkey", "www.runoob.com");
// 获取存储的数据并输出
System.out.println("redis 存储的字符串为: " + jedis.get("runoobkey"));
RedisUtil.returnResource(jedis);
}
}
Redis,JedisPool工具类的更多相关文章
- spring boot 结合Redis 实现工具类
自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...
- 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!
转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...
- redis分布式工具类 ----RedisShardedPoolUtil
这个是redis分布式的工具类,看非分布式的看 这里 说一下redis的分布式,分布式,无疑,肯定不是一台redis服务器.假如说,我们有两台redis服务器,一个6379端口,一个6380端口.那 ...
- redis缓存工具类,提供序列化接口
1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...
- springMVC+redis+redis自定义工具类 的配置
1. maven项目,加入这一个依赖包即可, <dependency> <groupId>redis.clients</groupId> <artifactI ...
- redis缓存工具类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis ...
- RedisPool操作Redis,工具类实例
redis.properties 配置文件内容 redis.pool.maxActive=100redis.pool.maxIdle=20redis.pool.maxWait=3000redis.po ...
- Openresty最佳案例 | 第8篇:RBAC介绍、sql和redis模块工具类
转载请标明出处: http://blog.csdn.net/forezp/article/details/78616738 本文出自方志朋的博客 RBAC介绍 RBAC(Role-Based Acce ...
- redis工具类 ----RedisPoolUtil
这里介绍一下,这个工具类不是在分布式环境下来用的,就是我们平常使用的,单机状况下,为什么博主开头要这样强调呢?因为,之前见网上有些博友有这样封装的,也有RedisShardedPoolUtil 封装的 ...
随机推荐
- cmd命令符大全
cmd命令大全(第一部分) winver---------检查Windows版本 wmimgmt.msc----打开windows管理体系结构(WMI) wupdmgr--------windows更 ...
- Linux性能优化:CPU性能分析工具--vmstat
Blog:博客园 个人 目录 参数说明 输出信息说明 procs memory swap io system cpu 示例 vmstat是Virtual Meomory Statistics(虚拟内存 ...
- [php]配置文件中的超时时间
概要 php.ini l max_execution_time l max_input_time php-fpm.conf l process_control_timeout l reques ...
- vue的绑定属性v-bind
v-bind的简略介绍 v-bind用于绑定一个或多个属性值,或者向另一个组件传递props值.目前,个人所用之中,更多的是使用于图片的链接src,a标签中的链接href,还有样式以及类的一些绑定,以 ...
- 敏捷史话(二):Scrum社区的悲剧性损失——Mike Beedle
2018年3月23日,在美国的芝加哥发生了一起意外刺杀事件.一名男子刺杀了一位首席执行官,而这位不幸的首席执行官就是<敏捷宣言>的合著者--Mike Beedle.Mike 的这场意外令 ...
- JavaScript基础知识梳理
一.简单数据类型 Number.String.Boolean.Undefined.Null 1.Number: 方法: toPrecision( ) 返回指定长度的数字(范围是1到100) toFix ...
- Logstash学习之路(五)使用Logstash抽取mysql数据到kakfa
一.Logstash对接kafka测通 说明: 由于我这里kafka是伪分布式,且kafka在伪分布式下,已经集成了zookeeper. 1.先将zk启动,如果是在伪分布式下,kafka已经集成了zk ...
- 2020 年度编程语言排行榜出炉!C 语言称霸,Java 遭遇滑铁卢…….
最近,TIOBE 发布了过去一年的编程语言排行榜: 数据来源TIOBE: https://www.tiobe.com/tiobe-index/ TIOBE介绍: TIOBE编程语言索引是编程语言流行程 ...
- 十八般武艺玩转GaussDB(DWS)性能调优:路径干预
摘要:路径生成是表关联方式确定的主要阶段,本文介绍了几个影响路径生成的要素:cost_param, scan方式,join方式,stream方式,并从原理上分析如何干预路径的生成. 一.cost模型选 ...
- 【Flutter】容器类组件之Scaffold、TabBar、底部导航
前言 一个完整的路由页可能会包含导航栏.抽屉菜单(Drawer)以及底部Tab导航菜单等.Flutter Material组件库提供了一些现成的组件来减少开发任务.Scaffold是一个路由页的骨架, ...