这里介绍一下,这个工具类不是在分布式环境下来用的,就是我们平常使用的,单机状况下,为什么博主开头要这样强调呢?因为,之前见网上有些博友有这样封装的,也有RedisShardedPoolUtil 封装的 ,刚开始不是很明白,现在知道了,后者是在分布式的场景下使用的。好啦。现在让我们来code了~~~~

首先来大致介绍下吧,redis的工具类很简单,就是先创建一个redis连接池(引入第三方的jar包就行),像数据库连接池一样,然后,需要的参数写在配置文件中,创建连接池这个类  RedisPool.java   需要两个方法,一个从连接池得到资源redis,一个是放回redis资源。

然后,再写一个专门操控redis的  ‘增删改查’  方法。这就可以。 不多说,老规矩,开箱即用。上代码!!!

pom.xml
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
<!--加速开发的工具,可以省略getset和日志类,只需要注解就可以-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.6</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency> <dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-core</artifactId>
<version>1.1.2</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.logback-extensions</groupId>
<artifactId>logback-ext-spring</artifactId>
<version>0.1.1</version>
</dependency>
</dependencies>
RedisPool.java
这里强调一下,redis的pom是2.9 所以回收资源是close方法,之前的pool.returnBrokenResource(jedis);
和pool.returnResource(jedis);已经被官方弃用了。这点注意。
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* Created by 敲代码的卡卡罗特
*/
@Slf4j
public class RedisPool {
private static JedisPool pool;//jedis连接池
private static Integer maxTotal = Integer.parseInt(PropertiesUtil.getProperty("redis.max.total","20")); //最大连接数
private static Integer maxIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.max.idle","20"));//在jedispool中最大的idle状态(空闲的)的jedis实例的个数
private static Integer minIdle = Integer.parseInt(PropertiesUtil.getProperty("redis.min.idle","20"));//在jedispool中最小的idle状态(空闲的)的jedis实例的个数 private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.borrow","true"));//在borrow一个jedis实例的时候,是否要进行验证操作,如果赋值true。则得到的jedis实例肯定是可以用的。
private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.test.return","true"));//在return一个jedis实例的时候,是否要进行验证操作,如果赋值true。则放回jedispool的jedis实例肯定是可以用的。 private static String redisIp = PropertiesUtil.getProperty("redis1.ip");
private static Integer redisPort = Integer.parseInt(PropertiesUtil.getProperty("redis1.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,1000*2);
} static{
initPool();
} public static Jedis getJedis(){
return pool.getResource();
} public static void close(Jedis jedis){
try {
if (jedis != null) {
jedis.close();
}
} catch (Exception e) {
log.error("return redis resource exception", e);
}
} public static void main(String[] args) {
Jedis jedis = pool.getResource();
jedis.set("lzh","liuzhonghua");
close(jedis); pool.destroy();//临时调用,销毁连接池中的所有连接
System.out.println("program is end"); } }

RedisPoolUtil.java   代码很简单  方法就不一一介绍了。看不懂的留言问我
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis; /**
* Created by 敲代码的卡卡罗特
*/
@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("expire key:{} error",key,e);
RedisPool.close(jedis);
return result;
}
RedisPool.close(jedis);
return result;
} //exTime的单位是秒
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("setex key:{} value:{} error",key,value,e);
RedisPool.close(jedis);
return result;
}
RedisPool.close(jedis);
return result;
} 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.close(jedis);
return result;
}
RedisPool.close(jedis);
return result;
} 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.close(jedis);
return result;
}
RedisPool.close(jedis);
return result;
} 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("del key:{} error",key,e);
RedisPool.close(jedis);
return result;
}
RedisPool.close(jedis);
return result;
} public static void main(String[] args) {
Jedis jedis = RedisPool.getJedis(); jedis.setex("name",100,"lzh"); System.out.println("end"); } }
再配上读取配置文件的工具类  PropertiesUtil  需要注意的是,这个文件名写死了,就从这一个文件名中读取参数。你也可以再封装一下。
我这里就不麻烦了。
PropertiesUtil.java
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties; /**
* Created by 敲代码的卡卡罗特
*/
@Slf4j
public class PropertiesUtil { private static Properties props; static {
String fileName = "mmall.properties";
props = new Properties();
try {
props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
} catch (IOException e) {
log.error("配置文件读取异常",e);
}
} public static String getProperty(String key){
String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
return null;
}
return value.trim();
} public static String getProperty(String key,String defaultValue){ String value = props.getProperty(key.trim());
if(StringUtils.isBlank(value)){
value = defaultValue;
}
return value.trim();
} public static void main(String[] arg){
System.out.println(PropertiesUtil.getProperty("redis.port"));
} }

