Spring 定时任务(精)(session工具类(配置失效时间),cookie工具类 web工程(初始化容器) redis工具类)

工作中的bean:
public class SystemSessionsScheduler {
    //log
    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 功能描述: 本地定时任务 定时清理过时的用户session 信息<br>
     * 〈功能详细描述〉
     *
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public void removeOvertimeSessionInfo() {
        long start = System.currentTimeMillis();
        logger.info("start excute task : removeOvertimeSessionInfo() ");
        try {
            //临时存放过时的session信息
            List<String> temp = new ArrayList<String>();
            for (Map.Entry<String, Object> element : StaticContainer.getSystemSessions().entrySet()) {
                if (RedisUtils.getInstance().get(AuthUtil.SESS_PREFIX + element.getKey()) == null) {
                    temp.add(element.getKey());
                }
            }
            for (String key : temp) {
                StaticContainer.getSystemSessions().remove(key);
            }
            temp.clear();
        } catch (Exception e) {
            logger.error("task removeOvertimeSessionInfo() error:", ExceptionUtils.getStackTrace(e));
        }
        logger.info("end excute removeOvertimeSessionInfo use [" + (System.currentTimeMillis() - start) + "]");
    }
}

spring-scheduler.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:ss="http://www.springframework.org/schema/security"
	xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
   	http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
   	http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context.xsd
   	http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
   	http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
   	http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

	<!-- 线程执行器配置,用于任务注册 -->
	<bean id="executor"
		  class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<property name="corePoolSize" value="5" />
		<property name="maxPoolSize" value="20" />
		<property name="queueCapacity" value="500" />
	</bean>

	<!-- 启动触发器的配置开始 -->
	<bean name="startQuertz" lazy-init="false" autowire="no" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
		<property name="triggers">
			<list>
				<ref bean="sessionsJobTrigger" />
			</list>
		</property>
	</bean>

	<bean id="sessionsJobTrigger"  class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
		<property name="jobDetail">
			<ref bean="sessionsJobDetail" />
		</property>
		<property name="cronExpression">
			<!--每30分钟执行一次调度任务 -->
			<value>0 */30 * * * ?</value>
		</property>
	</bean>

	<bean id="sessionsJobDetail"  class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
		<property name="targetObject">
			<ref bean="sessionsJob" />
		</property>
		<property name="targetMethod">
			<value>removeOvertimeSessionInfo</value>
		</property>
	</bean>

	<!-- 工作的bean -->
	<bean id="sessionsJob" class="counting.corn.job.session.SystemSessionsScheduler" />
</beans>


/**
 * 验证帮助类
 * 
 */
public class AuthUtil {
    //Cookie标识
    public final static String COOKIEID = "_passengerFlow_sessionId";
    //Session前缀
    public final static String SESS_PREFIX = "pfcSess:";


    /**
     * 获取Session中的登录用户
     *
     * @param request 请求
     * @return 登录用户信息
     */
    public static UserLoginInfoVO getSessionUserAuth(HttpServletRequest request) {
        String cookieValue = CookieUtil.getCookieValue(request, COOKIEID);
        if (null == cookieValue)
            return null;
        else
            return (UserLoginInfoVO) StaticContainer.getSystemSessions().get(cookieValue);
    }

    /**
     * 功能描述: 如果登录的时候 没有 cookie信息 登录时重新生成cookie信息 然后将其插入到本地缓存sessions中<br>
     * 〈功能详细描述〉
     *
     * @param cookieValue Cookie值
     * @param userEntity  用户实体
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static void setSessionAccountAuth(String cookieValue, UserLoginInfoVO userEntity) {
        StaticContainer.getSystemSessions().put(cookieValue, userEntity);
        return;
    }

    /**
     * 保存Session验证信息
     *
     * @param request    请求
     * @param userEntity 用户实体
     */
    public static void setSessionAccountAuth(HttpServletRequest request, UserLoginInfoVO userEntity) {
        StaticContainer.getSystemSessions().put(CookieUtil.getCookieValue(request, COOKIEID), userEntity);
        return;
    }

    /**
     * 移除Session中的验证用户
     *
     * @param request 请求
     */
    public static void removeSessionUserAuth(HttpServletRequest request) {
        StaticContainer.getSystemSessions().remove(CookieUtil.getCookieValue(request, COOKIEID));
        return;
    }

    /**
     * 获取Session中的超时时间,即web.xml中的session-timeout元素
     *
     * @param request 请求
     * @return 时间(分钟)
     */
    public static int getMaxInactiveInterval(HttpServletRequest request) {
        int times = request.getSession().getMaxInactiveInterval();
        if (times == 0) {
            times = 1800;
        }
        return times;
    }
}

/**
 * Cookie帮助类
 *
 */
public class CookieUtil {
    //log
    private static final Logger logger = LoggerFactory.getLogger(CookieUtil.class);

