Skip to content

Instantly share code, notes, and snippets.

@fwrq41251
Last active February 19, 2016 01:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fwrq41251/2fc9152a675f09d8eb3f to your computer and use it in GitHub Desktop.
Save fwrq41251/2fc9152a675f09d8eb3f to your computer and use it in GitHub Desktop.
shiro cache impl in redis.
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
public class ShiroRedisCache<K, V> implements Cache<K, V> {
private RedisTemplate<K, V> template;
private RedisTemplate<String, K> template2;
private final String name;
public ShiroRedisCache(String name) {
super();
this.name = name;
}
@Override
public V get(K key) throws CacheException {
V value = (V) template.opsForValue().get(key);
return value;
}
@Override
@SuppressWarnings("unchecked")
public V put(K key, V value) throws CacheException {
template.opsForValue().set(key, value);
template2.opsForSet().add(name, key);
return value;
}
@Override
public V remove(K key) throws CacheException {
V value = template.opsForValue().get(key);
template.opsForValue().getOperations().delete(key);
template2.opsForSet().remove(name, key);
return value;
}
@Override
public void clear() throws CacheException {
template.opsForValue().getOperations().delete(keys());
template2.opsForSet().remove(name, keys());
}
@Override
public int size() {
Long size = template2.opsForSet().size(name);
return size.intValue();
}
@Override
public Set<K> keys() {
SetOperations<String, K> setOps = template2.opsForSet();
return setOps.members(name);
}
@Override
public Collection<V> values() {
List<V> values = new ArrayList<>();
for (K key : keys()) {
values.add(get(key));
}
return values;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment