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工具类的更多相关文章

  1. Jedis工具类代码

    安装Redis可以参考 https://www.cnblogs.com/dddyyy/p/9763098.html Redis的学习可以参考https://www.cnblogs.com/dddyyy ...

  2. Jedis工具类(含分布式锁的调用和释放)

    个人把工具类分为两部分: 一.连接池部分 import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.j ...

  3. Java Redis 连接池 Jedis 工具类

    import org.slf4j.Logger; import org.slf4j.LoggerFactory; import redis.clients.jedis.Jedis; import re ...

  4. Jedis 工具类

    package com.pig4cloud.pigx.admin.utils; import redis.clients.jedis.*; import java.util.ArrayList; im ...

  5. Jedis 操作 Redis 工具类

    配置类 pom.xml pom.xml 里配置依赖 <dependency> <groupId>redis.clients</groupId> <artifa ...

  6. 关于jedis2.4以上版本的连接池配置,及工具类

    jedis.propertise 注意以前版本的maxAcitve和maxWait有所改变,JVM根据系统环境变量ServerType中的值 取不同的配置,实现多环境(测试环境.生产环境)集成. re ...

  7. 动态代理模式_应用(Redis工具类)

    本次使用动态代理的初衷是学习Redis,使用Java操作Redis时用到Jedis的JedisPool,而后对Jedis的方法进一步封装完善成为一个工具类.因为直接使用Jedis对象时,为了保证性能, ...

  8. Redis,JedisPool工具类

    Redis,JedisPool工具类 1.JedisPool 详细配置解释代码 2.Jedis工具类 导入相关依赖: commons-pool2-2.3.jar jedis-2.7.0.jar 1.J ...

  9. redis集群使用Java工具类(Java jedis集群工具类)

    package com.xiaomi.weather.vote.webservices.util.redisCache; import com.google.common.base.Strings; ...

随机推荐

  1. ajax轮循

    使用 AJAX 进行异步加载轮询操作.简单代码如下: <script> // 执行ajax轮循操作 function polling(){ var xmlhttp; // 判断浏览器--创 ...

  2. 数据库的SQL语句创建和主外键删除操作

    create table UserType ( Id ,), Name nvarchar() not null ) go create table UserInfo ( Id ,), LoginPwd ...

  3. 线段树(区间操作) POJ 3325 Help with Intervals

    题目传送门 题意:四种集合的操作,对应区间的01,问最后存在集合存在的区间. 分析:U T [l, r]填充1; I T [0, l), (r, N]填充0; D T [l, r]填充0; C T[0 ...

  4. Jenkins基础 - 常用配置操作

    1.修改jenkins的根目录,默认地在C:\Users\用户名\.jenkins下(win7) 或C:\Documents and Settings\用户名\.jenkins(xp) 修改步骤: 增 ...

  5. Storm TimeCacheMap RotatingMap源码分析

    TimeCacheMap是Twitter Storm里面一个类, Storm使用它来保存那些最近活跃的对象,并且可以自动删除那些已经过期的对象. 不过在storm0.8之后TimeCacheMap被弃 ...

  6. R AnalyticFlow---R的流程图

    0.简介 R AnalyticFlow是一款利用R环境作为统计计算的数据分析软件,创作者是日本人,版权属于日本Ef-prime公司.R AnalyticFlow除了拥有直观的用户界面和流程图显示,它还 ...

  7. mobile web HTML5 app曾经的踩过坑(转)

    兼容性一直是前端工程师心中永远的痛.手机浏览器,因为基本是webkit(blink)内核当道,很多公司,不用考虑IE系的浏览器,所以感觉兼容性上的问题可能会少一些. 但是手机端,虽然出了很多工具,但是 ...

  8. [杂谈] There is a Doctor in My Computer.

    (p.s. 附带手写翻译,有错轻喷) Admin: Hi.             (嗨) Doctor: How do you do?  What brings you to see me?     ...

  9. 【BZOJ】2084: [Poi2010]Antisymmetry

    http://www.lydsy.com/JudgeOnline/problem.php?id=2084 题意:一个01串,求满足字符串0和1取反后,再将整个串反过来和原串一样的子串数目.(n< ...

  10. 【BZOJ】1406: [AHOI2007]密码箱

    http://www.lydsy.com/JudgeOnline/problem.php?id=1406 题意:求$0<=x<n, 1<=n<=2,000,000,000, 且 ...