    /**
     * 获取Cookie中指定用户值
     *
     * @param request 请求
     * @param name    用户
     * @return cookie值
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie cookie = getCookie(request, name);
        if (cookie != null) {
            return cookie.getValue();
        } else {
            return null;
        }
    }

    /**
     * 获取Cookie
     *
     * @param request 请求
     * @param name    用户
     * @return cookie
     */
    public static Cookie getCookie(HttpServletRequest request, String name) {
        return WebUtils.getCookie(request, name);
    }

    /**
     * 设置Cookie
     *
     * @param request  请求
     * @param response 响应
     * @param name     用户
     * @param value    值
     * @param maxAge   最大时效
     */
    public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name, String value, int maxAge) {
        try {
            //用户访问的域名
            String doMain = request.getServerName();
            setCookie(response, name, value, doMain, maxAge);
        } catch (Exception e) {
            logger.error("error:", e);
        }
    }

    /**
     * 设置Cookie
     *
     * @param response 响应
     * @param name     用户
     * @param value    值
     * @param doMain   域
     * @param maxAge   最大时效
     */
    public static void setCookie(HttpServletResponse response, String name, String value, String doMain, int maxAge) {
        if (value == null) {
            value = "";
        }
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);

        if (StringUtils.isNotEmpty(doMain) && !"localhost".equals(doMain)) {
            cookie.setDomain(doMain);
        }
        cookie.setPath("/");
        response.addCookie(cookie);
    }

    /**
     * 功能描述: 动态生成一个32位的cookie value<br>
     * 〈功能详细描述〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static String getUuid32() {
        UUID uuid = UUID.randomUUID();
        String cookieValue = uuid.toString().replaceAll("-", "");
        logger.info("new cookie from uuid:" + cookieValue);
        return cookieValue;
    }
}


/**
 * 初始化容器类<br>
 * 〈功能详细描述〉
 *
 *
 * @see [相关类/方法](可选)
 * @since [产品/模块版本] (可选)
 */
public class StaticContainer {
    /**
     * 用户session资源存放
     */
    protected static final ConcurrentMap<String, Object> systemSessions = new ConcurrentHashMap<String, Object>();

    public static ConcurrentMap<String, Object> getSystemSessions() {
        return systemSessions;
    }
}


redis工具类:

**
 * Redis操作工具类
 * 
 */
public final class RedisUtils {
    //log
    private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    //pptv 超时时间 5s
    public static final int PPTV_LOCK_EXPIRE_TIME=5000;
    protected static ShardedJedisClientImpl shardedClient;
    private static RedisUtils redis = null;

    /**
     * 功能描述: <br>
     * 〈获取实例〉
     *
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public static synchronized RedisUtils getInstance() {
        if (redis == null) {
            shardedClient = new ShardedJedisClientImpl("redis.conf");
            redis = new RedisUtils();
        }
        return redis;
    }

    /**
     * 返回key所关联的序列化对象。如果key不存在则返回null。 </br>时间复杂度O(1)
     *
     * @param key
     * @return
     */
    public String get(final String key) {
        return shardedClient.execute(new ShardedJedisAction<String>() {
            @Override
            public String doAction(ShardedJedis shardedJedis) {
                return shardedJedis.get(key);
            }
        });
    }

    /**
     * 功能描述: <br>
     * 返回hash
     *
     * @param key
     * @return
     * @see [相关类/方法](可选)
     * @since [产品/模块版本](可选)
     */
    public Map<String, String> hgetAll(final String key) {
        return shardedClient.execute(new ShardedJedisAction<Map<String, String>>() {
            @Override
            public Map<String, String> doAction(ShardedJedis shardedJedis) {
                return shardedJedis.hgetAll(key);
            }
        });
    }


    /**
     * 获取Redis Key值对应的值类型
     *
     * @param key key
     * @return 值类型
     */
    public String getType(final String key) {
        return shardedClient.execute(new ShardedJedisAction<String>() {
            @Override
            public String doAction(ShardedJedis shardedJedis) {
                return shardedJedis.type(key);
            }
        });
    }



    //将序列化对象值value关联到key, 如果key已经持有其他值,SET就覆写旧值,无视类型 时间复杂度O(1)
    public String set(final String key, final String value,final int expireTime) {
        return shardedClient.execute(new ShardedJedisAction<String>() {
            @Override
            public String doAction(ShardedJedis shardedJedis) {
                String result = shardedJedis.set(key, value);
                shardedJedis.expire(key, expireTime);
                return result;
            }
        });
    }

    /**
     * 移除给定的key。如果key不存在,则忽略该命令。 <\br>时间复杂度O(1)
     *
     * @param key
     * @return
     */
    public Long del(final String key) {
        return shardedClient.execute(new ShardedJedisAction<Long>() {
            @Override
            public Long doAction(ShardedJedis shardedJedis) {
                return shardedJedis.del(key);
            }
        });
    }

    /**
     * 为给定key设置生存时间,当key过期时,它会被自动删除<\br> 时间复杂度O(1)
     *
     * @param key
     * @param seconds 秒
     * @return 1:成功; 0:key不存在或不能为key设置生存时间时
     */
    public static Long expire(final String key, final int seconds) {
        return shardedClient.execute(new ShardedJedisAction<Long>() {
            @Override
            public Long doAction(ShardedJedis shardedJedis) {
                return shardedJedis.expire(key, seconds);
            }
        });
    }

    /**
     * TTL命令用于获取键到期的剩余时间(毫秒)
     * 以毫秒为单位的整数值TTL或负值
     * TTL以毫秒为单位。
     * -1, 如果key没有到期超时。
     * -2, 如果键不存在。
     *
     * @param key
     * @return
     */
    public Long ttl(final String key) {
        return shardedClient.execute(new ShardedJedisAction<Long>() {
            @Override
            public Long doAction(ShardedJedis shardedJedis) {
                return shardedJedis.ttl(key);
            }
        });
    }

    /**
     * 打印Redis分片信息
     * @return 分片信息
     */
    public String info() {
        return shardedClient.execute(new ShardedJedisAction<String>() {
            @Override
            public String doAction(ShardedJedis shardedJedis) {
                StringBuffer info = new StringBuffer("");
                Collection<Jedis> shards = shardedJedis.getAllShards();
                for (Jedis shard : shards) {
                    info.append(shard.info());
                }
                return info.toString();
            }
        });
    }
    /**
     * 设置指定的字符串值,并返回其旧值
     * @param  key
     * @param  value
     * @return oldValue
     */
    public String getSet(final String key,final String value){
        return shardedClient.execute( new ShardedJedisAction<String>() {
            @Override
            public String doAction(ShardedJedis shardedJedis) {
                return shardedJedis.getSet(key, value);
            }
        });
    }


    /**
     * 判断是否获取锁
     * @param key KEY
     * @param timeout 超时时间
     * @return 是否获取锁
     */
    public boolean isGetLock(final String key, final long timeout){
        return shardedClient.execute(new ShardedJedisAction<Boolean>() {
            @Override
            public Boolean doAction(ShardedJedis shardedJedis) {
                long expireTimeValue=System.currentTimeMillis();//当前时间
                String expireTimeStr=String.valueOf(expireTimeValue);
                do {
                    Long setnx = shardedJedis.setnx(key, expireTimeStr);//当前时间戳作为value
                    if (setnx == 1) { //获取锁
                        //设置锁的超时时间
                        expire(key, PPTV_LOCK_EXPIRE_TIME);
                        logger.debug("get lock, key: " + key + " , expire in " + PPTV_LOCK_EXPIRE_TIME + " seconds.");
                        return true;
                    } else {  // 锁被占用
                        String value = get(key);//获取redis中的时间戳
                        //判断锁是否超时
                        if(value !=null && (System.currentTimeMillis()-Long.parseLong(value) )>timeout){
                            String oldValue=getSet(key,expireTimeStr);
                            //如果拿到的oldValue依然是超时的,说明已经拿到锁了
                            if(oldValue !=null && (System.currentTimeMillis()-Long.parseLong(oldValue) )>timeout){
                                return true;
                            }
                        }
                    }
                    if (timeout == 0) { //取不到锁时,不等待,直接返回
                        break;
                    }
                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        logger.error(e.getMessage());
                    }
                }while((System.currentTimeMillis()-expireTimeValue)<timeout);
                return false;
            }
        });

    }

    /**
     * 释放锁
     */
    public Long unlock(final String key){
        logger.debug("release lock, keys :" + key);
        return  del(key);
    }

    /**
     * 从队列的头部(左边)弹出元素
     *
     * @param key
     * @return
     */
    public static String lpop(final String key){
        return shardedClient.execute( new ShardedJedisAction<String>() {
            @Override
            public String doAction(ShardedJedis shardedJedis) {
                return shardedJedis.lpop(key);
            }
        });
    }

    /**
     * 返回列表的长度
     *
     * @param key
     * @return
     */
    public static Long llen(final String key){
        return shardedClient.execute(new ShardedJedisAction<Long>() {
            @Override
            public Long doAction(ShardedJedis shardedJedis) {
                return shardedJedis.llen(key);
            }
        });
    }

    /**
     * 向队列的尾部(右边)加入元素
     *
     * @param key
     * @param value
     * @return
     */
    public static Long rpush(final String key, final String value){
        return shardedClient.execute( new ShardedJedisAction<Long>() {
            @Override
            public Long doAction(ShardedJedis shardedJedis) {
                return shardedJedis.rpush(key, value);
            }
        });
    }

}

ShardedJedisClientImpl :
public class ShardedJedisClientImpl extends AbstractClient implements ShardedJedisClient {
    private static final Logger logger = LoggerFactory.getLogger(ShardedJedisClientImpl.class);

    public ShardedJedisClientImpl(String configFile) {
        super(configFile);
    }

    public ShardedJedisClientImpl(String configPath, boolean globalConfig) {
        super(configPath, globalConfig);
    }

    public void destroy() {
        super.destroy();
    }

    public <T> T execute(ShardedJedisAction<T> action) {
        try {
            T result = this.executeAction(action);
            return result;
        } catch (Exception var4) {
            throw new RedisClientException(var4);
        }
    }

    private <T> T executeAction(ShardedJedisAction<T> action) {
        SmartShardedJedisPool pool = this.getSmartShardedJedisPool();
        ShardedJedis shardedJedis = null;

        Object var4;
        try {
            shardedJedis = (ShardedJedis)pool.getResource();
            var4 = action.doAction(shardedJedis);
        } catch (JedisConnectionException var15) {
            if(shardedJedis != null) {
                try {
                    pool.returnBrokenResource(shardedJedis);
                } catch (Exception var14) {
                    logger.warn("Can not return broken resource.", var14);
                }

                shardedJedis = null;
            }

            throw var15;
        } finally {
            if(shardedJedis != null) {
                try {
                    pool.returnResource(shardedJedis);
                } catch (Exception var13) {
                    logger.warn("Can not return resource.", var13);
                }
            }

        }

        return var4;
    }
}

public abstract class AbstractClient {
    private static final Map<String, SmartShardedJedisPool> smartShardedJedisPools = new ConcurrentHashMap();
    private static final Object MUX = new Object();
    private static final String GLOBAL_WARNING_CONFIG_PATH = "/monitor.warning.service";
    private static SCMNode globalWarnConfigNode;
    private SCMNode redisConfigNode;
    private String configPath;
    private final SCMListener redisConfigListener;

    protected AbstractClient(String configPath) {
        this(configPath, false);
    }

    protected AbstractClient(String configPath, boolean globalConfig) {
        this.redisConfigListener = new SCMListener() {
            public void execute(String oldValue, String newValue) {
                if(newValue != null && !"".equals(newValue.trim())) {
                    SmartShardedJedisPool shardedJedisPoolx;
                    if(AbstractClient.this.notEqual(AbstractClient.XMLParser.parseSentinels(oldValue), AbstractClient.XMLParser.parseSentinels(newValue)) 
                       || AbstractClient.this.notEqual(AbstractClient.XMLParser.parseMasters(oldValue), AbstractClient.XMLParser.parseMasters(newValue)) 
              || AbstractClient.this.notEqual(AbstractClient.XMLParser.parse(oldValue, "timeOut"), AbstractClient.XMLParser.parse(newValue, "timeOut")) 
          || AbstractClient.this.notEqual(AbstractClient.XMLParser.parse(oldValue, "dbIndex"), AbstractClient.XMLParser.parse(newValue, "dbIndex"))) {
                        synchronized(AbstractClient.MUX) {
   shardedJedisPoolx = AbstractClient.XMLParser.parse(AbstractClient.this.redisConfigNode.getValue(), 
(WarningService)AbstractClient.this.makeWarningService());
  SmartShardedJedisPool oldPool = (SmartShardedJedisPool)AbstractClient.smartShardedJedisPools.put(AbstractClient.this.configPath, shardedJedisPoolx);
                            if(oldPool != null) {
                                try {
                                    Thread.sleep(5000L);
                                } catch (Exception var8) {
                                    ;
                                }

                                oldPool.destroy();
                            }
                        }
                    }

          if(AbstractClient.this.notEqual(AbstractClient.XMLParser.poolConfig(oldValue, "maxIdle"), 
                  AbstractClient.XMLParser.poolConfig(newValue, "maxIdle"))) {
  PoolStatusUtil.setMaxIdle(AbstractClient.this.getSmartShardedJedisPool(),
 AbstractClient.XMLParser.poolConfig(AbstractClient.this.redisConfigNode.getValue(), "maxIdle"));
                    }

  if(AbstractClient.this.notEqual(AbstractClient.XMLParser.poolConfig(oldValue, "minIdle"), AbstractClient.XMLParser.poolConfig(newValue, "minIdle"))) {
                        PoolStatusUtil.setMinIdle(AbstractClient.this.getSmartShardedJedisPool(),
                          AbstractClient.XMLParser.poolConfig(AbstractClient.this.redisConfigNode.getValue(), "minIdle"));
                    }

                    SmartShardedJedisPool shardedJedisPool;
    if(AbstractClient.this.notEqual(AbstractClient.XMLParser.parse(oldValue, "phones"), AbstractClient.XMLParser.parse(newValue, "phones"))) {
                        shardedJedisPool = AbstractClient.this.getSmartShardedJedisPool();
                        if(shardedJedisPool != null) {
                            shardedJedisPool.setWarningService(AbstractClient.this.makeWarningService());
                        }
                    }

                    if(AbstractClient.this.notEqual(AbstractClient.XMLParser.forceMasterKeys(oldValue), 
AbstractClient.XMLParser.forceMasterKeys(newValue)) || AbstractClient.this.notEqual(AbstractClient.XMLParser.parse(oldValue, "forceMaster"), 
AbstractClient.XMLParser.parse(newValue, "forceMaster"))) {
                        shardedJedisPool = AbstractClient.this.getSmartShardedJedisPool();
                        if(shardedJedisPool != null) {
                            shardedJedisPool.setRwPolicy(AbstractClient.XMLParser.parseRwPolicy(AbstractClient.this.redisConfigNode.getValue()));
                        }
                    }

                    if(AbstractClient.this.notEqual(AbstractClient.XMLParser.parse(oldValue, "execTimeThreshold"), 
AbstractClient.XMLParser.parse(newValue, "execTimeThreshold"))) {
                        String execTimeThreshold = AbstractClient.XMLParser.parse(AbstractClient.this.redisConfigNode.getValue(), "execTimeThreshold");
                        if(null == execTimeThreshold || "".equals(execTimeThreshold.trim())) {
                            execTimeThreshold = "20";
                        }

                        shardedJedisPoolx = AbstractClient.this.getSmartShardedJedisPool();
                        if(shardedJedisPoolx != null) {
                            shardedJedisPoolx.setExecTimeThreshold(Long.valueOf(execTimeThreshold));
                        }
                    }

                }
            }
        };
        this.configPath = globalConfig?"GLOBAL." + configPath:"PROJECT." + configPath;
        if(!smartShardedJedisPools.containsKey(this.configPath)) {
            Object var3 = MUX;
            synchronized(MUX) {
                if(!smartShardedJedisPools.containsKey(this.configPath)) {
                    VersionStatistics.reportVersion(AbstractClient.class);
                    SCMClient scmClient = SCMClientImpl.getInstance();
                    globalWarnConfigNode = scmClient.getGlobalConfig("/monitor.warning.service");
                    globalWarnConfigNode.sync();
                    if(globalConfig) {
                        this.redisConfigNode = scmClient.getGlobalConfig(configPath);
                        this.redisConfigNode.sync();
                    } else {
                        this.redisConfigNode = scmClient.getConfig(configPath);
                        this.redisConfigNode.sync();
                    }

                    String redisConfig = this.redisConfigNode.getValue();
                    if(redisConfig != null && !"".equals(redisConfig.trim())) {
                        String globalWarnConfig = globalWarnConfigNode.getValue();
                        if(globalWarnConfig != null && !"".equals(globalWarnConfig.trim())) {
                            SmartShardedJedisPool pool = AbstractClient.XMLParser.parse(this.redisConfigNode.getValue(),
                            (WarningService)this.makeWarningService());
                            smartShardedJedisPools.put(this.configPath, pool);
                            globalWarnConfigNode.monitor(new SCMListener() {
                                public void execute(String oldValue, String newValue) {
                                    SmartShardedJedisPool shardedJedisPool = AbstractClient.this.getSmartShardedJedisPool();
                                    if(shardedJedisPool != null) {
                                        shardedJedisPool.setWarningService(AbstractClient.this.makeWarningService());
                                    }

                                }
                            });
                            this.redisConfigNode.monitor(this.redisConfigListener);
                            return;
                        }

                        throw new RedisClientException("can't find warningService config or config is empty.");
                    }

                    throw new RedisClientException("can't find redis config or config content is empty.");
                }
            }
        }

    }

