Jedis 操作 Redis 工具类
配置类
pom.xml
pom.xml 里配置依赖
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.5.2</version>
</dependency>
application.properties
spring 属性文件 application.properties 里配置 redis 配置项
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=xxxxxxx
#超时时间,毫秒
REDIS_TIMEOUT=1000
#最大连接数
REDIS_MAXTOTAL=1000
#最大空闲连接数
REDIS_MAXIDLE=100
#最小空闲连接数
REDIS_MINIDLE=100
#获取连接时的最大等待毫秒数
REDIS_MAXWAITMILLIS=100
#默认缓存过期时间,单位秒
REDIS_DEFAULT_TIMEOUT=7200
常量配置类
@Configuration
public class Constants { public static String REDIS_HOST;
public static int REDIS_PORT;
public static String REDIS_PASSWORD;
public static int REDIS_TIMEOUT;
public static int REDIS_MAXTOTAL;
public static int REDIS_MAXIDLE;
public static int REDIS_MINIDLE;
public static int REDIS_MAXWAITMILLIS;
public static int REDIS_DEFAULT_TIMEOUT; @Value("${REDIS_HOST}")
public void setREDIS_HOST(String rEDIS_HOST) {
REDIS_HOST = rEDIS_HOST;
} @Value("${REDIS_PORT}")
public void setREDIS_PORT(int rEDIS_PORT) {
REDIS_PORT = rEDIS_PORT;
} @Value("${REDIS_PASSWORD}")
public void setREDIS_PASSWORD(String rEDIS_PASSWORD) {
REDIS_PASSWORD = rEDIS_PASSWORD;
} @Value("${REDIS_TIMEOUT}")
public void setREDIS_TIMEOUT(int rEDIS_TIMEOUT) {
REDIS_TIMEOUT = rEDIS_TIMEOUT;
} @Value("${REDIS_MAXTOTAL}")
public void setREDIS_MAXTOTAL(int rEDIS_MAXTOTAL) {
REDIS_MAXTOTAL = rEDIS_MAXTOTAL;
} @Value("${REDIS_MAXIDLE}")
public void setREDIS_MAXIDLE(int rEDIS_MAXIDLE) {
REDIS_MAXIDLE = rEDIS_MAXIDLE;
} @Value("${REDIS_MINIDLE}")
public void setREDIS_MINIDLE(int rEDIS_MINIDLE) {
REDIS_MINIDLE = rEDIS_MINIDLE;
} @Value("${REDIS_MAXWAITMILLIS}")
public void setREDIS_MAXWAITMILLIS(int rEDIS_MAXWAITMILLIS) {
REDIS_MAXWAITMILLIS = rEDIS_MAXWAITMILLIS;
} @Value("${REDIS_DEFAULT_TIMEOUT}")
public void setREDIS_DEFAULT_TIMEOUT(int rEDIS_DEFAULT_TIMEOUT) {
REDIS_DEFAULT_TIMEOUT = rEDIS_DEFAULT_TIMEOUT;
}
}
工厂类
Jedis工厂类(枚举)
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.zcdog.market.util.Constants; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisDataException; public enum JedisFactory { INSTANCE; private static Logger logger = LoggerFactory.getLogger(JedisFactory.class); private volatile JedisPool pool; /**
* 获取Jedis连接
* @return
*/
public Jedis getConnection() {
if (pool == null) {
synchronized (INSTANCE) {
if (pool == null) {
logger.debug("init jedis pool." + Thread.currentThread().getName());
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxTotal(Constants.REDIS_MAXTOTAL);
poolConfig.setMaxIdle(Constants.REDIS_MAXIDLE);
poolConfig.setMinIdle(Constants.REDIS_MINIDLE);
poolConfig.setMaxWaitMillis(Constants.REDIS_MAXWAITMILLIS);
if (Constants.REDIS_PASSWORD != null && !"".equals(Constants.REDIS_PASSWORD)) {
pool = new JedisPool(poolConfig, Constants.REDIS_HOST, Constants.REDIS_PORT, Constants.REDIS_TIMEOUT, Constants.REDIS_PASSWORD);
}else {
pool = new JedisPool(poolConfig, Constants.REDIS_HOST, Constants.REDIS_PORT, Constants.REDIS_TIMEOUT);
}
}
}
}
return pool.getResource();
} /**
* 处理Jedis连接异常
* 记录日志并返回连接是否中断
* @param jedisException
* @return
*/
public boolean handleJedisException(Exception jedisException) {
if (jedisException instanceof JedisConnectionException) {
logger.error("Redis connection lost.", jedisException);
} else if (jedisException instanceof JedisDataException) {
if ((jedisException.getMessage() != null) && (jedisException.getMessage().indexOf("READONLY") != -1)) {
logger.error("Redis connection is read-only slave.", jedisException);
} else {
return false;
}
} else {
logger.error("Jedis happen exception.", jedisException);
}
return true;
} /**
* 返回Jedis连接到连接池
* 根据连接状态调用不同的返回方法
* @param jedis
* @param exceptionFlag
*/
public void closeResource(Jedis jedis, boolean exceptionFlag) {
try {
if (exceptionFlag) {
pool.returnBrokenResource(jedis);
} else if (!exceptionFlag && jedis != null) {
pool.returnResource(jedis);
}
} catch (Exception e) {
logger.error("Return back jedis failed, will close the jedis.", e);
try {
jedis.quit();
} catch (Exception ex) {
logger.error("Jedis quit error.", ex);
}
try {
jedis.disconnect();
} catch (Exception exd) {
logger.error("Jedis disconnect error.", exd);
}
}
}
}
工具类
Jedis工具类,如果没有适用的方法,可自行添加,仅作示例。
更多可参考:Jedis工具类
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction; public class RedisUtils { private static Logger logger = LoggerFactory.getLogger(RedisUtils.class); private static Jedis getConnection() {
return JedisFactory.INSTANCE.getConnection();
} public static void closeResource(Jedis jedis, boolean exceptionFlag) {
JedisFactory.INSTANCE.closeResource(jedis, exceptionFlag);
} public static boolean handleJedisException(Exception jedisException) {
return JedisFactory.INSTANCE.handleJedisException(jedisException);
} public static void save(String key, String value) {
save(key, value, Constants.REDIS_DEFAULT_TIMEOUT);
} public static void save(String key, String value, int expires) {
Jedis jedis = null;
boolean exceptionFlag = false;
try {
jedis = getConnection();
if (key == null || "".equals(key)) {
return;
}
jedis.setex(key, expires, value);
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error("save redis error:", e);
} finally {
closeResource(jedis, exceptionFlag);
}
} public static String get(String key) {
boolean exceptionFlag = false;
Jedis jedis = null;
String value = null;
try {
jedis = getConnection();
value = jedis.get(key);
return value;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error("get redis error :", e);
return value;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static void delete(String key) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
if (key == null || "".equals(key)) {
return;
}
jedis = getConnection();
jedis.del(key);
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error("delete redis error:", e);
} finally {
closeResource(jedis, exceptionFlag);
}
} public static List<String> mget(String[] keys) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
List<String> list = null;
jedis = getConnection();
list = jedis.mget(keys);
return list;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
return null;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static String hget(String key, String field) {
boolean exceptionFlag = false;
Jedis jedis = null;
String value = null;
try {
jedis = getConnection();
value = jedis.hget(key, field);
return value;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
return value;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static String setnx(String key, String value) {
boolean exceptionFlag = false;
Jedis jedis = null;
String result = null;
try {
jedis = getConnection();
result = jedis.set(key, value, "NX", "EX", 300L);
return result;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
return result;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static void hsetTransaction(String key1, String field1, String value1, String key2, String field2,
String value2, int timeout) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
jedis = getConnection();
Transaction multi = jedis.multi();
multi.hset(key1, field1, value1);
multi.expire(key1, Constants.REDIS_DEFAULT_TIMEOUT); multi.hset(key2, field2, value2);
multi.expire(key2, timeout);
multi.exec();
logger.info("[redis] hsetTransaction success key1: {} field1: {} key2: {} field2: {}", key1, field1, key2,
field2);
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error(" hset hsetTransaction error :", e);
} finally {
closeResource(jedis, exceptionFlag);
} } public static void hsetTransactionWithDeleteV2(String key1, String field1, String value1, String key2,
String field2, String value2, int timeout, String deleteKey) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
jedis = getConnection();
Transaction multi = jedis.multi();
multi.hset(key1, field1, value1);
multi.expire(key1, Constants.REDIS_DEFAULT_TIMEOUT); multi.hset(key2, field2, value2);
multi.expire(key2, timeout);
multi.del(deleteKey);
multi.exec();
logger.info("[redis] hsetTransactionWithDelete success key1: {} field1: {} key2: {} field2: {}", key1,
field1, key2, field2);
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error(" hsetTransactionWithDelete redis error :", e);
} finally {
closeResource(jedis, exceptionFlag);
} } public static Map<?, ?> hgetall(String key) {
boolean exceptionFlag = false;
Jedis jedis = null;
Map<?, ?> value = null;
try {
jedis = getConnection();
value = jedis.hgetAll(key);
return value;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error(" hgetall redis error :", e);
return value;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static void hset(String key, String field, String value) {
hset(key, field, value, Constants.REDIS_DEFAULT_TIMEOUT);
} public static void hset(String key, String field, String value, int expireTime) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
jedis = getConnection();
jedis.hset(key, field, value);
jedis.expire(key, expireTime);
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error(" hset redis error :", e);
} finally {
closeResource(jedis, exceptionFlag);
}
} public static void hdelete(String key, String field) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
jedis = getConnection();
jedis.hdel(key, field);
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error(" hdel redis error :", e);
} finally {
closeResource(jedis, exceptionFlag);
}
} public static boolean hexist(String key, String field) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
jedis = getConnection();
boolean flag = jedis.hexists(key, field);
return flag;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error("hexist redis error:", e);
return false;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static int hlen(String key) {
boolean exceptionFlag = false;
Jedis jedis = null;
try {
jedis = getConnection();
return jedis.hlen(key).intValue();
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error(" hlen redis error :", e);
return 0;
} finally {
closeResource(jedis, exceptionFlag);
}
} public static Set<String> hkeys(String key) {
boolean exceptionFlag = false;
Jedis jedis = null;
Set<String> skey = null;
try {
jedis = getConnection();
skey = jedis.hkeys(key);
return skey;
} catch (Exception e) {
exceptionFlag = handleJedisException(e);
logger.error("hkeys redis error:", e);
return skey;
} finally {
closeResource(jedis, exceptionFlag);
}
} }
Jedis 操作 Redis 工具类的更多相关文章
- Java操作Redis工具类
依赖 jar 包 <dependency> <groupId>redis.clients</groupId> <artifactId>jedis< ...
- redis 工具类 单个redis、JedisPool 及多个redis、shardedJedisPool与spring的集成配置
http://www.cnblogs.com/edisonfeng/p/3571870.html http://javacrazyer.iteye.com/blog/1840161 http://ww ...
- Redis操作Set工具类封装,Java Redis Set命令封装
Redis操作Set工具类封装,Java Redis Set命令封装 >>>>>>>>>>>>>>>>& ...
- Redis操作List工具类封装,Java Redis List命令封装
Redis操作List工具类封装,Java Redis List命令封装 >>>>>>>>>>>>>>>> ...
- Redis操作Hash工具类封装,Redis工具类封装
Redis操作Hash工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>> ...
- Redis操作字符串工具类封装,Redis工具类封装
Redis操作字符串工具类封装,Redis工具类封装 >>>>>>>>>>>>>>>>>>& ...
- redistemplate优雅地操作redis redis 工具类
参考:https://www.cnblogs.com/superfj/p/9232482.html redis 工具类 package com.service; import org.springfr ...
- Java中使用Jedis操作Redis(转载)
整理 1.字符串 添加:set keyname value 查询:get keyname 拼接:append keyname value 删除:del keyname 添加多个: mset keyna ...
- jedis操作redis全指南
package com.wujintao.redis; import java.util.Date; import java.util.HashMap; import java.util.Iterat ...
随机推荐
- [Redis]Redis的五种数据类型与键值/服务器相关命令
-------------------------------------------------------------------------------------- String(字符串):最 ...
- python 关于文件夹的操作
在python中,文件夹的操作主要是利用os模块来实现的, 其中关于文件夹的方法为:os.lister() , os.path.join() , os.path.isdir() # path 表示文 ...
- rest_framework常用设置
1.常用配置 import django_filters from django.db.models import Q from rest_framework.pagination import Pa ...
- SSM商城项目(九)
1. 学习计划 1.Activemq整合springMQ的应用场景 2.添加商品同步索引库 3.商品详情页面动态展示 4.展示详情页面使用缓存 2. Activemq整合spring 2.1. ...
- Kb和KB的区别
- lenet-5
https://blog.csdn.net/happyorg/article/details/78274066 深度学习 CNN卷积神经网络 LeNet-5详解 2017年10月18日 16:04:3 ...
- [leetcode]96. Unique Binary Search Trees给定节点形成不同BST的个数
Given n, how many structurally unique BST's (binary search trees) that store values 1 ... n? Input: ...
- java_24 FileOutputStream类和FileInputStream类
1.OutputStream 和InputStream 输入和输出:1.参照物都是java程序来惨遭 2.Input输入,持久化上的数据---->内存 3.Output输出,内存--->硬 ...
- github windows配置以及ssh生成 Permission denied (publickey)
1:进入cmd命令下,或者可以使用GIt工具 (如果出现了 Permission denied 或者配置多个SSH Key跳第6步) git工具 下载地址:https://git-scm.com ...
- Linux安装redis服务器
Linux安装redis服务器 初次接触,这里简单的说下我遇到的情况以及安装方法,当然也是参考了诸位大神的. 确定虚拟机的主机IP. 1)首先需要一个linux虚拟机,确定虚拟机的ip ,输入命令:# ...