com.penglecode.common.web.shiro.cache.RedisCache Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of commons Show documentation
Show all versions of commons Show documentation
commons is a little java tool to make your development easier in your work.
The newest version!
package com.penglecode.common.web.shiro.cache;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.util.Assert;
/**
* 基于Redis缓存的Cache实现
*
* @author pengpeng
* @date 2015年1月30日 下午2:25:51
* @version 1.0
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public class RedisCache implements Cache {
/**
* 相当于存在redis中的key的prefix
*/
private final String cacheName;
private RedisTemplate redisTemplate;
private boolean cacheExpire;
private int cacheExpireSeconds;
public RedisCache(String cacheName, RedisTemplate redisTemplate) {
super();
Assert.hasText(cacheName, "Parameter 'cacheName' can not be empty!");
Assert.notNull(redisTemplate, "Parameter 'redisTemplate' can not be null!");
this.cacheName = cacheName;
this.redisTemplate = redisTemplate;
}
public RedisCache(String cacheName, RedisTemplate redisTemplate, boolean cacheExpire, int cacheExpireSeconds) {
this(cacheName, redisTemplate);
this.cacheExpire = cacheExpire;
this.cacheExpireSeconds = cacheExpireSeconds;
}
public Object get(final String key) throws CacheException {
String realKey = key(key);
if(cacheExpire){ //touch
redisTemplate.expire(realKey, cacheExpireSeconds, TimeUnit.SECONDS);
}
Object value = redisTemplate.opsForValue().get(realKey);
return value;
}
public Object put(final String key, final Object value) throws CacheException {
final String realKey = key(key);
return redisTemplate.execute(new SessionCallback