mmall.properties

#redis config start

redis1.ip=127.0.0.1
redis1.port=6379 ##Tips:以上redis1和redis2的ip和port改成你自己的哟 #最大连接数
redis.max.total=20 #最大空闲数
redis.max.idle=10 #最小空闲数
redis.min.idle=2 #从jedis连接池获取连接时,校验并返回可用的连接
redis.test.borrow=true #把连接放回jedis连接池时,校验并返回可用的连接
redis.test.return=false #redis config end
ok,大功告成
 


redis工具类 ----RedisPoolUtil的更多相关文章

  1. Redis操作Hash工具类封装,Redis工具类封装

    Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...

  2. Redis操作字符串工具类封装,Redis工具类封装

    Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...

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

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

  4. SpringBoot整合Redis及Redis工具类撰写

            SpringBoot整合Redis的博客很多,但是很多都不是我想要的结果.因为我只需要整合完成后,可以操作Redis就可以了,并不需要配合缓存相关的注解使用(如@Cacheable). ...

  5. redistemplate优雅地操作redis redis 工具类

    参考:https://www.cnblogs.com/superfj/p/9232482.html redis 工具类 package com.service; import org.springfr ...

  6. java的redis工具类

    package com.mracale.sell.utils; /** * @Auther: Mracale */ import org.springframework.beans.factory.a ...

  7. Redis 工具类

    项目里的Redis 工具类,写下来以备后用 public class RedisConnector { public class RedisParseResult<T> { public ...

  8. Redis 工具类 java 实现的redis 工具类

    最近了解了一下非关系型数据库 redis 会使用简单的命令 在自己本地电脑 使用时必须先启动服务器端 在启动客户端 redis 简介 Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内 ...

  9. Java操作Redis工具类

    依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...

随机推荐

  1. [转帖]DevOps/TestOps概念

    发现收藏不好用..还是转吧.. https://www.cnblogs.com/fnng/p/8232410.html DevOps/TestOps概念 2018-01-07 22:02 by 虫师, ...

  2. ionic2中如何使用自动生成器

    ionic generator是命令行的功能,ionic2自动帮我们创建应用程序,从而节省了大量的时间,并增加我们的速度来开发一个项目的关键部分. ionic generator使我们可以自动创建以下 ...

  3. Linux基础学习(9)--文件系统管理

    第九章——文件系统管理 一.回顾分区和文件系统 1.分区类型: 2.分区表示方法: 3.文件系统: 二.文件系统常用命令 1.df命令.du命令.fsck命令和dump2fs命令: (1)文件系统查看 ...

  4. Linux基础学习(5)--文本编辑器Vim

    第五章——文本编辑器Vim 一. Vim常用操作 1.Vim简介:              Vim是一个功能强大的全屏幕文本编辑器,是Linux/UNIX上最常用的文本编辑器,它的作用是建立.编辑. ...

  5. AntDesign从入门到精通

    第一 设计原则 官方网址:https://ant.design/index-cn 需要做出更好的设计决策,给予研发团队一种高确定性.低熵值的研发状态.同时,不同设计者在充分理解业务述求后,基于 Ant ...

  6. jquery 選擇器

    jquery 選擇器有: 元素選擇器: $("p")選擇所有<p> $("p.intro")選擇所有class=“intro”的<p> ...

  7. Lodop如何设置预览后导出带背景的图,打印不带背景图

    Lodop中的ADD_PRINT_SETUP_BKIMG,可以加载上背景图,该背景图在预览的时候可以显示也可以不显示,打印可以打印出来也可以不打印出来.一般套打,都是不打印背景图的,比如一些快递的快递 ...

  8. BZOJ2135 刷题计划(贪心+二分)

    相邻数作差后容易转化成将这些数最多再切m刀能获得的最小偏差值.大胆猜想化一波式子可以发现将一个数平均分是最优的.并且划分次数越多能获得的偏差值增量越小.那么就可以贪心了:将所有差扔进堆里,每次取出增量 ...

  9. Hibernate表关系03

    一. 一对多映射 1.基本应用 1.1 准备项目 创建项目:hibernate-02-relation 引入jar,同前一个项目 复制实体(客户).映射.配置.工具类 1.2 创建订单表 表名: t_ ...

  10. LightOJ - 1356 Prime Independence (二分图 最大独立集 素数打表)

    题意: 给你一个集合,让你从这个集合中挑选出几个数,使得这几个数中任意两个数相除后的值不能为素数 即挑选出来的这几个数不能互相冲突 最大独立集 = 所有点数 - 最大匹配数 呵..呵...原先用的二维 ...