Jedis工具类
1、RedisCache.java
package cn.itcast.mybatis.dao;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import com.google.gson.Gson;
/**
*
* @description
*
* @author xujie04
* @version $Id: RedisCacher.java, v 0.1 2015年8月25日 下午5:23:19 xujie04 Exp $
*/
public class RedisCacher {
private static int DEFAULT_DB_INDEX = 0;
private static int DB_INDEX_1 = 1;
private static JedisPool jedisPool = null;
private String host;
private int port;
private String password;
private static Gson gson = new Gson();
private static final String ClassName = "CN";
private static final String ObjectKey = "OBJK";
private static final String EXPIRE_SECONDS = "expireSeconds";
private static final String TIMESTAMP = "timestamp";
public RedisCacher(String host, int port) {
this.host = host;
this.port = port;
}
public RedisCacher(String host, int port, String password) {
this.host = host;
this.port = port;
this.password = password;
}
/**
* 初始化redis连接池
*/
public void init() {
try {
if (jedisPool == null) {
// 配置如下的4个参数就够了。
JedisPoolConfig config = new JedisPoolConfig();
// 控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
config.setMaxTotal(100);
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
config.setMaxIdle(10);
// 表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
config.setMaxWaitMillis(10000L);
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
config.setTestOnBorrow(true);
jedisPool = new JedisPool(config, host, port, 10000, password);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获得redis实例
*/
public Jedis getJedis() {
try {
if (jedisPool != null) {
Jedis resource = jedisPool.getResource();
resource.select(DEFAULT_DB_INDEX);
return resource;
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void returnResource(final Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
private String objectToJSONString(Object val, Integer seconds) {
Map<String, Object> map = new HashMap<String, Object>();
map.put(ObjectKey, gson.toJson(val));
map.put(ClassName, val.getClass().getName());
map.put(EXPIRE_SECONDS, seconds);
map.put(TIMESTAMP, new Date().getTime());
return gson.toJson(map);
}
@SuppressWarnings("unchecked")
private Object jsonStringToObject(String value) throws Exception {
Map<String, Object> map = gson.fromJson(value, new HashMap<String, Object>().getClass());
Object obj = map.get(ObjectKey);
if (obj == null) {
return null;
}
Integer seconds = ((Double) map.get(EXPIRE_SECONDS)).intValue();
if (seconds != null) {
Long timestamp = ((Double) map.get(TIMESTAMP)).longValue();
Long now = new Date().getTime();
if ((timestamp + (seconds.longValue() * 1000)) < now) {
//过期
throw new Exception("the value has expire,but not expire in redis...");
}
}
String objStr = (String) obj;
String className = (String) map.get(ClassName);
return gson.fromJson(objStr, Class.forName(className));
}
//删除
public void delete(String... keys) {
Jedis jedis = getJedis();
try {
if (jedis != null) {
if (keys != null) {
jedis.del(keys);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
}
/**
* 值设置到redis中
*
* @param key
* @param val
* @param seconds 单位秒
*/
public void set(String key, Object val, Integer seconds) {
Jedis jedis = getJedis();
try {
if (jedis != null) {
jedis.set(key, objectToJSONString(val, seconds));
if (seconds != null) {
jedis.expire(key, seconds);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
}
/**
* 新增将hash值设置到redis中
*
* @param key
* @param val
* @param seconds 单位秒
*/
public void hset(String key, String field, String val, Integer seconds) {
Jedis jedis = getJedis();
try {
if (jedis != null) {
jedis.select(DB_INDEX_1);
jedis.hset(key, field, val);
if (seconds != null) {
jedis.expire(key, seconds);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
returnResource(jedis);
}
}
/**
* 获取值
*
* @param key
* @return
*/
public Object get(String key) {
Jedis jedis = getJedis();
try {
if (jedis != null) {
String str = jedis.get(key);
if (StringUtils.isEmpty(str)) {
return null;
}
return jsonStringToObject(str);
}
return null;
} catch (Exception e) {
if (jedis.exists(key)) {
delete(key);
}
return null;
} finally {
returnResource(jedis);
}
}
/**
*根据key field 获取hash值
*
* @param key
* @param field
* @return
*/
public String hget(String key, String field) {
Jedis jedis = getJedis();
try {
if (jedis != null) {
jedis.select(DB_INDEX_1);
String str = jedis.hget(key, field);
if (StringUtils.isEmpty(str)) {
return null;
}
return str;
}
return null;
} catch (Exception e) {
if (jedis.exists(key)) {
delete(key);
}
return null;
} finally {
returnResource(jedis);
}
}
/**
* 获取hash值
*
* @param key
* @return
*/
public Map<String, String> hgetAll(String key) {
Jedis jedis = getJedis();
Map<String, String> str = new HashMap<String, String>();
try {
if (jedis != null) {
jedis.select(DB_INDEX_1);
str = jedis.hgetAll(key);
if (StringUtils.isEmpty(str.toString())) {
return null;
}
return str;
}
return str;
} catch (Exception e) {
if (jedis.exists(key)) {
delete(key);
}
return null;
} finally {
returnResource(jedis);
}
}
/**
* 获取key模糊查询得到的数组
*
* @param key
* @return
*/
public Set<String> keys(String key) {
Jedis jedis = getJedis();
Set<String> str = new HashSet<String>();
try {
if (jedis != null) {
jedis.select(DB_INDEX_1);
str = jedis.keys(key);
if (null == str || str.size() == 0) {
return null;
}
return str;
}
return str;
} catch (Exception e) {
if (jedis.exists(key)) {
delete(key);
}
return null;
} finally {
returnResource(jedis);
}
}
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2、CacheManager.java
package cn.itcast.mybatis.dao;
import java.util.Map;
import java.util.Set;
/**
*
* @description
*
* @author xujie04
* @version $Id: CacheManager.java, v 0.1 2015年8月26日 上午10:36:05 xujie04 Exp $
*/
public interface CacheManager {
/**
*
* @param key 缓存对象的key
* @param val 缓存的对象
* @param expireSeconds 有效时间
*/
public void set(String key, Object val, Integer expireSeconds);
public Object get(String key);
public void delete(String key);
public void hset(String key, String field, String val, Integer seconds);
public String hget(String key, String field);
public Map<String, String> hgetAll(String key);
public Set<String> keys(String key);
}
3、CacheManagerImpl.java
package cn.itcast.mybatis.dao;
import java.util.Map;
import java.util.Set;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
*
* @description
*
* @author xujie04
* @version $Id: CacheManagerImpl.java, v 0.1 2015年8月26日 上午10:35:58 xujie04 Exp $
*/
@Component
public class CacheManagerImpl implements CacheManager {
private RedisCacher cacher;
@Value("${redis.ip}")
private String host;
@Value("${redis.port}")
private int port;
@Value("${redis.password}")
private String password;
@PostConstruct
public void init() {
cacher = new RedisCacher(host, port, password);
cacher.init();
}
@Override
public void set(String key, Object val, Integer expireSeconds) {
cacher.set(key, val, expireSeconds);
}
@Override
public Object get(String key) {
return cacher.get(key);
}
@Override
public void delete(String key) {
cacher.delete(key);
}
@Override
public void hset(String key, String field, String val, Integer seconds) {
cacher.hset(key, field, val, seconds);
}
@Override
public String hget(String key, String field) {
return cacher.hget(key, field);
}
@Override
public Map<String, String> hgetAll(String key) {
return cacher.hgetAll(key);
}
@Override
public Set<String> keys(String key) {
return cacher.keys(key);
}
}
Jedis工具类的更多相关文章
- Jedis工具类代码
安装Redis可以参考 https://www.cnblogs.com/dddyyy/p/9763098.html Redis的学习可以参考https://www.cnblogs.com/dddyyy ...
- Jedis工具类(含分布式锁的调用和释放)
个人把工具类分为两部分: 一.连接池部分 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.j ...
- Java Redis 连接池 Jedis 工具类
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import re ...
- Jedis 工具类
package com.pig4cloud.pigx.admin.utils; import redis.clients.jedis.*; import java.util.ArrayList; im ...
- Jedis 操作 Redis 工具类
配置类 pom.xml pom.xml 里配置依赖 <dependency> <groupId>redis.clients</groupId> <artifa ...
- 关于jedis2.4以上版本的连接池配置,及工具类
jedis.propertise 注意以前版本的maxAcitve和maxWait有所改变,JVM根据系统环境变量ServerType中的值 取不同的配置,实现多环境(测试环境.生产环境)集成. re ...
- 动态代理模式_应用(Redis工具类)
本次使用动态代理的初衷是学习Redis,使用Java操作Redis时用到Jedis的JedisPool,而后对Jedis的方法进一步封装完善成为一个工具类.因为直接使用Jedis对象时,为了保证性能, ...
- Redis,JedisPool工具类
Redis,JedisPool工具类 1.JedisPool 详细配置解释代码 2.Jedis工具类 导入相关依赖: commons-pool2-2.3.jar jedis-2.7.0.jar 1.J ...
- redis集群使用Java工具类(Java jedis集群工具类)
package com.xiaomi.weather.vote.webservices.util.redisCache; import com.google.common.base.Strings; ...
随机推荐
- 【转】清理Kylin的中间存储数据(HDFS & HBase Tables)
http://blog.csdn.net/jiangshouzhuang/article/details/51290399 Kylin在创建cube过程中会在HDFS上生成中间数据.另外,当我们对cu ...
- poj3642 01背包
http://poj.org/problem?id=3624 #include<iostream> #include<cstdio> #include<algorithm ...
- SQL初级
SQL是一个微软开发的数据库,因为联系到很多内部服务程序和文件所以安装和删除的时候有些人会遇上些麻烦,如果安装失败了那就得完全删除后重装,然而他自己自带的删除系统并不是那么给力,所以悲剧就诞生了,不行 ...
- CSS3设置多张背景图片
background-image:url("1.jpg"),url("2.jpg"),url("3.jpg");background-rep ...
- [工作中的设计模式]策略模式stategy
一.模式解析 策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换.策略模式让算法独立于使用它的客户而独立变化. 策略模式的关键点为: 1.多种算法存在 2.算法继承同样的接口 ...
- 2.2 代码块--delphi 写日志模块
//2.2 代码块--写日志 //调用例句如:LogMsg('FTP上传线程终止',False,true); procedure LogMsg(AMsg: string; const blnIsErr ...
- zjoi2016 day1【bzoj4455】【bzoj4456】
首先做了T2的旅行者,看到bz上面过的人数比较多.. 考试的时候完全没有想太多.一闪而过了分块思想,然后就没有然后了.. 大视野上面有题解,竟然是一个初中生写的..? 正解其实是“分治”,每次选择中轴 ...
- 后缀数组 UVA 11107 Life Forms
题目链接 题意:训练指南P223 分析:二分长度,把所有字符串连成一个字符串,中间用不同的字符分隔(这是为了保证匹配长度始终在一个字符串内).height数组分段,vis数组标记哪些字符串被访问了,如 ...
- 差分约束系统 POJ 3169 Layout
题目传送门 题意:有两种关系,n牛按照序号排列,A1到B1的距离不超过C1, A2到B2的距离不小于C2,问1到n的距离最大是多少.如果无限的话是-2, 如果无解是-1 分析:第一种可以写这样的方程: ...
- Darkest page of my coding life
The code i wrote a while ago recently caused a disaster and as I reviewed it I found it is the silli ...