redis整体结构
将redis.windows.conf文件复制到6382等多个文件夹下并重命名redis.conf
2 配置文件
bind 127.0.0.1
protected-mode yes
port 6382
slave-serve-stale-data yes
slave-read-only yes
repl-diskless-sync-delay 5
repl-disable-tcp-nodelay no
slave-priority 100
appendonly no
appendfilename "appendonly6382.aof"
cluster-node-timeout 15000
appendfsync everysec
no-appendfsync-on-rewrite no
auto-aof-rewrite-percentage 100
auto-aof-rewrite-min-size 64mb
aof-load-truncated yes
lua-time-limit 5000
cluster-enabled yes
cluster-config-file nodes-6382.conf
dbfilename dump6382.rdb
cluster-node-timeout 15000
slowlog-log-slower-than 10000
slowlog-max-len 128
latency-monitor-threshold 0
notify-keyspace-events ""
hash-max-ziplist-entries 512
hash-max-ziplist-value 64
list-max-ziplist-size -2
list-compress-depth 0
set-max-intset-entries 512
zset-max-ziplist-entries 128
zset-max-ziplist-value 64
hll-sparse-max-bytes 3000
activerehashing yes
client-output-buffer-limit normal 0 0 0
client-output-buffer-limit slave 256mb 64mb 60
client-output-buffer-limit pubsub 32mb 8mb 60
hz 10
aof-rewrite-incremental-fsync yes
3 启动每个redis
redis-server 6382/redis.conf
4 创建集群
redis-cli --cluster create 127.0.0.1:6380 127.0.0.1:6381 127.0.0.1:6382 --cluster-replicas 2
连接集群
redis-cli -c -h 127.0.0.1 -p 6380
查询集群节点信息
redis-cli -c -p 7001 cluster nodes
其他老代码部分
spring-context-jedis.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"
default-lazy-init="true">
<description>Jedis Configuration</description>
<!-- 加载配置属性文件 -->
<context:property-placeholder ignore-unresolvable="true" location="classpath:jeesite.properties" />
<!-- <bean id="redisHttpSessionConfiguration" -->
<!-- class="org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration"> -->
<!-- <property name="maxInactiveIntervalInSeconds" value="1800" /> -->
<!-- </bean> -->
<!--创建了一个RedisConnectionFactory,它将Spring会话连接到Redis服务器。我们配置连接到默认端口(6379)上的本地主机!-->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"/>
<property name="port" value="${redis.port}"/>
<property name="poolConfig" ref="jedisPoolConfig"/>
</bean>
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxIdle" value="300" /> <!-- 最大能够保持idel状态的对象数 -->
<property name="maxTotal" value="60000" /> <!-- 最大分配的对象数 -->
<property name="testOnBorrow" value="true" /> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->
</bean>
<bean id="jedis" class="redis.clients.jedis.JedisCluster">
<constructor-arg>
<set>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="127.0.0.1"></constructor-arg>
<constructor-arg name="port" value="6380"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="127.0.0.1"></constructor-arg>
<constructor-arg name="port" value="6381"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="127.0.0.1"></constructor-arg>
<constructor-arg name="port" value="6382"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="127.0.0.1"></constructor-arg>
<constructor-arg name="port" value="6383"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="127.0.0.1"></constructor-arg>
<constructor-arg name="port" value="6384"></constructor-arg>
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg name="host" value="127.0.0.1"></constructor-arg>
<constructor-arg name="port" value="6385"></constructor-arg>
</bean>
</set>
</constructor-arg>
<constructor-arg name="connectionTimeout" value="30" />
<constructor-arg name="soTimeout" value="30" />
<constructor-arg name="maxAttempts" value="300" />
<!-- <constructor-arg name="password" value="${redis.password}" /> -->
<constructor-arg name="poolConfig">
<ref bean="jedisPoolConfig" />
</constructor-arg>
</bean>
<!--redis redisTemplate -->
<!-- <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate"> -->
<!-- <property name="connectionFactory" ref="jedisConnectionFactory" /> -->
<!-- <property name="keySerializer"> -->
<!-- <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> -->
<!-- </property> -->
<!-- <property name="hashKeySerializer"> -->
<!-- <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" /> -->
<!-- </property> -->
<!-- <property name="valueSerializer"> -->
<!-- <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" /> -->
<!-- </property> -->
<!-- <property name="hashValueSerializer"> -->
<!-- <bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" /> -->
<!-- </property> -->
<!-- <property name="enableTransactionSupport" value="true"></property> -->
<!-- </bean> -->
<!-- <bean id="redisMessageListener" class="com.msunsoft.websocket.oaNotify.listener.OaNotifyListener"></bean> -->
<!-- <bean class="com.msunsoft.websocket.oaNotify.listener.OaNotifyListener"></bean> -->
</beans>
jedisSessionDao
/**
* Copyright © 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
*/
package com.msunsoft.common.security.shiro.session;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool;
import com.google.common.collect.Sets;
import com.msunsoft.common.config.Global;
import com.msunsoft.common.utils.DateUtils;
import com.msunsoft.common.utils.JedisUtils;
import com.msunsoft.common.utils.SpringContextHolder;
import com.msunsoft.common.utils.StringUtils;
import com.msunsoft.common.web.Servlets;
/**
* 自定义授权会话管理类
* @author ThinkGem
* @version 2014-7-20
*/
public class JedisSessionDAO extends AbstractSessionDAO implements SessionDAO {
private Logger logger = LoggerFactory.getLogger(getClass());
private String sessionKeyPrefix = "shiro_session_";
@Override
public void update(Session session) throws UnknownSessionException {
if (session == null || session.getId() == null) {
return;
}
HttpServletRequest request = Servlets.getRequest();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不更新SESSION
if (Servlets.isStaticFile(uri)){
return;
}
// 如果是视图文件,则不更新SESSION
if (StringUtils.startsWith(uri, Global.getConfig("web.view.prefix"))
&& StringUtils.endsWith(uri, Global.getConfig("web.view.suffix"))){
return;
}
// 手动控制不更新SESSION
if (Global.NO.equals(request.getParameter("updateSession"))){
return;
}
}
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
// 获取登录者编号
PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
String principalId = pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY;
jedis.hset(sessionKeyPrefix, session.getId().toString(), principalId + "|" + session.getTimeout() + "|" + session.getLastAccessTime().getTime());
jedis.set(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()), JedisUtils.toBytes(session));
// 设置超期时间
int timeoutSeconds = (int)(session.getTimeout() / 1000);
jedis.expire((sessionKeyPrefix + session.getId()), timeoutSeconds);
logger.debug("update {} {}", session.getId(), request != null ? request.getRequestURI() : "");
} catch (Exception e) {
logger.error("update {} {}", session.getId(), request != null ? request.getRequestURI() : "", e);
} finally {
}
}
@Override
public void delete(Session session) {
if (session == null || session.getId() == null) {
return;
}
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
/*jedis.hdel(JedisUtils.getBytesKey(sessionKeyPrefix), JedisUtils.getBytesKey(session.getId().toString()));
jedis.del(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()));*/
jedis.hdel(sessionKeyPrefix, session.getId().toString());
jedis.del(JedisUtils.getBytesKey(sessionKeyPrefix + session.getId()));
logger.debug("delete {} ", session.getId());
} catch (Exception e) {
logger.error("delete {} ", session.getId(), e);
} finally {
//JedisUtils.returnResource(jedis);
}
}
@Override
public Collection<Session> getActiveSessions() {
return getActiveSessions(true);
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @return
*/
@Override
public Collection<Session> getActiveSessions(boolean includeLeave) {
return getActiveSessions(includeLeave, null, null);
}
/**
* 获取活动会话
* @param includeLeave 是否包括离线(最后访问时间大于3分钟为离线会话)
* @param principal 根据登录者对象获取活动会话
* @param filterSession 不为空,则过滤掉(不包含)这个会话。
* @return
*/
@Override
public Collection<Session> getActiveSessions(boolean includeLeave, Object principal, Session filterSession){
Set<Session> sessions = Sets.newHashSet();
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
Map<String, String> map = jedis.hgetAll(sessionKeyPrefix);
for (Map.Entry<String, String> e : map.entrySet()){
if (StringUtils.isNotBlank(e.getKey()) && StringUtils.isNotBlank(e.getValue())){
String[] ss = StringUtils.split(e.getValue(), "|");
if (ss != null && ss.length == 3){// jedis.exists(sessionKeyPrefix + e.getKey())){
// Session session = (Session)JedisUtils.toObject(jedis.get(JedisUtils.getBytesKey(sessionKeyPrefix + e.getKey())));
SimpleSession session = new SimpleSession();
session.setId(e.getKey());
session.setAttribute("principalId", ss[0]);
session.setTimeout(Long.valueOf(ss[1]));
session.setLastAccessTime(new Date(Long.valueOf(ss[2])));
try{
// 验证SESSION
session.validate();
boolean isActiveSession = false;
// 不包括离线并符合最后访问时间小于等于3分钟条件。
if (includeLeave || DateUtils.pastMinutes(session.getLastAccessTime()) <= 3){
isActiveSession = true;
}
// 符合登陆者条件。
if (principal != null){
PrincipalCollection pc = (PrincipalCollection)session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
if (principal.toString().equals(pc != null ? pc.getPrimaryPrincipal().toString() : StringUtils.EMPTY)){
isActiveSession = true;
}
}
// 过滤掉的SESSION
if (filterSession != null && filterSession.getId().equals(session.getId())){
isActiveSession = false;
}
if (isActiveSession){
sessions.add(session);
}
}
// SESSION验证失败
catch (Exception e2) {
jedis.hdel(sessionKeyPrefix, e.getKey());
}
}
// 存储的SESSION不符合规则
else{
jedis.hdel(sessionKeyPrefix, e.getKey());
}
}
// 存储的SESSION无Value
else if (StringUtils.isNotBlank(e.getKey())){
jedis.hdel(sessionKeyPrefix, e.getKey());
}
}
logger.info("getActiveSessions size: {} ", sessions.size());
} catch (Exception e) {
logger.error("getActiveSessions", e);
} finally {
//JedisUtils.returnResource(jedis);
}
return sessions;
}
@Override
protected Serializable doCreate(Session session) {
HttpServletRequest request = Servlets.getRequest();
if (request != null){
String uri = request.getServletPath();
// 如果是静态文件,则不创建SESSION
if (Servlets.isStaticFile(uri)){
return null;
}
}
Serializable sessionId = this.generateSessionId(session);
this.assignSessionId(session, sessionId);
this.update(session);
return sessionId;
}
@Override
protected Session doReadSession(Serializable sessionId) {
Session s = null;
HttpServletRequest request = Servlets.getRequest();
if (request != null){
//String uri = request.getServletPath();
// 如果是静态文件,则不获取SESSION
// if (Servlets.isStaticFile(uri)){
// return null;
// }
s = (Session)request.getAttribute("session_"+sessionId);
}
if (s != null){
return s;
}
Session session = null;
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
// if (jedis.exists(sessionKeyPrefix + sessionId)){
session = (Session)JedisUtils.toObject(jedis.get(
JedisUtils.getBytesKey(sessionKeyPrefix + sessionId)));
// }
logger.debug("doReadSession {} {}", sessionId, request != null ? request.getRequestURI() : "");
} catch (Exception e) {
logger.error("doReadSession {} {}", sessionId, request != null ? request.getRequestURI() : "", e);
} finally {
}
if (request != null && session != null){
request.setAttribute("session_"+sessionId, session);
}
return session;
}
@Override
public Session readSession(Serializable sessionId) throws UnknownSessionException {
try{
return super.readSession(sessionId);
}catch (UnknownSessionException e) {
return null;
}
}
public String getSessionKeyPrefix() {
return sessionKeyPrefix;
}
public void setSessionKeyPrefix(String sessionKeyPrefix) {
this.sessionKeyPrefix = sessionKeyPrefix;
}
}
jedisCachManage
/**
- Copyright © 2012-2016 JeeSite All rights reserved.
*/
package com.msunsoft.common.security.shiro.cache;
import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import com.google.common.collect.Sets;
import com.msunsoft.common.utils.JedisUtils;
import com.msunsoft.common.web.Servlets;
/**
-
自定义授权缓存管理类
-
@author ThinkGem
-
@version 2014-7-20
*/
public class JedisCacheManager implements CacheManager {private String cacheKeyPrefix = “shiro_cache_”;
@Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
return new JedisCache<K, V>(cacheKeyPrefix + name);
}public String getCacheKeyPrefix() {
return cacheKeyPrefix;
}public void setCacheKeyPrefix(String cacheKeyPrefix) {
this.cacheKeyPrefix = cacheKeyPrefix;
}/**
-
自定义授权缓存管理类
-
@author ThinkGem
-
@version 2014-7-20
*/
public class JedisCache<K, V> implements Cache<K, V> {private Logger logger = LoggerFactory.getLogger(getClass());
private String cacheKeyName = null;
public JedisCache(String cacheKeyName) {
this.cacheKeyName = cacheKeyName;
// if (!JedisUtils.exists(cacheKeyName)){
// Map<String, Object> map = Maps.newHashMap();
// JedisUtils.setObjectMap(cacheKeyName, map, 60 * 60 * 24);
// }
// logger.debug("Init: cacheKeyName {} ", cacheKeyName);
}@SuppressWarnings(“unchecked”)
@Override
public V get(K key) throws CacheException {
if (key == null){
return null;
}V v = null; HttpServletRequest request = Servlets.getRequest(); if (request != null){ v = (V)request.getAttribute(cacheKeyName+key); if (v != null){ return v; } } V value = null; JedisCluster jedis = null; try { jedis = JedisUtils.getResource(); value = (V)JedisUtils.toObject(jedis.hget(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key))); logger.debug("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : ""); } catch (Exception e) { logger.error("get {} {} {}", cacheKeyName, key, request != null ? request.getRequestURI() : "", e); } finally { //JedisUtils.returnResource(jedis); } if (request != null && value != null){ request.setAttribute(cacheKeyName+key, value); } return value;
}
@Override
public V put(K key, V value) throws CacheException {
if (key == null){
return null;
}JedisCluster jedis = null; try { jedis = JedisUtils.getResource(); jedis.hset(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key), JedisUtils.toBytes(value)); logger.debug("put {} {} = {}", cacheKeyName, key, value); } catch (Exception e) { logger.error("put {} {}", cacheKeyName, key, e); } finally { //JedisUtils.returnResource(jedis); } return value;
}
@SuppressWarnings(“unchecked”)
@Override
public V remove(K key) throws CacheException {
V value = null;
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
value = (V)JedisUtils.toObject(jedis.hget(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key)));
jedis.hdel(JedisUtils.getBytesKey(cacheKeyName), JedisUtils.getBytesKey(key));
logger.debug(“remove {} {}”, cacheKeyName, key);
} catch (Exception e) {
logger.warn(“remove {} {}”, cacheKeyName, key, e);
} finally {
//JedisUtils.returnResource(jedis);
}
return value;
}@Override
public void clear() throws CacheException {
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
jedis.hdel(JedisUtils.getBytesKey(cacheKeyName));
logger.debug(“clear {}”, cacheKeyName);
} catch (Exception e) {
logger.error(“clear {}”, cacheKeyName, e);
} finally {
//JedisUtils.returnResource(jedis);
}
}@Override
public int size() {
int size = 0;
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
size = jedis.hlen(JedisUtils.getBytesKey(cacheKeyName)).intValue();
logger.debug("size {} {} ", cacheKeyName, size);
return size;
} catch (Exception e) {
logger.error(“clear {}”, cacheKeyName, e);
} finally {
//JedisUtils.returnResource(jedis);
}
return size;
}@SuppressWarnings(“unchecked”)
@Override
public Set keys() {
Set keys = Sets.newHashSet();
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
Set<byte[]> set = jedis.hkeys(JedisUtils.getBytesKey(cacheKeyName));
for(byte[] key : set){
Object obj = (K)JedisUtils.getObjectKey(key);
if (obj != null){
keys.add((K) obj);
}
}
logger.debug("keys {} {} ", cacheKeyName, keys);
return keys;
} catch (Exception e) {
logger.error(“keys {}”, cacheKeyName, e);
} finally {
//JedisUtils.returnResource(jedis);
}
return keys;
}@SuppressWarnings(“unchecked”)
@Override
public Collection values() {
Collection vals = Collections.emptyList();;
JedisCluster jedis = null;
try {
jedis = JedisUtils.getResource();
Collection<byte[]> col = jedis.hvals(JedisUtils.getBytesKey(cacheKeyName));
for(byte[] val : col){
Object obj = JedisUtils.toObject(val);
if (obj != null){
vals.add((V) obj);
}
}
logger.debug("values {} {} ", cacheKeyName, vals);
return vals;
} catch (Exception e) {
logger.error(“values {}”, cacheKeyName, e);
} finally {
//JedisUtils.returnResource(jedis);
}
return vals;
}
}
}
-
JedisUtils
/**
- Copyright © 2012-2016 JeeSite All rights reserved.
*/
package com.msunsoft.common.utils;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import redis.clients.jedis.JedisCluster;
/**
-
jedisPool Cache 工具类
-
@author ThinkGem
-
@version 2014-6-29
*/
public class JedisUtils {private static Logger logger = LoggerFactory.getLogger(JedisUtils.class);
//private static JedisPool jedisPool = SpringContextHolder.getBean(JedisPool.class);
private static JedisCluster jedisPool = SpringContextHolder.getBean(JedisCluster .class);
// public static final String KEY_PREFIX = Global.getConfig(“redis.keyPrefix”);
/**
* 获取缓存
* @param key 键
* @return 值
*/
public static String get(String key) {
String value = null;
try {
if (jedisPool.exists(key)) {
value = jedisPool.get(key);
value = StringUtils.isNotBlank(value) && !"nil".equalsIgnoreCase(value) ? value : null;
logger.debug("get {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("get {} = {}", key, value, e);
} finally {
//
}
return value;
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public static Object getObject(String key) {
Object value = null;
try {
if (jedisPool.exists(getBytesKey(key))) {
value = toObject(jedisPool.get(getBytesKey(key)));
logger.debug("getObject {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObject {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 设置缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static String set(String key, String value, int cacheSeconds) {
String result = null;
try {
result = jedisPool.set(key, value);
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("set {} = {}", key, value);
} catch (Exception e) {
logger.warn("set {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 设置缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static String setObject(String key, Object value, int cacheSeconds) {
String result = null;
try {
result = jedisPool.set(getBytesKey(key), toBytes(value));
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setObject {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObject {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 获取List缓存
* @param key 键
* @return 值
*/
public static List<String> getList(String key) {
List<String> value = null;
try {
if (jedisPool.exists(key)) {
value = jedisPool.lrange(key, 0, -1);
logger.debug("getList {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getList {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 获取List缓存
* @param key 键
* @return 值
*/
public static List<Object> getObjectList(String key) {
List<Object> value = null;
try {
if (jedisPool.exists(getBytesKey(key))) {
List<byte[]> list = jedisPool.lrange(getBytesKey(key), 0, -1);
value = Lists.newArrayList();
for (byte[] bs : list){
value.add(toObject(bs));
}
logger.debug("getObjectList {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectList {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 设置List缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static long setList(String key, List<String> value, int cacheSeconds) {
long result = 0;
try {
if (jedisPool.exists(key)) {
jedisPool.del(key);
}
result = jedisPool.rpush(key, (String[])value.toArray());
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setList {} = {}", key, value);
} catch (Exception e) {
logger.warn("setList {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 设置List缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static long setObjectList(String key, List<Object> value, int cacheSeconds) {
long result = 0;
try {
if (jedisPool.exists(getBytesKey(key))) {
jedisPool.del(key);
}
List<byte[]> list = Lists.newArrayList();
for (Object o : value){
list.add(toBytes(o));
}
result = jedisPool.rpush(getBytesKey(key), (byte[][])list.toArray());
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setObjectList {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectList {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 向List缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public static long listAdd(String key, String... value) {
long result = 0;
try {
result = jedisPool.rpush(key, value);
logger.debug("listAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listAdd {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 向List缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public static long listObjectAdd(String key, Object... value) {
long result = 0;
try {
List<byte[]> list = Lists.newArrayList();
for (Object o : value){
list.add(toBytes(o));
}
result = jedisPool.rpush(getBytesKey(key), (byte[][])list.toArray());
logger.debug("listObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("listObjectAdd {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public static Set<String> getSet(String key) {
Set<String> value = null;
try {
if (jedisPool.exists(key)) {
value = jedisPool.smembers(key);
logger.debug("getSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getSet {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 获取缓存
* @param key 键
* @return 值
*/
public static Set<Object> getObjectSet(String key) {
Set<Object> value = null;
try {
if (jedisPool.exists(getBytesKey(key))) {
value = Sets.newHashSet();
Set<byte[]> set = jedisPool.smembers(getBytesKey(key));
for (byte[] bs : set){
value.add(toObject(bs));
}
logger.debug("getObjectSet {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectSet {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 设置Set缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static long setSet(String key, Set<String> value, int cacheSeconds) {
long result = 0;
try {
if (jedisPool.exists(key)) {
jedisPool.del(key);
}
result = jedisPool.sadd(key, (String[])value.toArray());
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSet {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 设置Set缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static long setObjectSet(String key, Set<Object> value, int cacheSeconds) {
long result = 0;
try {
if (jedisPool.exists(getBytesKey(key))) {
jedisPool.del(key);
}
Set<byte[]> set = Sets.newHashSet();
for (Object o : value){
set.add(toBytes(o));
}
result = jedisPool.sadd(getBytesKey(key), (byte[][])set.toArray());
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setObjectSet {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectSet {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 向Set缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public static long setSetAdd(String key, String... value) {
long result = 0;
try {
result = jedisPool.sadd(key, value);
logger.debug("setSetAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetAdd {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 向Set缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public static long setSetObjectAdd(String key, Object... value) {
long result = 0;
try {
Set<byte[]> set = Sets.newHashSet();
for (Object o : value){
set.add(toBytes(o));
}
result = jedisPool.rpush(getBytesKey(key), (byte[][])set.toArray());
logger.debug("setSetObjectAdd {} = {}", key, value);
} catch (Exception e) {
logger.warn("setSetObjectAdd {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 获取Map缓存
* @param key 键
* @return 值
*/
public static Map<String, String> getMap(String key) {
Map<String, String> value = null;
try {
if (jedisPool.exists(key)) {
value = jedisPool.hgetAll(key);
logger.debug("getMap {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getMap {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 获取Map缓存
* @param key 键
* @return 值
*/
public static Map<String, Object> getObjectMap(String key) {
Map<String, Object> value = null;
try {
if (jedisPool.exists(getBytesKey(key))) {
value = Maps.newHashMap();
Map<byte[], byte[]> map = jedisPool.hgetAll(getBytesKey(key));
for (Map.Entry<byte[], byte[]> e : map.entrySet()){
value.put(StringUtils.toString(e.getKey()), toObject(e.getValue()));
}
logger.debug("getObjectMap {} = {}", key, value);
}
} catch (Exception e) {
logger.warn("getObjectMap {} = {}", key, value, e);
} finally {
}
return value;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static String setMap(String key, Map<String, String> value, int cacheSeconds) {
String result = null;
try {
if (jedisPool.exists(key)) {
jedisPool.del(key);
}
result = jedisPool.hmset(key, value);
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setMap {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 设置Map缓存
* @param key 键
* @param value 值
* @param cacheSeconds 超时时间,0为不超时
* @return
*/
public static String setObjectMap(String key, Map<String, Object> value, int cacheSeconds) {
String result = null;
try {
if (jedisPool.exists(getBytesKey(key))) {
jedisPool.del(key);
}
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()){
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedisPool.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
if (cacheSeconds != 0) {
jedisPool.expire(key, cacheSeconds);
}
logger.debug("setObjectMap {} = {}", key, value);
} catch (Exception e) {
logger.warn("setObjectMap {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 向Map缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public static String mapPut(String key, Map<String, String> value) {
String result = null;
try {
result = jedisPool.hmset(key, value);
logger.debug("mapPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapPut {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 向Map缓存中添加值
* @param key 键
* @param value 值
* @return
*/
public static String mapObjectPut(String key, Map<String, Object> value) {
String result = null;
try {
Map<byte[], byte[]> map = Maps.newHashMap();
for (Map.Entry<String, Object> e : value.entrySet()){
map.put(getBytesKey(e.getKey()), toBytes(e.getValue()));
}
result = jedisPool.hmset(getBytesKey(key), (Map<byte[], byte[]>)map);
logger.debug("mapObjectPut {} = {}", key, value);
} catch (Exception e) {
logger.warn("mapObjectPut {} = {}", key, value, e);
} finally {
}
return result;
}
/**
* 移除Map缓存中的值
* @param key 键
* @param value 值
* @return
*/
public static long mapRemove(String key, String mapKey) {
long result = 0;
try {
result = jedisPool.hdel(key, mapKey);
logger.debug("mapRemove {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapRemove {} {}", key, mapKey, e);
} finally {
}
return result;
}
/**
* 移除Map缓存中的值
* @param key 键
* @param value 值
* @return
*/
public static long mapObjectRemove(String key, String mapKey) {
long result = 0;
try {
result = jedisPool.hdel(getBytesKey(key), getBytesKey(mapKey));
logger.debug("mapObjectRemove {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapObjectRemove {} {}", key, mapKey, e);
} finally {
}
return result;
}
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @param value 值
* @return
*/
public static boolean mapExists(String key, String mapKey) {
boolean result = false;
try {
result = jedisPool.hexists(key, mapKey);
logger.debug("mapExists {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapExists {} {}", key, mapKey, e);
} finally {
}
return result;
}
/**
* 判断Map缓存中的Key是否存在
* @param key 键
* @param value 值
* @return
*/
public static boolean mapObjectExists(String key, String mapKey) {
boolean result = false;
try {
result = jedisPool.hexists(getBytesKey(key), getBytesKey(mapKey));
logger.debug("mapObjectExists {} {}", key, mapKey);
} catch (Exception e) {
logger.warn("mapObjectExists {} {}", key, mapKey, e);
} finally {
}
return result;
}
/**
* 删除缓存
* @param key 键
* @return
*/
public static long del(String key) {
long result = 0;
try {
if (jedisPool.exists(key)){
result = jedisPool.del(key);
logger.debug("del {}", key);
}else{
logger.debug("del {} not exists", key);
}
} catch (Exception e) {
logger.warn("del {}", key, e);
} finally {
}
return result;
}
/**
* 删除缓存
* @param key 键
* @return
*/
public static long delObject(String key) {
long result = 0;
try {
if (jedisPool.exists(getBytesKey(key))){
result = jedisPool.del(getBytesKey(key));
logger.debug("delObject {}", key);
}else{
logger.debug("delObject {} not exists", key);
}
} catch (Exception e) {
logger.warn("delObject {}", key, e);
} finally {
}
return result;
}
/**
* 缓存是否存在
* @param key 键
* @return
*/
public static boolean exists(String key) {
boolean result = false;
try {
result = jedisPool.exists(key);
logger.debug("exists {}", key);
} catch (Exception e) {
logger.warn("exists {}", key, e);
} finally {
//
}
return result;
}
/**
* 缓存是否存在
* @param key 键
* @return
*/
public static boolean existsObject(String key) {
boolean result = false;
try {
result = jedisPool.exists(getBytesKey(key));
logger.debug("existsObject {}", key);
} catch (Exception e) {
logger.warn("existsObject {}", key, e);
} finally {
}
return result;
}
/**
* 获取资源
* @return
* @throws JedisException
*/
public static JedisCluster getResource() {
jedisPool.hset("a", "o", "12");
return jedisPool;
}
/**
* 归还资源
* @param jedisPool
* @param isBroken
*/
// public static void returnBrokenResource(jedisPool jedisPool) {
// if (jedisPool != null) {
// jedisPool.returnBrokenResource(jedisPool);
// }
// }
/**
* 释放资源
* @param jedisPool
* @param isBroken
*/
// public static void returnResource(jedisPool jedisPool) {
// if (jedisPool != null) {
// jedisPool.
// }
// }
/**
* 获取byte[]类型Key
* @param key
* @return
*/
public static byte[] getBytesKey(Object object){
if(object instanceof String){
return StringUtils.getBytes((String)object);
}else{
return ObjectUtils.serialize(object);
}
}
/**
* 获取byte[]类型Key
* @param key
* @return
*/
public static Object getObjectKey(byte[] key){
try{
return StringUtils.toString(key);
}catch(UnsupportedOperationException uoe){
try{
return JedisUtils.toObject(key);
}catch(UnsupportedOperationException uoe2){
uoe2.printStackTrace();
}
}
return null;
}
/**
* Object转换byte[]类型
* @param key
* @return
*/
public static byte[] toBytes(Object object){
return ObjectUtils.serialize(object);
}
/**
* byte[]型转换Object
* @param key
* @return
*/
public static Object toObject(byte[] bytes){
return ObjectUtils.unserialize(bytes);
}
}