导入相关依赖:

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. python图片的读取保存

    #coding:utf-8 from PIL import Image import matplotlib.pyplot as plt img=Image.open("F:\\Upan\\源 ...

  2. Spring Boot Starters

    Spring Boot Starters 摘自 https://www.nosuchfield.com/2017/10/15/Spring-Boot-Starters/ 2017-10-15 Spri ...

  3. SSM框架整合模板

    SSM框架整合--MAVEN依赖 spring方面(包含了springmvc): spring-webmvc:spring与mvc的整合依赖,主要包括spring的核心包和springmvc需要的包 ...

  4. [Java基础]——String类

    此篇博客主要整理Java中的String类的使用. 一.String    1.1  String 的定义 上图是jdk中对String类的定义,得到的信息有: ①.String类声明为final的, ...

  5. PHP jquer网页打印插件 PrintArea

    <!DOCTYPE html> <head> <meta charset="utf-8"> <meta http-equiv=" ...

  6. Head First 设计模式 —— 09. 模版方法 (Template Method) 模式

    模板方法模式 在一个方法中定义一个算法的骨架,而将一些步骤延迟到子类中.模板方法使得子类可以在不改变算法结构的情况下,重新定义算法中的某些步骤. P289 特点 主导算法框架,并且保护这个算法 P28 ...

  7. Java安全之Weblogic 2016-3510 分析

    Java安全之Weblogic 2016-3510 分析 首发安全客:Java安全之Weblogic 2016-3510 分析 0x00 前言 续前面两篇文章的T3漏洞分析文章,继续来分析CVE-20 ...

  8. Python作业---内置数据类型

    实验2 内置数据类型 实验性质:验证性 一.实验目的 1.掌握内置函数.列表.切片.元组的基本操作: 2.掌握字典.集合和列表表达式的基本操作. 二.实验预备知识 1.掌握Python内置函数的基/本 ...

  9. 【UML】基本介绍与类图(依赖、泛化、实现、关联、聚合、组合关系)

    文章目录 UML基本介绍 UML图 UML类图 类图-依赖关系(Dependence) 类图-泛化关系(generalization) 类图-实现关系(Implementation) 类图-关联关系( ...

  10. kubernets之计算资源

    一  为pod分配cpu,内存以及其他的资源 1.1  创建一个pod,同时为这个pod分配内存以及cpu的资源请求量 apiVersion: v1 kind: Pod metadata: name: ...