Commit edddf672 by cjh

更新redis连接方式,添加过期key监听

parent fe91fa64
......@@ -188,8 +188,13 @@
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.3.0.RELEASE</version>
</dependency>
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
......
......@@ -12,4 +12,6 @@ public class Constants {
public final static String DISPLAY_FILE_NAME = "fileName";
public final static String MAPPING_PRE = "_";
public final static String SESSION = "session";
}
......@@ -11,6 +11,7 @@ import org.springframework.web.servlet.ModelAndView;
import org.sss.presentation.noui.api.request.NoUiRequest;
import org.sss.presentation.noui.api.response.ErrorCodes;
import org.sss.presentation.noui.api.response.Result;
import org.sss.presentation.noui.common.Constants;
import org.sss.presentation.noui.context.NoUiContextManager;
import org.sss.presentation.noui.util.NumericUtil;
import org.sss.presentation.noui.util.RedisUtil;
......@@ -49,7 +50,7 @@ public class OpenTransInterceptor implements HandlerInterceptor {
if (redisLoginInfo != null && System.currentTimeMillis() <= redisLoginInfo.getExpiredTime()) {
// 重新刷入登陆时间
RedisLoginInfo nweRedisLoginInfo = new RedisLoginInfo(userId, token, NumericUtil.sessionTimeOut(), redisLoginInfo.getSysmod());
RedisUtil.set(userId + "." + terminalType, nweRedisLoginInfo);
RedisUtil.set(Constants.SESSION + "." + userId + "." + terminalType, nweRedisLoginInfo);
}
String url = request.getRequestURI();
......
......@@ -10,6 +10,7 @@ import org.springframework.web.servlet.ModelAndView;
import org.sss.presentation.noui.api.request.NoUiRequest;
import org.sss.presentation.noui.api.response.ErrorCodes;
import org.sss.presentation.noui.api.response.Result;
import org.sss.presentation.noui.common.Constants;
import org.sss.presentation.noui.util.NumericUtil;
import org.sss.presentation.noui.util.RedisUtil;
import org.sss.presentation.noui.util.StringUtil;
......@@ -76,7 +77,7 @@ public class TokenInterceptor implements HandlerInterceptor {
// 重新刷入登陆时间
RedisLoginInfo nweRedisLoginInfo = new RedisLoginInfo(userId, token, NumericUtil.sessionTimeOut(), redisLoginInfo.getSysmod());
RedisUtil.set(userId + "." + terminalType, nweRedisLoginInfo);
RedisUtil.set(Constants.SESSION + "." + userId + "." + terminalType, nweRedisLoginInfo);
return true;
}
......
package org.sss.presentation.noui.redis;
import log.Log;
import log.LogFactory;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Service;
import org.sss.presentation.noui.common.Constants;
import org.sss.module.hibernate.HibernateUtils;
import org.sss.presentation.noui.jwt.RedisLoginInfo;
import org.sss.presentation.noui.util.RedisUtil;
@Service
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
protected static final Log log = LogFactory.getLog(RedisKeyExpirationListener.class);
public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
super(listenerContainer);
}
@Override
public void onMessage(Message message, byte[] pattern) {
//获取过期的key
String expireKey = message.toString();
log.debug("expireKey is:"+ expireKey);
if(expireKey.startsWith(Constants.SESSION)){
String[] arrayKey = expireKey.split("\\.");
if(arrayKey.length>2){
String userId = arrayKey[1];
Session session = HibernateUtils.openSession(null);
Transaction transaction = session.beginTransaction();
session.createSQLQuery("delete from lck where nam='"+userId+"'").executeUpdate();
transaction.commit();
session.close();
log.info("clear expire user "+userId+" session success");
}
}
}
}
package org.sss.presentation.noui.redis;
import log.Log;
import log.LogFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
@Configuration
public class RedisListenerConfig {
protected static final Log log = LogFactory.getLog(RedisListenerConfig.class);
@Bean
RedisMessageListenerContainer listenerContainer(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer listenerContainer = new RedisMessageListenerContainer();
listenerContainer.setConnectionFactory(connectionFactory);
return listenerContainer;
}
@Bean
KeyExpirationEventMessageListener redisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
log.debug("init redisKeyExpirationListener");
return new RedisKeyExpirationListener(listenerContainer);
}
}
package org.sss.presentation.noui.util;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.sss.presentation.noui.jwt.RedisLoginInfo;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import org.springframework.data.redis.core.RedisTemplate;
/**
* Redis连接池工具类
*/
public class RedisUtil {
private static JedisPool jedisPool = null;
private static String redisConfigFile = "redis.properties";
// 把redis连接对象放到本地线程中
private static RedisTemplate redisTemplate = SpringContextHolder.getBean(RedisTemplate.class);
private static String redisConfigFile = "redis.properties";
private static int sessionTimeOut = 1800;
static {
initialPool();
init();
}
public static void setSessionTimeOut(int time){
......@@ -29,61 +26,23 @@ public class RedisUtil {
return sessionTimeOut;
}
/**
* 初始化Redis连接池
*/
private static void initialPool() {
private static void init() {
try {
Properties props = new Properties();
// 加载连接池配置文件
// 加载配置文件
props.load(RedisUtil.class.getClassLoader().getResourceAsStream(redisConfigFile));
sessionTimeOut = Integer.valueOf(props.getProperty("sessionTimeOut"));
// 创建jedis池配置实例
JedisPoolConfig config = new JedisPoolConfig();
// 设置池配置项值
config.setMaxTotal(Integer.valueOf(props.getProperty("jedis.pool.maxActive")));
config.setMaxIdle(Integer.valueOf(props.getProperty("jedis.pool.maxIdle")));
config.setMaxWaitMillis(Long.valueOf(props.getProperty("jedis.pool.maxWait")));
config.setTestOnBorrow(Boolean.valueOf(props.getProperty("jedis.pool.testOnBorrow")));
config.setTestOnReturn(Boolean.valueOf(props.getProperty("jedis.pool.testOnReturn")));
// 根据配置实例化jedis池
String password = props.getProperty("redis.passWord");
if (StringUtil.isEmpty(password))
jedisPool = new JedisPool(config, props.getProperty("redis.ip"), Integer.valueOf(props.getProperty("redis.port")),
Integer.valueOf(props.getProperty("redis.timeout")));
else
jedisPool = new JedisPool(config, props.getProperty("redis.ip"), Integer.valueOf(props.getProperty("redis.port")),
Integer.valueOf(props.getProperty("redis.timeout")), password);
System.out.println("线程池被成功初始化");
} catch (Exception e) {
e.printStackTrace();
}
}
public static void set(String key, Object value) {
Jedis jedis = jedisPool.getResource();
jedis.set(key.getBytes(), SerializeUtil.serialize(value));
jedis.expire(key, sessionTimeOut);
jedis.close();
redisTemplate.opsForValue().set(key,value);
redisTemplate.expire(key,sessionTimeOut, TimeUnit.SECONDS);
}
public static Object get(String key) {
Jedis jedis = jedisPool.getResource();
Object getObj = jedis.get(key.getBytes());
if(getObj == null)
return null;
Object obj = SerializeUtil.unserialize((byte[]) getObj);
jedis.close();
return obj;
}
public static void main(String[] args) {
RedisLoginInfo info = new RedisLoginInfo();
info.setExpiredTime(1000);
info.setSysmod(null);
info.setToken("123");
info.setUserId("zz");
RedisUtil.set("ABC", info);
System.out.println(RedisUtil.get("ABC"));
return redisTemplate.opsForValue().get(key);
}
}
\ No newline at end of file
package org.sss.presentation.noui.util;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
/**
*
*以静态变量保存Spring ApplicationContext, 可在任何代码任何地方任何时候中取出ApplicaitonContext.
*
*/
@Service
@Lazy(false)
public class SpringContextHolder implements ApplicationContextAware{
private static ApplicationContext applicationContext;
//实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextHolder.applicationContext = applicationContext;
}
//取得存储在静态变量中的ApplicationContext.
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
//从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
//从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
//如果有多个Bean符合Class, 取出第一个.
@SuppressWarnings("unchecked")
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
@SuppressWarnings("rawtypes")
Map beanMaps = applicationContext.getBeansOfType(clazz);
if (beanMaps!=null && !beanMaps.isEmpty()) {
return (T) beanMaps.values().iterator().next();
} else{
return null;
}
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
}
package org.sss.presentation.noui.util;
import org.sss.presentation.noui.api.request.NoUiRequest;
import org.sss.presentation.noui.common.Constants;
public class StringUtil {
......@@ -11,7 +12,7 @@ public class StringUtil {
}
public static String userUniqueId(NoUiRequest request) {
return request.getUserId() + "." + request.getTerminalType();
return Constants.SESSION + "." + request.getUserId() + "." + request.getTerminalType();
}
}
<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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">
<bean id="annotationPropertyConfigurerRedis"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="order" value="1" />
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="locations">
<list>
<value>classpath:redis.properties</value>
</list>
</property>
</bean>
<!--redis连接密码-->
<bean id="redisPassword" class="org.springframework.data.redis.connection.RedisPassword">
<constructor-arg name="thePassword" value="${redis.passWord}"></constructor-arg>
</bean>
<!--spring-data-redis2.0以上的配置-->
<bean id="redisStandaloneConfiguration" class="org.springframework.data.redis.connection.RedisStandaloneConfiguration">
<property name="hostName" value="${redis.ip}"/>
<property name="port" value="${redis.port}"/>
<property name="password" ref="redisPassword" />
</bean>
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<constructor-arg name="standaloneConfig" ref="redisStandaloneConfiguration"></constructor-arg>
</bean>
<!--手动设置 key 与 value的序列化方式-->
<bean id="keySerializer" class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
<bean id="valueSerializer" class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
<!--配置jedis模板 -->
<bean id = "redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
<property name="connectionFactory" ref="connectionFactory" />
<property name="keySerializer" ref="keySerializer" />
<property name="valueSerializer" ref="valueSerializer" />
<property name="hashKeySerializer" ref="keySerializer" />
<property name="hashValueSerializer" ref="valueSerializer" />
</bean>
<bean id="springContextHolder" class="org.sss.presentation.noui.util.SpringContextHolder" />
<context:component-scan base-package="org.sss.presentation.noui.redis"></context:component-scan>
</beans>
\ No newline at end of file
......@@ -30,8 +30,17 @@
</context-param>
<context-param>
<param-name>nouiTimeout</param-name>
<param-value>10</param-value>
<param-value>120</param-value>
</context-param>
<!-- 配置监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment