一、RedisCache.javajava
package cn.itcast.mybatis.dao;redis
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;spring
import org.apache.commons.lang3.StringUtils;apache
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;json
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 {mybatis
private static int DEFAULT_DB_INDEX = 0;
private static int DB_INDEX_1 = 1;
private static JedisPool jedisPool = null;ide
private String host;
private int port;
private String password;this
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;
}
}
二、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);
}
三、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);
}
}