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 ...
随机推荐
- join() ---- 使用四种不同的分隔符连接数组元素
var a = ['Wind', 'Rain', 'Fire']; var myVar1 = a.join(); // myVar1的值变为"Wind,Rain,Fire" var ...
- vue 未完待续
1. v-text:主要用来更新textContent,可以等同于JS的text属性. <span v-text="msg"></span> 这两者等价: ...
- Nginx搭建
Nginx nginx是一个开源的,支持高性能,高并发的www服务和代理服务软件. nginx因具有高并发(特别是静态资源),占用系统资源少等特性,且功能丰富而逐渐流行起来. nginx不但是一个优秀 ...
- CAFE: a computational tool for the study of gene family evolution
1.摘要 摘要:我们提出了CAFE(计算分析基因家族进化),这是一个统计分析基因家族进化规模的工具.它使用随机的出生和死亡过程来模拟一个系统发育过程中基因家族大小的进化.对于一个特定的系统发育树,并给 ...
- linux下redis4.0.2集群部署(利用原生命令)
一.部署架构如下 每台服务器准备2个节点,一主一从,主节点为另外两台其中一台的主,从节点为另外两台其中一台的从. 二.准备6个节点配置文件 在172.28.18.75上操作 cd /etc/redis ...
- mysql_day01
1.MySQL概述 1.什么是数据库 数据库是一个存储数据的仓库 2.都有哪些公司在用数据库 金融机构.游戏网站.购物网站.论坛网站 ... ... 3.提供数据库服务的软件 1.软件分类 MySQL ...
- 音频音乐播放 Service
界面效果: 界面就一个播放的Button和一个进度条SeekBar,也可以自己加上两个显示时间的TextView: 点击播放时,有音乐声音,进度条也会自动更新,Button文字变成暂停 ...
- http://ctf.bugku.com/challenges#Mountain%20climbing:bugku--Mountain-Climbing
分析这道题,爽,能够结合IDA和ollydbg分析代码,美滋滋.但如果以后能直接根据汇编容易地看懂逻辑那就更好了. 参考链接: https://blog.csdn.net/cossack9989/ ...
- [leetcode]56. Merge Intervals归并区间
Given a collection of intervals, merge all overlapping intervals. Example 1: Input: [[1,3],[2,6],[8, ...
- Django model进阶
Django-model进阶 QuerySet 可切片 使用Python 的切片语法来限制查询集记录的数目 .它等同于SQL 的LIMIT 和OFFSET 子句. >>> Ent ...