    private boolean notEqual(Set<String> setA, Set<String> setB) {
        List<String> listA = new ArrayList(setA);
        List<String> listB = new ArrayList(setB);
        return this.notEqual((List)listA, (List)listB);
    }

    private boolean notEqual(List<String> listA, List<String> listB) {
        Collections.sort(listA, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return s1.compareToIgnoreCase(s2);
            }
        });
        Collections.sort(listB, new Comparator<String>() {
            public int compare(String s1, String s2) {
                return s1.compareToIgnoreCase(s2);
            }
        });
        StringBuilder strA = new StringBuilder();
        Iterator i$ = listA.iterator();

        while(i$.hasNext()) {
            String s = (String)i$.next();
            strA.append(s.trim());
        }

        StringBuilder strB = new StringBuilder();
        Iterator i$ = listB.iterator();

        while(i$.hasNext()) {
            String s = (String)i$.next();
            strB.append(s.trim());
        }

        return this.notEqual(strA.toString(), strB.toString());
    }

    private boolean notEqual(String strA, String strB) {
        return strA != null && strB != null && !strA.trim().equalsIgnoreCase(strB.trim());
    }

    public SmartShardedJedisPool getSmartShardedJedisPool() {
        return (SmartShardedJedisPool)smartShardedJedisPools.get(this.configPath);
    }

    public void setMasterChangedListener(MasterChangedListener masterChangedListener) {
        this.getSmartShardedJedisPool().setMasterChangedListener(masterChangedListener);
    }

    protected void destroy() {
        Object var1 = MUX;
        synchronized(MUX) {
            SmartShardedJedisPool pool = this.getSmartShardedJedisPool();
            if(pool != null) {
                pool.destroy();
            }

            smartShardedJedisPools.remove(this.configPath);
        }
    }

    protected SNWarningService makeWarningService() {
        Properties properties = new Properties();
        StringReader reader = new StringReader(globalWarnConfigNode.getValue());

        try {
            properties.load(reader);
        } catch (IOException var11) {
            throw new RedisClientException("load warning config error");
        }

        String appCode = SCMClientImpl.getInstance().getAppCode();
        String url = (String)properties.get("monitor.service.server");
        String globalPhones = (String)properties.get("sedis.warning.phones");
        String phones = AbstractClient.XMLParser.parse(this.redisConfigNode.getValue(), "phones");
        Set<String> phonesSet = new HashSet();
        phonesSet.addAll(Arrays.asList(globalPhones.split("\\,")));
        phonesSet.addAll(Arrays.asList(phones.split("\\,")));
        StringBuilder allPhones = new StringBuilder();
        Iterator i$ = phonesSet.iterator();

        while(i$.hasNext()) {
            String str = (String)i$.next();
            allPhones.append(",");
            allPhones.append(str);
        }

        allPhones.delete(0, 1);
        return new SNWarningService(appCode, url, allPhones.toString());
    }

    public String getPoolStatus() {
        return PoolStatusUtil.getPoolStatus(this.getSmartShardedJedisPool());
    }

    private static class XMLParser {
        private static Logger logger = LoggerFactory.getLogger(AbstractClient.XMLParser.class);
        private static XPath path;
        private static Document doc;

        private XMLParser() {
        }

        private static String getString(Object node, String expression) throws XPathExpressionException {
            return (String)path.evaluate(expression, node, XPathConstants.STRING);
        }

        private static NodeList getList(Object node, String expression) throws XPathExpressionException {
            return (NodeList)path.evaluate(expression, node, XPathConstants.NODESET);
        }

        private static Node getNode(Object node, String expression) throws XPathExpressionException {
            return (Node)path.evaluate(expression, node, XPathConstants.NODE);
        }

        public static String parse(String redisConfig, String key) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    return getString(rootN, key);
                }
            } catch (Exception var6) {
                throw new RedisClientException("Fail to parse redis configure file.", var6);
            }
        }

        public static String poolConfig(String redisConfig, String field) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    Node poolConfigNode = getNode(rootN, "poolConfig");
                    return getString(poolConfigNode, field);
                }
            } catch (Exception var7) {
                throw new RedisClientException("Fail to parse redis configure file.", var7);
            }
        }

        public static Set<String> parseSentinels(String redisConfig) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    Node sentinelNode = getNode(rootN, "sentinels");
                    Set<String> sentinels = new HashSet();
                    NodeList sentinelConfigs = getList(sentinelNode, "sentinel");

                    for(int i = 0; i < sentinelConfigs.getLength(); ++i) {
                        Node sentinelConfig = sentinelConfigs.item(i);
                        String ip = getString(sentinelConfig, "ip");
                        String port = getString(sentinelConfig, "port");
                        sentinels.add(ip + ":" + port);
                    }

                    return sentinels;
                }
            } catch (Exception var12) {
                throw new RedisClientException("Fail to parse redis configure file.", var12);
            }
        }

        public static List<String> parseMasters(String redisConfig) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    List<String> masters = new ArrayList();
                    Node mastersNode = getNode(rootN, "shards");
                    if(mastersNode != null) {
                        NodeList masterNodes = getList(mastersNode, "shardName");

                        for(int i = 0; i < masterNodes.getLength(); ++i) {
                            String master = masterNodes.item(i).getTextContent();
                            masters.add(master);
                        }
                    }

                    return masters;
                }
            } catch (Exception var10) {
                throw new RedisClientException("Fail to parse redis configure file.", var10);
            }
        }

        public static List<String> forceMasterKeys(String redisConfig) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    List<String> forceMasterKeys = new ArrayList();
                    Node forceMasterKeysNode = getNode(rootN, "forceMasterkeys");
                    if(forceMasterKeysNode != null) {
                        NodeList keyPatternNodes = getList(forceMasterKeysNode, "keyPattern");

                        for(int i = 0; i < keyPatternNodes.getLength(); ++i) {
                            String master = keyPatternNodes.item(i).getTextContent();
                            forceMasterKeys.add(master);
                        }
                    }

                    return forceMasterKeys;
                }
            } catch (Exception var10) {
                throw new RedisClientException("Fail to parse redis configure file.", var10);
            }
        }

        public static RwPolicy parseRwPolicy(String redisConfig) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    RwPolicy rwPolicy = null;
                    Node forceMasterKeysNode = getNode(rootN, "forceMasterkeys");
                    if(forceMasterKeysNode != null) {
                        NodeList keyPatternNodes = getList(forceMasterKeysNode, "keyPattern");
                        if(keyPatternNodes != null) {
                            String[] keyPatterns = new String[keyPatternNodes.getLength()];

                            for(int i = 0; i < keyPatternNodes.getLength(); ++i) {
                                String keyPattern = keyPatternNodes.item(i).getTextContent();
                                keyPatterns[i] = keyPattern;
                            }

                            rwPolicy = new SimpleRwPolicy(keyPatterns);
                        }
                    }

                    if(rwPolicy == null) {
                        String forceMaster = getString(rootN, "forceMaster");
                        if(null == forceMaster || "".equals(forceMaster.trim())) {
                            forceMaster = "true";
                        }

                        Boolean isForceMaster = Boolean.valueOf(forceMaster);
                        if(isForceMaster.booleanValue()) {
                            rwPolicy = new SimpleRwPolicy(true);
                        } else {
                            rwPolicy = new SimpleRwPolicy(false);
                        }
                    }

                    return rwPolicy;
                }
            } catch (Exception var11) {
                throw new RedisClientException("Fail to parse redis configure file.", var11);
            }
        }

        public static SmartShardedJedisPool parse(String redisConfig, WarningService warningService) {
            try {
                StringReader reader = new StringReader(redisConfig);
                InputSource is = new InputSource(reader);
                DocumentBuilder dbd = DocumentBuilderFactory.newInstance().newDocumentBuilder();
                doc = dbd.parse(is);
                path = XPathFactory.newInstance().newXPath();
                Node rootN = getNode(doc, "config");
                if(null == rootN) {
                    throw new RedisClientException("Invalid xml format, can't find <config> root node!");
                } else {
                    String timeOut = getString(rootN, "timeOut");
                    if(null == timeOut || "".equals(timeOut.trim())) {
                        timeOut = "2000";
                    }

                    String password = getString(rootN, "password");
                    if(null == password || "".equals(password.trim())) {
                        password = null;
                    }

                    String dbIndex = getString(rootN, "dbIndex");
                    if(null == dbIndex || "".equals(dbIndex.trim())) {
                        dbIndex = "0";
                    }

                    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
                    Node poolConfigNode = getNode(rootN, "poolConfig");
                    String numTestsPerEvictionRun;
                    String evictionPolicyClassName;
                    String testOnBorrow;
                    String testOnReturn;
                    String jmxEnabled;
                    if(poolConfigNode != null) {
                        poolConfig.setMaxTotal(2147483647);
                        poolConfig.setMaxWaitMillis(200L);
                        poolConfig.setBlockWhenExhausted(false);
                        String maxIdle = getString(poolConfigNode, "maxIdle");
                        if(null != maxIdle && !"".equals(maxIdle.trim())) {
                            poolConfig.setMaxIdle(Integer.valueOf(maxIdle).intValue());
                        }

                        String minIdle = getString(poolConfigNode, "minIdle");
                        if(null != minIdle && !"".equals(minIdle.trim())) {
                            poolConfig.setMinIdle(Integer.valueOf(minIdle).intValue());
                        }

                        String lifo = getString(poolConfigNode, "lifo");
                        if(null != lifo && !"".equals(lifo.trim())) {
                            poolConfig.setLifo(Boolean.valueOf(lifo).booleanValue());
                        }

                        String minEvictableIdleTimeMillis = getString(poolConfigNode, "minEvictableIdleTimeMillis");
                        if(null != minEvictableIdleTimeMillis && !"".equals(minEvictableIdleTimeMillis.trim())) {
                            poolConfig.setMinEvictableIdleTimeMillis(Long.valueOf(minEvictableIdleTimeMillis).longValue());
                        } else {
                            poolConfig.setMinEvictableIdleTimeMillis(60000L);
                        }

                        String softMinEvictableIdleTimeMillis = getString(poolConfigNode, "softMinEvictableIdleTimeMillis");
                        if(null != softMinEvictableIdleTimeMillis && !"".equals(softMinEvictableIdleTimeMillis.trim())) {
                            poolConfig.setSoftMinEvictableIdleTimeMillis(Long.valueOf(softMinEvictableIdleTimeMillis).longValue());
                        }

                        numTestsPerEvictionRun = getString(poolConfigNode, "numTestsPerEvictionRun");
                        if(null != numTestsPerEvictionRun && !"".equals(numTestsPerEvictionRun.trim())) {
                            poolConfig.setNumTestsPerEvictionRun(Integer.valueOf(numTestsPerEvictionRun).intValue());
                        } else {
                            poolConfig.setNumTestsPerEvictionRun(-1);
                        }

                        evictionPolicyClassName = getString(poolConfigNode, "evictionPolicyClassName");
                        if(null != evictionPolicyClassName && !"".equals(evictionPolicyClassName.trim())) {
                            poolConfig.setEvictionPolicyClassName(evictionPolicyClassName);
                        }

                        testOnBorrow = getString(poolConfigNode, "testOnBorrow");
                        if(null != testOnBorrow && !"".equals(testOnBorrow.trim())) {
                            poolConfig.setTestOnBorrow(Boolean.valueOf(testOnBorrow).booleanValue());
                        }

                        testOnReturn = getString(poolConfigNode, "testOnReturn");
                        if(null != testOnReturn && !"".equals(testOnReturn.trim())) {
                            poolConfig.setTestOnReturn(Boolean.valueOf(testOnReturn).booleanValue());
                        }

                        String testWhileIdle = getString(poolConfigNode, "testWhileIdle");
                        if(null != testWhileIdle && !"".equals(testWhileIdle.trim())) {
                            poolConfig.setTestWhileIdle(Boolean.valueOf(testWhileIdle).booleanValue());
                        } else {
                            poolConfig.setTestWhileIdle(true);
                        }

                        String timeBetweenEvictionRunsMillis = getString(poolConfigNode, "timeBetweenEvictionRunsMillis");
                        if(null != timeBetweenEvictionRunsMillis && !"".equals(timeBetweenEvictionRunsMillis.trim())) {
                            poolConfig.setTimeBetweenEvictionRunsMillis(Long.valueOf(timeBetweenEvictionRunsMillis).longValue());
                        } else {
                            poolConfig.setTimeBetweenEvictionRunsMillis(30000L);
                        }

                        jmxEnabled = getString(poolConfigNode, "jmxEnabled");
                        if(null != jmxEnabled && !"".equals(jmxEnabled.trim())) {
                            poolConfig.setJmxEnabled(Boolean.valueOf(jmxEnabled).booleanValue());
                        }

                        String jmxNamePrefix = getString(poolConfigNode, "jmxNamePrefix");
                        if(null != jmxNamePrefix && !"".equals(jmxNamePrefix.trim())) {
                            poolConfig.setJmxNamePrefix(jmxNamePrefix);
                        }
                    }

                    Node sentinelNode = getNode(rootN, "sentinels");
                    Set<String> sentinels = new HashSet();
                    NodeList sentinelConfigs = getList(sentinelNode, "sentinel");
                    if(sentinelConfigs.getLength() != 0 && sentinelConfigs.getLength() < 3) {
                        throw new RedisClientException("Configuration error,no less than 3 sentinels");
                    } else {
                        Node mastersNode;
                        for(int i = 0; i < sentinelConfigs.getLength(); ++i) {
                            mastersNode = sentinelConfigs.item(i);
                            numTestsPerEvictionRun = getString(mastersNode, "ip");
                            evictionPolicyClassName = getString(mastersNode, "port");
                            if(null == numTestsPerEvictionRun || "".equals(numTestsPerEvictionRun.trim())) {
                                throw new RedisClientException("Configuration error,sentinel host can not be null");
                            }

                            if(null == evictionPolicyClassName || "".equals(evictionPolicyClassName.trim())) {
                                evictionPolicyClassName = "26379";
                            }

                            sentinels.add(numTestsPerEvictionRun + ":" + evictionPolicyClassName);
                        }

                        List<String> masters = new ArrayList();
                        mastersNode = getNode(rootN, "shards");
                        if(mastersNode == null) {
                            throw new RedisClientException("Configuration error, <shards> can not be null in <shardConfig> ");
                        } else {
                            NodeList masterNodes = getList(mastersNode, "shardName");
                            if(masterNodes.getLength() == 0) {
                                throw new RedisClientException("Configuration error, <shardName> can not be null in <shards> ");
                            } else {
                                for(int i = 0; i < masterNodes.getLength(); ++i) {
                                    testOnBorrow = masterNodes.item(i).getTextContent();
                                    if(null == testOnBorrow || "".equals(testOnBorrow.trim())) {
                                        throw new RedisClientException("Configuration error,<master> can not be null in <shard>");
                                    }

                                    masters.add(testOnBorrow);
                                }

                                RwPolicy rwPolicy = null;
                                Node forceMasterKeysNode = getNode(rootN, "forceMasterkeys");
                                if(forceMasterKeysNode != null) {
                                    NodeList keyPatternNodes = getList(forceMasterKeysNode, "keyPattern");
                                    if(keyPatternNodes != null) {
                                        String[] keyPatterns = new String[keyPatternNodes.getLength()];

                                        for(int i = 0; i < keyPatternNodes.getLength(); ++i) {
                                            jmxEnabled = keyPatternNodes.item(i).getTextContent();
                                            keyPatterns[i] = jmxEnabled;
                                        }

                                        rwPolicy = new SimpleRwPolicy(keyPatterns);
                                    }
                                }

                                if(rwPolicy == null) {
                                    testOnReturn = getString(rootN, "forceMaster");
                                    if(null == testOnReturn || "".equals(testOnReturn.trim())) {
                                        testOnReturn = "true";
                                    }

                                    Boolean isForceMaster = Boolean.valueOf(testOnReturn);
                                    if(isForceMaster.booleanValue()) {
                                        rwPolicy = new SimpleRwPolicy(true);
                                    } else {
                                        rwPolicy = new SimpleRwPolicy(false);
                                    }
                                }

                                testOnReturn = getString(rootN, "execTimeThreshold");
                                if(null == testOnReturn || "".equals(testOnReturn.trim())) {
                                    testOnReturn = "20";
                                }

                                Reporter.report();
                                return new SmartShardedJedisPool(masters, sentinels, poolConfig, Integer.valueOf(timeOut).intValue(), password, 
                          Integer.valueOf(dbIndex).intValue(), rwPolicy, warningService, Long.valueOf(testOnReturn));
                            }
                        }
                    }
                }
            } catch (IOException var24) {
                logger.error("IOException!", var24);
                throw new RedisClientException("IOException!", var24);
            } catch (Exception var25) {
                throw new RedisClientException("Fail to parse redis configure file.", var25);
            }
        }
    }
}

public interface ShardedJedisClient {
    void destroy();

    <T> T execute(ShardedJedisAction<T> var1);
}


在web.xml中配置:

<session-config>
    <session-timeout>30</session-timeout>
</session-config>



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值