首先,配置一个RedisUtil类用于处理redis交互
package com.tky.subway.common.util;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import java.io.*;
import java.util.concurrent.locks.ReentrantLock;
/**
* Redis 工具类
* Created by shuzheng on 2016/11/26.
*/
public class RedisUtil {
protected static ReentrantLock lockPool = new ReentrantLock();
protected static ReentrantLock lockJedis = new ReentrantLock();
private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtil.class);
// Redis服务器IP
private static String IP = PropertiesFileUtil.getInstance("redis").get("master.redis.ip");
// Redis的端口号
private static int PORT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.port");
// 访问密码
private static String PASSWORD = PropertiesFileUtil.getInstance("redis").get("master.redis.password");
// 可用连接实例的最大数目,默认值为8;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_active");
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_idle");
// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.max_wait");
// 超时时间
private static int TIMEOUT = PropertiesFileUtil.getInstance("redis").getInt("master.redis.timeout");
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = false;
private static JedisPool jedisPool = null;
/**
* redis过期时间,以秒为单位
*/
// 一小时
public final static int EXRP_HOUR = 60 * 60;
// 一天
public final static int EXRP_DAY = 60 * 60 * 24;
// 一个月
public final static int EXRP_MONTH = 60 * 60 * 24 * 30;
/**
* 初始化Redis连接池
*/
private static void initialPool() {
try {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(MAX_ACTIVE);
config.setMaxIdle(MAX_IDLE);
config.setMaxWaitMillis(MAX_WAIT);
config.setTestOnBorrow(TEST_ON_BORROW);
jedisPool = new JedisPool(config, IP, PORT, TIMEOUT);
} catch (Exception e) {
LOGGER.error("First create JedisPool error : " + e);
}
}
/**
* 在多线程环境同步初始化
*/
private static synchronized void poolInit() {
if (null == jedisPool) {
initialPool();
}
}
/**
* 同步获取Jedis实例
* @return Jedis
*/
public synchronized static Jedis getJedis() {
poolInit();
Jedis jedis = null;
try {
if (null != jedisPool) {
jedis = jedisPool.getResource();
try {
jedis.auth(PASSWORD);
} catch (Exception e) {
}
}
} catch (Exception e) {
LOGGER.error("Get jedis error : " + e);
}
return jedis;
}
/**
* 设置 String
* @param key
* @param value
*/
public synchronized static void set(String key, String value) {
try {
value = StringUtils.isBlank(value) ? "" : value;
Jedis jedis = getJedis();
jedis.set(key, value);
jedis.close();
} catch (Exception e) {
LOGGER.error("Set key error : " + e);
}
}
/**
* 设置 byte[]
* @param key
* @param value
*/
public synchronized static void set(byte[] key, byte[] value) {
try {
Jedis jedis = getJedis();
jedis.set(key, value);
jedis.close();
} catch (Exception e) {
LOGGER.error("Set key error : " + e);
}
}
/**
* 设置 String 过期时间
* @param key
* @param value
* @param seconds 以秒为单位
*/
public synchronized static void set(String key, String value, int seconds) {
try {
value = StringUtils.isBlank(value) ? "" : value;
Jedis jedis = getJedis();
jedis.setex(key, seconds, value);
jedis.close();
} catch (Exception e) {
LOGGER.error("Set keyex error : " + e);
}
}
/**
* 设置 byte[] 过期时间
* @param key
* @param value
* @param seconds 以秒为单位
*/
public synchronized static void set(byte[] key, byte[] value, int seconds) {
try {
Jedis jedis = getJedis();
jedis.set(key, value);
jedis.expire(key, seconds);
jedis.close();
} catch (Exception e) {
LOGGER.error("Set key error : " + e);
}
}
/**
* 获取String值
* @param key
* @return value
*/
public synchronized static String get(String key) {
Jedis jedis = getJedis();
if (null == jedis) {
return null;
}
String value = jedis.get(key);
jedis.close();
return value;
}
/**
* 获取byte[]值
* @param key
* @return value
*/
public synchronized static byte[] get(byte[] key) {
Jedis jedis = getJedis();
if (null == jedis) {
return null;
}
byte[] value = jedis.get(key);
jedis.close();
return value;
}
/**
* 删除值
* @param key
*/
public synchronized static void remove(String key) {
try {
Jedis jedis = getJedis();
jedis.del(key);
jedis.close();
} catch (Exception e) {
LOGGER.error("Remove keyex error : " + e);
}
}
/**
* 删除值
* @param key
*/
public synchronized static void remove(byte[] key) {
try {
Jedis jedis = getJedis();
jedis.del(key);
jedis.close();
} catch (Exception e) {
LOGGER.error("Remove keyex error : " + e);
}
}
/**
* lpush
* @param key
* @param key
*/
public synchronized static void lpush(String key, String... strings) {
try {
Jedis jedis = RedisUtil.getJedis();
jedis.lpush(key, strings);
jedis.close();
} catch (Exception e) {
LOGGER.error("lpush error : " + e);
}
}
/**
* lrem
* @param key
* @param count
* @param value
*/
public synchronized static void lrem(String key, long count, String value) {
try {
Jedis jedis = RedisUtil.getJedis();
jedis.lrem(key, count, value);
jedis.close();
} catch (Exception e) {
LOGGER.error("lpush error : " + e);
}
}
/**
* sadd
* @param key
* @param value
* @param seconds
*/
public synchronized static void sadd(String key, String value, int seconds) {
try {
Jedis jedis = RedisUtil.getJedis();
jedis.sadd(key, value);
jedis.expire(key, seconds);
jedis.close();
} catch (Exception e) {
LOGGER.error("sadd error : " + e);
}
}
/**
* incr
* @param key
* @return value
*/
public synchronized static Long incr(String key) {
Jedis jedis = getJedis();
if (null == jedis) {
return null;
}
long value = jedis.incr(key);
jedis.close();
return value;
}
/**
* decr
* @param key
* @return value
*/
public synchronized static Long decr(String key) {
Jedis jedis = getJedis();
if (null == jedis) {
return null;
}
long value = jedis.decr(key);
jedis.close();
return value;
}
//序列化
public static byte [] serialize(Object obj){
ObjectOutputStream obi=null;
ByteArrayOutputStream bai=null;
try {
bai=new ByteArrayOutputStream();
obi=new ObjectOutputStream(bai);
obi.writeObject(obj);
byte[] byt=bai.toByteArray();
return byt;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//反序列化
public static Object unserizlize(byte[] byt){
ObjectInputStream oii=null;
ByteArrayInputStream bis=null;
bis=new ByteArrayInputStream(byt);
try {
oii=new ObjectInputStream(bis);
Object obj=oii.readObject();
return obj;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
配置文件调用PropertiesFileUtil初始化redis的连接
package com.tky.subway.common.util;
import java.util.Date;
import java.util.HashMap;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
/**
* 资源文件读取工具
* @author shuzheng
* @date 2016年10月15日
*/
public class PropertiesFileUtil {
// 当打开多个资源文件时,缓存资源文件
private static HashMap configMap = new HashMap();
// 打开文件时间,判断超时使用
private Date loadTime = null;
// 资源文件
private ResourceBundle resourceBundle = null;
// 默认资源文件名称
private static final String NAME = "config";
// 缓存时间
private static final Integer TIME_OUT = 60 * 1000;
// 私有构造方法,创建单例
private PropertiesFileUtil(String name) {
this.loadTime = new Date();
this.resourceBundle = ResourceBundle.getBundle(name);
}
public static synchronized PropertiesFileUtil getInstance() {
return getInstance(NAME);
}
public static synchronized PropertiesFileUtil getInstance(String name) {
PropertiesFileUtil conf = configMap.get(name);
if (null == conf) {
conf = new PropertiesFileUtil(name);
configMap.put(name, conf);
}
// 判断是否打开的资源文件是否超时1分钟
if ((System.currentTimeMillis() - conf.getLoadTime().getTime()) > TIME_OUT) {
conf = new PropertiesFileUtil(name);
configMap.put(name, conf);
}
return conf;
}
// 根据key读取value
public String get(String key) {
try {
String value = resourceBundle.getString(key);
return value;
} catch (MissingResourceException e) {
return "";
}
}
// 根据key读取value(整形)
public Integer getInt(String key) {
try {
String value = resourceBundle.getString(key);
return Integer.parseInt(value);
} catch (MissingResourceException e) {
return null;
}
}
// 根据key读取value(布尔)
public boolean getBool(String key) {
try {
String value = resourceBundle.getString(key);
if ("true".equals(value)) {
return true;
}
return false;
} catch (MissingResourceException e) {
return false;
}
}
public Date getLoadTime() {
return loadTime;
}
}
配置web.xml中启动时监听器用于初始化字典项
<listener> <listener-class>org.springframework.web.util.Log4jConfigListenerlistener-class> listener>
监听器代码如下:
package com.tky.subway.data.dictionary.controller;
import com.tky.subway.common.util.RedisUtil;
import com.tky.subway.data.basic.Line;
import com.tky.subway.data.dictionary.entity.Dict;
import com.tky.subway.data.dictionary.service.ItemsService;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Chasel
* @Title: DataDictionaryListener
* @Package com.tky.subway.data.dictionary.controller
* @Description: ${todo}
* @date 2018/6/28 13:49
*/
public class DataDictionaryListener extends ContextLoader implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
//Spring上下文获取及Bean获取
ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContextEvent.getServletContext());
ItemsService itemsService = (ItemsService) applicationContext.getBean("ItemsService");
Map> dictMap = changeToMap(itemsService.findAllDict());
List lineList = itemsService.findAllLine();
dictMap.put("LINE_INFO",changeLineToMap(lineList));
//遍历字典项,将之存入缓存
for (Map.Entry> entry : dictMap.entrySet()) {
RedisUtil.set(entry.getKey().getBytes(), RedisUtil.serialize(entry.getValue()));
}
System.out.println((Map) RedisUtil.unserizlize(RedisUtil.get("tky_exception_gj".getBytes())));
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
closeWebApplicationContext(servletContextEvent.getServletContext());
}
/**
* 将字典list转换为Map
*
* @param dictList
* @return
*/
private Map> changeToMap(List dictList) {
Map> resultMap = new HashMap>();
for (Dict dict : dictList
) {
String groupId = dict.getGroupid();
Map dictMap = resultMap.get(groupId);
if (dictMap != null) {
dictMap.put(dict.getId(), dict.getText());
} else {
dictMap = new HashMap<>();
dictMap.put(dict.getId(), dict.getText());
resultMap.put(groupId, dictMap);
}
}
return resultMap;
}
private Map changeLineToMap(List lineList) {
Map map = new HashMap<>();
for (Line line : lineList
) {
map.put(line.getLinecode(), line.getLinename());
}
return map;
}
}