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; ...
随机推荐
- JavaScript设计模式——工厂模式
工厂模式:是一种实现“工厂”概念的面上对象设计模式.实质是定义一个创建对象的接口,但是让实现这个接口的类来决定实例化哪个类.工厂方法让类的实例化推迟到子类中进行.创建一个对象常常需要复杂的过程,所以不 ...
- express-1 从Node开始
hello world var http = require('http'); http.createServer(function (req, res) { res.writeHead(200, { ...
- 提取Windows用户密钥文件cachedump
提取Windows用户密钥文件cachedump Windows系统将用户信息和密钥存储在系统存档文件(System hive)和安全存档(Security hive)中.只要提取这些内容,就可以 ...
- jQuery-品牌列表案例
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title> ...
- AspNetPager 样式以及使用(漂亮)
自定义样式: <style type="text/css"> /*拍拍网风格*/ .paginator { font: 11px Arial, Helvetica, s ...
- 转:Delphi和Office程序开发 --不错可查阅
http://www.delphifans.com/infoview/Article_730.html日期:2006年2月20日 作者:潇潇2003 人气:5602 查看:[大字体 中字体 小字体] ...
- 使用 Velocity 模板引擎快速生成代码
http://www.ibm.com/developerworks/cn/java/j-lo-velocity1/
- AWS S3 API实现文件上传下载
http://blog.csdn.net/marvin198801/article/details/47662965
- iOS之03-类的合理设计
以下代码为了充分学习理解 类与对象 类与对象的定义 类就是将事物的共有属性和方法抽离出来形成的:类是现实世界或思维世界中的实体在计算机中的反映,它将数据以及这些数据上的操作封装在一起. 对象是具有类类 ...
- ccc 播放动画
cc.Class({ extends: cc.Component, properties: { anim:cc.Animation, }, // use this for initialization ...