导入相关依赖:

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工具类的更多相关文章

  1. spring boot 结合Redis 实现工具类

    自己整理了 spring boot 结合 Redis 的工具类引入依赖 <dependency> <groupId>org.springframework.boot</g ...

  2. 最全的Java操作Redis的工具类,使用StringRedisTemplate实现,封装了对Redis五种基本类型的各种操作!

    转载自:https://github.com/whvcse/RedisUtil 代码 ProtoStuffSerializerUtil.java import java.io.ByteArrayInp ...

  3. redis分布式工具类 ----RedisShardedPoolUtil

    这个是redis分布式的工具类,看非分布式的看  这里 说一下redis的分布式,分布式,无疑,肯定不是一台redis服务器.假如说,我们有两台redis服务器,一个6379端口,一个6380端口.那 ...

  4. redis缓存工具类,提供序列化接口

    1.序列化工具类 package com.qicheshetuan.backend.util; import java.io.ByteArrayInputStream; import java.io. ...

  5. springMVC+redis+redis自定义工具类 的配置

    1. maven项目,加入这一个依赖包即可, <dependency> <groupId>redis.clients</groupId> <artifactI ...

  6. redis缓存工具类

    import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis ...

  7. RedisPool操作Redis,工具类实例

    redis.properties 配置文件内容 redis.pool.maxActive=100redis.pool.maxIdle=20redis.pool.maxWait=3000redis.po ...

  8. Openresty最佳案例 | 第8篇:RBAC介绍、sql和redis模块工具类

    转载请标明出处: http://blog.csdn.net/forezp/article/details/78616738 本文出自方志朋的博客 RBAC介绍 RBAC(Role-Based Acce ...

  9. redis工具类 ----RedisPoolUtil

    这里介绍一下,这个工具类不是在分布式环境下来用的,就是我们平常使用的,单机状况下,为什么博主开头要这样强调呢?因为,之前见网上有些博友有这样封装的,也有RedisShardedPoolUtil 封装的 ...

随机推荐

  1. 【Go】我与sync.Once的爱恨纠缠

    原文链接: https://blog.thinkeridea.com/202101/go/exsync/once.html 官方描述 Once is an object that will perfo ...

  2. jQuery是如何实现?

    jQuery是什么? jQuery就是一个javascript的类库,函数库. jQuery是如何实现的? jQuery采用的是构造函数模式进行开发的,jQuery是一个类 常用的方法(CSS.属性. ...

  3. IT 界那些朗朗上口的“名言

    中国有很多古代警世名言,朗朗上口,凝聚了很多故事与哲理.硅谷的互联网公司里头也有一些这样的名言,凝聚了很多公司价值观和做事的方法,对于很多程序员来说,其影响潜移默化.这里收集了一些,如下. Stay ...

  4. Modbus 报文

    Tx:002366-02 10 00 02 00 04 08 00 0A 00 14 00 1E 00 28 F6 A7 02: 地址位 -- Slave ID 10: 功能码 -- Function ...

  5. 一文彻底吃透MyBatis源码!!

    写在前面 随着互联网的发展,越来越多的公司摒弃了Hibernate,而选择拥抱了MyBatis.而且,很多大厂在面试的时候喜欢问MyBatis底层的原理和源码实现.总之,MyBatis几乎成为了Jav ...

  6. 利用github使自己的域名绑定CSDN博客

    首先你要有一个GitHub账号和一个域名 在你自己GitHub账号中创建一个仓库 ​ 在仓库里创建一个index.html的文件 ​ ​ <!DOCTYPE html> <html& ...

  7. Unraid修改docker镜像地址&默认启动

    起源 由于Unraid系统每次启动都会清空Docker的镜像地址配置,故需要默认配置镜像地址 方法 添加修改镜像脚本到开机文件中实现 先找一个镜像加速地址,我使用的是阿里云的容器镜像服务 形如 :ht ...

  8. 风炫安全web安全学习第二十八节课 CSRF攻击原理

    风炫安全web安全学习第二十八节课 CSRF攻击原理 CSRF 简介 跨站请求伪造 (Cross-Site Request Forgery, CSRF),也被称为 One Click Attack 或 ...

  9. 【JDBC核心】commons-dbutils

    commons-dbutils 简介 commons-dbutils 是 Apache 组织提供的一个开源 JDBC 工具类库,它是对 JDBC 的简单封装,学习成本极低,并且使用 commons-d ...

  10. mmall商城分类模块总结

    后台分类model的开发具体功能有:添加分类名称,修改分类名称,查询所有子分类,查询父分类以及它下面的子分类(递归) 需要注意的是,在后台管理进行操作的时候,都需要验证当前用户是否是管理员的角色,不管 ...