springBoot 使用自定义配置文件集成 redis
程序员文章站
2022-05-01 23:26:08
...
springBoot用官方的那种方法集成redis比较简单,今天大佬非要让用自定义配置文件去集成redis,这样子反而变的麻烦了点,甚至有点违背springboot的原则了;
依赖jar:
只贴了redis的;
<!-- redis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
</dependency>
这里我采用的不是写对应配置config用注解的那种方式去获取配置文件的值,还是采用的需要时去读取配置文件:
import com.sess.june17th.common.util.PropertiesHelper;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
/**
* @Description: 读取redis配置文件
* @param ${tags}
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/31 0031 下午 5:03
*/
public class RedisProperties {
static final String PROPERTIES_FILE_NAME = "redis.properties";
static PropertiesHelper props;
public static String applicationPath;
@SuppressWarnings("rawtypes")
private static void loadProperties() {
try {
if (props == null) {
System.out.println("Load [redis.properties] from classpath");
Properties properties = new Properties();
Enumeration urls = RedisProperties.class.getClassLoader().getResources(PROPERTIES_FILE_NAME);
while (urls.hasMoreElements()) {
URL url = (URL) urls.nextElement();
InputStream input = null;
try {
URLConnection con = url.openConnection();
con.setUseCaches(false);
input = con.getInputStream();
properties.load(input);
} finally {
if (input != null) {
input.close();
}
}
}
props = new PropertiesHelper(properties);
for (Iterator it = props.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
System.out.println("[Property] " + entry.getKey() + "=" + entry.getValue());
}
System.out.println();
}
} catch (IOException e) {
throw new RuntimeException("在classpath中未找到redis.properties配置文件!", e);
}
}
public static Properties getProperties() {
return getHelper().getProperties();
}
private static PropertiesHelper getHelper() {
if (props == null)
loadProperties();
return props;
}
public static String getProperty(String key, String defaultValue) {
return getHelper().getProperty(key, defaultValue);
}
public static String getProperty(String key) {
return getHelper().getProperty(key);
}
public static String getRequiredProperty(String key) {
return getHelper().getRequiredProperty(key);
}
public static int getRequiredInt(String key) {
return getHelper().getRequiredInt(key);
}
public static int getInt(String key, int defaultValue) {
return getHelper().getInt(key, defaultValue);
}
public static boolean getRequiredBoolean(String key) {
return getHelper().getRequiredBoolean(key);
}
public static String getNullIfBlank(String key) {
return getHelper().getNullIfBlank(key);
}
public static void setProperty(String key, String value) {
getHelper().setProperty(key, value);
}
public static void setProperties(Properties v) {
props = new PropertiesHelper(v);
}
public static String getRealPath(String reportTemplateDir, String string) {
String path = getProperty(reportTemplateDir, string);
if (!StringUtils.isEmpty(applicationPath)) {
path = applicationPath + path;
}
return path;
}
}
配置文件处理工具类:
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import com.sess.june17th.common.base.SystemProperties;
/**
* 配置文件支持类
* @author liux
* @Date 2017年8月12日 下午5:51:29
*/
public class PropertiesHelper {
Properties p;
public PropertiesHelper(Properties p) {
this.p = p;
}
public Properties getProperties() {
return this.p;
}
public String getProperty(String key, String defaultValue) {
return getProperties().getProperty(key, defaultValue);
}
public String getProperty(String key) {
return getProperties().getProperty(key);
}
public String getRequiredProperty(String key) {
String value = getProperty(key);
if ((value == null) || ("".equals(value.trim()))) {
throw new IllegalStateException("required property is blank by key=" + key);
}
return value;
}
public Integer getInt(String key) {
if (getProperty(key) == null) {
return null;
}
return Integer.valueOf(Integer.parseInt(getRequiredProperty(key)));
}
public int getInt(String key, int defaultValue) {
if (getProperty(key) == null) {
return defaultValue;
}
return Integer.parseInt(getRequiredProperty(key));
}
public int getRequiredInt(String key) {
return Integer.parseInt(getRequiredProperty(key));
}
public Boolean getBoolean(String key) {
if (getProperty(key) == null) {
return null;
}
return Boolean.valueOf(Boolean.parseBoolean(getRequiredProperty(key)));
}
public boolean getBoolean(String key, boolean defaultValue) {
if (getProperty(key) == null) {
return defaultValue;
}
return Boolean.parseBoolean(getRequiredProperty(key));
}
public boolean getRequiredBoolean(String key) {
return Boolean.parseBoolean(getRequiredProperty(key));
}
public String getNullIfBlank(String key) {
String value = getProperties().getProperty(key);
if ((value == null) || ("".equals(value.trim()))) {
return null;
}
return value;
}
public PropertiesHelper setProperty(String key, String value) {
this.p.setProperty(key, value);
return this;
}
public void clear() {
this.p.clear();
}
public Set<Map.Entry<Object, Object>> entrySet() {
return this.p.entrySet();
}
public Enumeration<?> propertyNames() {
return this.p.propertyNames();
}
@SuppressWarnings("rawtypes")
public static Properties loadAllPropertiesFromClassLoader(String resourceName) throws IOException {
Properties properties = new Properties();
Enumeration urls = SystemProperties.class.getClassLoader().getResources(resourceName);
while (urls.hasMoreElements()) {
URL url = (URL) urls.nextElement();
InputStream input = null;
try {
URLConnection con = url.openConnection();
con.setUseCaches(false);
input = con.getInputStream();
properties.load(input);
} finally {
if (input != null) {
input.close();
}
}
}
return properties;
}
}
redisutil工具类:
import com.sess.june17th.common.config.RedisProperties;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
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 redis.clients.jedis.Transaction;
import java.io.*;
import java.util.*;
import java.util.concurrent.locks.ReentrantLock;
/**
* Redis 工具类
*/
public class RedisUtil {
// protected static ReentrantLock lockPool = new ReentrantLock();
protected static final ReentrantLock lockJedis = new ReentrantLock();
private static Logger _log = LoggerFactory.getLogger(RedisUtil.class);
// Redis服务器IP
private static String IP = RedisProperties.getProperty("redis.ip","127.0.0.1");
// Redis的端口号
private static int PORT = Integer.valueOf(RedisProperties.getProperty("redis.port","3306"));
// 访问密码
private static String PASSWORD = AESUtil.AESDecode(RedisProperties.getProperty("redis.password",null));
// 可用连接实例的最大数目,默认值为8;
// 如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_ACTIVE = Integer.valueOf(RedisProperties.getProperty("redis.max_active","500"));
// 控制一个pool最多有多少个状态为idle(空闲的)的jedis实例,默认值也是8。
private static int MAX_IDLE = Integer.valueOf(RedisProperties.getProperty("redis.max_idle","5"));
// 等待可用连接的最大时间,单位毫秒,默认值为-1,表示永不超时。如果超过等待时间,则直接抛出JedisConnectionException;
private static int MAX_WAIT = Integer.valueOf(RedisProperties.getProperty("redis.max_wait","10000"));
// 超时时间
private static int TIMEOUT = Integer.valueOf(RedisProperties.getProperty("redis.timeout","10000"));
// redis数据库db选择(默认db0)
private static int JEDIS_DB_INDEX = Integer.valueOf(RedisProperties.getProperty("redis.db_index","0"));
// 在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
private static boolean TEST_ON_BORROW = false;
private static volatile 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; // 一个月
static {
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) {
_log.error("First create JedisPool error : " + e);
}
}
/**
* 初始化Redis连接池
*/
private static void initialPool() {
if (jedisPool != null) {
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) {
_log.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) {
_log.error("Get jedis error : " + e);
_log.error(" ip-> " + IP + " port-> " + PORT);
}
return jedis;
}
/**
* 设置 String
*
* @param key
* @param value
* @param dbSelect (设置DB库,传null默认为db0)
*/
public synchronized static void set(String key, String value,Integer dbSelect) {
Jedis jedis = null;
try {
value = StringUtils.isBlank(value) ? "" : value;
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.set(key, value);
jedis.expire(key, EXRP_MONTH);
} catch (Exception e) {
_log.error("Set key error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 设置 byte[]
*
* @param key
* @param value
* @param dbSelect (设置DB库,传null默认为db0)
*/
public synchronized static void set(byte[] key, byte[] value,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.set(key, value);
jedis.expire(key, EXRP_MONTH);
} catch (Exception e) {
_log.error("Set key error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 设置 String 过期时间
*
* @param key
* @param value
* @param seconds
* @param dbSelect (设置DB库,传null默认为db0)
* 以秒为单位
*/
public synchronized static void set(String key, String value, int seconds,Integer dbSelect) {
Jedis jedis = null;
try {
value = StringUtils.isBlank(value) ? "" : value;
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.setex(key, seconds, value);
} catch (Exception e) {
_log.error("Set keyex error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 设置 byte[] 过期时间
*
* @param key
* @param value
* @param seconds
* @param dbSelect (设置DB库,传null默认为db0)
* 以秒为单位
*/
public synchronized static void set(byte[] key, byte[] value, int seconds,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.set(key, value);
jedis.expire(key, seconds);
} catch (Exception e) {
_log.error("Set key error : " + e);
} finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 获取String值
*
* @param key
* @param dbSelect (设置DB库,传null默认为db0)
* @return value
*/
public synchronized static String get(String key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
if (null == jedis) {
return null;
}
String value = jedis.get(key);
return value;
}catch(Exception e){
}finally{
if(null != jedis){
jedis.close();
}
}
return null;
}
/**
* 获取byte[]值
*
* @param key
* @param dbSelect (设置DB库,传null默认为db0)
* @return value
*/
public synchronized static byte[] get(byte[] key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
if (null == jedis) {
return null;
}
byte[] value = jedis.get(key);
return value;
}catch(Exception e){
}finally{
if(null != jedis){
jedis.close();
}
}
return null;
}
/**
* 删除值
* @param dbSelect (设置DB库,传null默认为db0)
* @param key
*/
public synchronized static void remove(String key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.del(key);
} catch (Exception e) {
_log.error("Remove keyex error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 删除值
* @param dbSelect (设置DB库,传null默认为db0)
* @param key
*/
public synchronized static void remove(byte[] key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.del(key);
} catch (Exception e) {
_log.error("Remove keyex error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* lpush 将数据放入队列中
*
* @param key
* 队列名称
* @param dbSelect (设置DB库,传null默认为db0)
* @param values
* 数据
*/
public synchronized static void lpush(String key,Integer dbSelect, String... values) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.lpush(key, values);
} catch (Exception e) {
_log.error("lpush error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* lrem
*
* @param key
* @param count
* @param value
* @param dbSelect (设置DB库,传null默认为db0)
*/
public synchronized static void lrem(String key, long count, String value,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.lrem(key, count, value);
} catch (Exception e) {
_log.error("lpush error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* sadd
*
* @param key
* @param value
* @param seconds
* @param dbSelect (设置DB库,传null默认为db0)
*/
public synchronized static void sadd(String key, String value, int seconds,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.sadd(key, value);
jedis.expire(key, seconds);
} catch (Exception e) {
_log.error("sadd error : " + e);
} finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 将本次处理的任务从srckey队列缓存到dstkey队列中
*
* @param srckey
* 缓存队列
* @param dstkey
* 目标队列
* @param dbSelect (设置DB库,传null默认为db0)
*/
public synchronized static String rpoplpush(String srckey, String dstkey,Integer dbSelect) {
String result = null;
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
// 将本次处理失败的任务从暂存队列"tmp-queue"中,弹回任务队列"task-queue"
result = jedis.rpoplpush(srckey, dstkey);
} catch (Exception e) {
_log.error("sadd error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
return result;
}
/**
* 将本次任务从暂存队列中清除
*
* @param key
* @param dbSelect (设置DB库,传null默认为db0)
*/
public synchronized static void rpop(String key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
// 将本次处理失败的任务从暂存队列"tmp-queue"中,弹回任务队列"task-queue"
jedis.rpop(key);
} catch (Exception e) {
_log.error("sadd error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 功能简述: 对实体Bean进行序列化操作.
*
* @param source
* 待转换的实体
* @return 转换之后的字节数组
* @throws Exception
*/
private static byte[] serialize(final Object source) {
ByteArrayOutputStream byteOut = null;
ObjectOutputStream ObjOut = null;
try {
byteOut = new ByteArrayOutputStream();
ObjOut = new ObjectOutputStream(byteOut);
ObjOut.writeObject(source);
ObjOut.flush();
} catch (IOException e) {
e.printStackTrace();
_log.error(source.getClass().getName() + " serialized error !", e);
} finally {
try {
if (null != ObjOut) {
ObjOut.close();
}
} catch (IOException e) {
ObjOut = null;
}
}
return byteOut.toByteArray();
}
/**
* 功能简述: 将字节数组反序列化为实体Bean.
*
* @param source
* 需要进行反序列化的字节数组
* @return 反序列化后的实体Bean
* @throws Exception
*/
private static Object deserialize(final byte[] source) {
ObjectInputStream ObjIn = null;
Object retVal = null;
try {
ByteArrayInputStream byteIn = new ByteArrayInputStream(source);
ObjIn = new ObjectInputStream(byteIn);
retVal = ObjIn.readObject();
} catch (Exception e) {
e.printStackTrace();
_log.error("deserialized error !", e);
} finally {
try {
if (null != ObjIn) {
ObjIn.close();
}
} catch (IOException e) {
ObjIn = null;
}
}
return retVal;
}
/**
* 从缓存中获取对象,如果类实现了序列化接口则使用Java反序列化解码,否则用JSON反解码
*
* @param key
* @param clazz
* @param dbSelect (设置DB库,传null默认为db0)
* @return
*/
@SuppressWarnings("unchecked")
public static <T> T getFromCache(final String key, final Class<T> clazz,Integer dbSelect) {
if (Serializable.class.isAssignableFrom(clazz)) {
return (T) getFromCacheWithDeserialize(key,dbSelect);
} else {
String json = getFromRedis(key,dbSelect);
if (json != null) {
return JSONUtil.fromJson(json, clazz);
}
}
return null;
}
/**
* 获取缓存并反序列化成对象
*
* @param key
* @param dbSelect (设置DB库,传null默认为db0)
* @return
*/
public static Object getFromCacheWithDeserialize(String key,Integer dbSelect) {
try {
byte[] data = getBytesFromRedis(key,dbSelect);
if (data != null)
return deserialize(data);
} catch (Exception e) {
e.printStackTrace();
_log.error("获取缓存并反序列化异常", e);
}
return null;
}
/**
* @Description: TODO
* @param ${tags}
@param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:53
*/
private static byte[] getBytesFromRedis(final String key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
byte[] bytes = jedis.get(key.getBytes());
return bytes;
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* 序列化对象并存入缓存
*
* @param key
* @param obj
* @param expireSeconds
* @param dbSelect (设置DB库,传null默认为db0)
* 过期时间,秒
*/
public static void putIntoCacheWithSerialize(final String key, final Object obj, final int expireSeconds,Integer dbSelect) {
try {
/*
* if(obj instanceof Serializable){ byte[] data = serialize(obj);
* if(data!=null){ putIntoRedis(key, data, expireSeconds); } }else{
*/
putIntoCacheWithJson(key, obj, expireSeconds, dbSelect);
// }
} catch (Exception e) {
e.printStackTrace();
_log.error("序列化对象并存缓存异常", e);
}
}
/**
* @Description: TODO
* @@param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:54
*/
// 序列化方式存 针对微信unitid添加的方法,旧工程用的序列化方式存储
public static void putIntoCacheToSerialize(final String key, final Object obj,Integer dbSelect) {
int time = 5 * 365 * 24 * 60 * 60;
if (obj instanceof Serializable) {
byte[] data = serialize(obj);
if (data != null) {
putIntoRedis(key, data, time);
}
} else {
putIntoCacheWithJson(key, obj, time, dbSelect);
}
}
/**
* @Description: TODO
* @param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:54
*/
public static void putIntoCacheToSerialize(final String key, final Object obj, final int expireSeconds,Integer dbSelect) {
if (obj instanceof Serializable) {
byte[] data = serialize(obj);
if (data != null) {
putIntoRedis(key, data, expireSeconds);
}
} else {
putIntoCacheWithJson(key, obj, expireSeconds, dbSelect);
}
}
/**
* 序列化对象并存入缓存,永久存储(将造成缓存脏数据,不建议使用)
*
* @param key
* @param obj
* @param dbSelect (设置DB库,传null默认为db0)
*/
public static void putIntoCacheWithSerialize(final String key, final Object obj,Integer dbSelect) {
putIntoCacheWithSerialize(key, obj, 24 * 60 * 60, dbSelect);
}
private static void putIntoRedis(final String key, final byte[] data, final int expireSeconds) {
Jedis jedis = RedisUtil.getJedis();
try {
if (expireSeconds < 1)
jedis.set(key.getBytes(), data);
else
jedis.setex(key.getBytes(), expireSeconds, data);
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* 将对象转成JSON并存入缓存
*
* @param key
* @param obj
* @param expireSeconds
* @param dbSelect (设置DB库,传null默认为db0)
* 过期时间,秒
*/
public static void putIntoCacheWithJson(final String key, final Object obj, final int expireSeconds,Integer dbSelect) {
try {
String json = JSONUtil.toJson(obj);
if (json != null) {
putStringIntoCache(key, json, expireSeconds, dbSelect);
}
} catch (Exception e) {
e.printStackTrace();
_log.error("将对象转成JSON并存入缓存异常", e);
}
}
/**
* 将字符串存入缓存
*
* @param key
* @param value
* @param expireSeconds
* @param dbSelect (设置DB库,传null默认为db0)
* 过期时间,秒
*/
public static void putStringIntoCache(final String key, final String value, final int expireSeconds,Integer dbSelect) {
try {
putIntoRedis(key, value, expireSeconds, dbSelect);
} catch (Exception e) {
e.printStackTrace();
_log.error("缓存字符串异常", e);
}
}
/**
* @Description: TODO
* @param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:54
*/
private static void putIntoRedis(final String key, final String data, final int expireSeconds,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
if (expireSeconds < 1)
jedis.set(key, data);
else
jedis.setex(key, expireSeconds, data);
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* @Description: TODO
*@param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:54
*/
public static <T> T getFromCacheWithJson(String key, String field, Class<T> clazz,Integer dbSelect) {
try {
String json = getFromRedis(key, field,dbSelect);
if (json != null) {
return JSONUtil.fromJson(json, clazz);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @Description: TODO
* @param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:55
*/
private static String getFromRedis(String key, String field,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
return jedis.hget(key, field);
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* @Description: TODO
*@param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:55
*/
public static void hsetWithJson(final String key, final String field, final Object obj, final int expireSeconds,Integer dbSelect) {
try {
String json = JSONUtil.toJson(obj);
if (json != null) {
putIntoRedis(key, field, json, expireSeconds,dbSelect);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* @Description: TODO
* @param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:55
*/
private static void putIntoRedis(final String key, final String field, final String data, final int expireSeconds,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.hset(key, field, data);
if (expireSeconds > 0) {
jedis.expire(key, expireSeconds);
}
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* 获取缓存并反JSON成对象
*
* @param key
* @param clazz
* @param dbSelect (设置DB库,传null默认为db0)
* @return
*/
public static <T> T getFromCacheWithJson(final String key, final Class<T> clazz,Integer dbSelect) {
try {
String json = getFromRedis(key, dbSelect);
if (json != null) {
return JSONUtil.fromJson(json, clazz);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* @Description: TODO
* @param ${tags}
@param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:55
*/
public static String getFromRedis(final String key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
return jedis.get(key);
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* @Description: TODO
*@param dbSelect (设置DB库,传null默认为db0)
* @return ${return_type}
* @throws
* @author liuxue
* @date 2019/7/29 0029 下午 3:55
*/
public static void setIncr(final String key, final int expireSeconds,Integer dbSelect) {
Jedis jedis = null;
try {
RedisUtil.lockJedis.lock();
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
String str = jedis.get(key); // 取一下
long count = jedis.incr(key);
if (count == 1 && (null == str || "".equals(str))) { // 取不到并且插入成功了 也就是第一次的情况持久化
jedis.expire(key, expireSeconds);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisUtil.lockJedis.unlock();
if (jedis != null)
jedis.close();
}
}
/**
* 通过redis的incr特性保证key值的唯一
*
* @param key
* @param expireSeconds
* @param dbSelect (设置DB库,传null默认为db0)
* @return
*/
public static boolean setIncrKey(final String key, final int expireSeconds,Integer dbSelect) {
// Jedis jedis = new Jedis("192.168.18.188", 6380); //redis服务器的ip和端口
Jedis jedis = null;
try {
RedisUtil.lockJedis.lock();
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
long count = jedis.incrBy(key, 1);
if (count == 1) {
jedis.expire(key, expireSeconds);
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisUtil.lockJedis.unlock();
if (jedis != null)
jedis.close();
}
return false;
}
/**
* 根据key删除redis缓存
*
* @param key
* @param dbSelect (设置DB库,传null默认为db0)
*/
public static void deleteFromRedis(String key,Integer dbSelect) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
jedis.del(key);
} catch (Exception e) {
_log.error("删除缓存异常|" + key + "|" + e);
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* 批量删除以 preStr 字符开头的缓存数据
*
* @param preStr
* @param dbSelect (设置DB库,传null默认为db0)
*/
public static void batchDel(String preStr,Integer dbSelect) {
Jedis jedis = null;
// Jedis jedis = new Jedis("192.168.18.188", 6380); //redis服务器的ip和端口
try {
jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
Set<String> set = jedis.keys(preStr + "*");
Iterator<String> it = set.iterator();
while (it.hasNext()) {
String keyStr = it.next();
jedis.del(keyStr);
}
} catch (Exception e) {
_log.error("删除缓存异常|" + preStr + "|" + e);
e.printStackTrace();
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* 批量获取缓存中的数据
*
* @param preStr
* @param dbSelect (设置DB库,传null默认为db0)
* @return
*/
public Set<String> getBatchRedis(String preStr,Integer dbSelect) {
Jedis jedis = RedisUtil.getJedis();
jedis.select(dbSelect == null?JEDIS_DB_INDEX:dbSelect);
return jedis.keys(preStr + "*");
}
/**
* 获取锁
*
* @param lockName
* 锁名称 ,默认传redis缓存的key
* @param waitTimeOut
* 等待获取锁的超时时间(秒)
* @param lockTimeOut
* 锁的生存时间(秒)
* @return 如果获取锁成功则返回锁键对应值,否则返回null
*/
public static String addLockWithTimeOut(String lockName, int waitTimeOut, int lockTimeOut) {
Jedis conn = RedisUtil.getJedis();
try {
String lockKey = "lock:" + lockName;
String lockId = UUID.randomUUID().toString();
int now = 0;
int end = now + waitTimeOut;
while (now < end) {
if (conn.setnx(lockKey, lockId).intValue() == 1) {
conn.expire(lockKey, lockTimeOut);
_log.info("获取锁成功|acquirelock|'" + lockName + "'|锁标识|" + lockId + "|获取锁次数| " + (now + 1));
return lockId;
}
if (conn.ttl(lockKey) < 0) {
conn.expire(lockKey, lockTimeOut);
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
_log.info("获取锁等待|acquirelock|'" + lockName + "'|锁标识|" + lockId + "|获取锁重试次数| " + (now + 1));
now++;
}
} catch (Exception e) {
_log.error("获取锁|redis加锁异常|" + lockName + "|" + e);
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return null;
}
/**
* 释放锁 解锁时将判断锁键对应值是否是给定的值,防止误解锁。
*
* @param lockName
* 锁名称
* @param lockId
* 锁键对应值
* @param waiteTimeOut
* 解锁动作的超时时间(秒)
* @return true如果解锁成功,否则返回false
*/
public static boolean releaseLock(String lockName, String lockId, int waiteTimeOut) {
Jedis conn = RedisUtil.getJedis();
try {
String lockKey = "lock:" + lockName;
long now = 0;
long end = now + waiteTimeOut;
while (now < end) {
conn.watch(lockKey); // 监视锁的键
if (null != conn.get(lockKey) && lockId.equals(conn.get(lockKey))) { // 判断锁的值是否和加锁时设置的一致,即检查进程是否仍然持有锁
Transaction trans = conn.multi();
trans.del(lockKey); // 在Redis事务中释放锁
List<Object> exec = trans.exec();
if (exec != null) { // 事务执行失败后重试(监视的键被修改导致事务失败,重新监视并释放锁)
_log.info("释放锁成功|releaseLock|'" + lockName + "'|锁标识|" + lockId + "|释放锁次数| " + (now + 1));
return true;
}
now++;
continue;
} else {
_log.info("锁已释放|releaseLock|'" + lockName + "'|锁标识|" + lockId + "|过期自动释放");
}
conn.unwatch(); // 解除监视
break;
}
} catch (Exception e) {
e.printStackTrace();
_log.error("释放锁|redis解锁异常|" + lockName + "|" + e);
e.printStackTrace();
} finally {
if (conn != null)
conn.close();
}
return false;
}
/**
* @Title: hgetWithJson
* @Description: TODO
* @return: T
*/
public static <T> T hgetWithJson(final String key, String field, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = getJedis();
String ret = jedis.hget(key, field);
if (StringUtils.isNotBlank(ret)) {
return JSONUtil.fromJson(ret, clazz);
}
return null;
} finally {
if (jedis != null)
jedis.close();
}
}
/**
* @Description: 删除缓存哈希结构中的一条
* @Param: [key, field]
* @return: void
*/
public synchronized static void hdel(final String key, String field) {
Jedis jedis = null;
try {
jedis = getJedis();
jedis.hdel(key, field);
} catch (Exception e) {
_log.error("Remove keyex error : " + e);
}finally{
if(null != jedis){
jedis.close();
}
}
}
/**
* 获取redis set list
*
* @function:
* @since 1.0
* @param key
* @param clazz
* @return
*/
public static <T> Map<String, T> hgetAllWithJson(final String key, Class<T> clazz) {
Jedis jedis = null;
try {
jedis = getJedis();
Map<String, String> retmap = jedis.hgetAll(key);
if (retmap != null) {
Map<String, T> map = new HashMap<>();
for (Map.Entry<String, String> entry : retmap.entrySet()) {
if (StringUtils.isNotBlank(entry.getValue())) {
T t = JSONUtil.fromJson(entry.getValue(), clazz);
map.put(entry.getKey(), t);
}
}
return map;
}
return null;
} finally {
if (jedis != null)
jedis.close();
}
}
/**
*
* @Description: 返回List
* @param key
* @param clazz
* @return List<T>
*/
public static <T> List<T> getListFromCacheWithJson(String key, Class<T> clazz, JsonConfig jsonConfig,Integer dbSelect) {
try {
String json = getFromRedis(key,dbSelect);
if (json != null) {
return JSONUtil.fromListJson(json, clazz, jsonConfig);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("rawtypes")
public static void putListIntoCacheWithSerialize(String key, List list, int expire, JsonConfig jsonConfig,Integer dbSelect) {
JSONArray jsonArray = null;
if (null != jsonConfig) {
jsonArray = JSONArray.fromObject(list, jsonConfig);
} else {
jsonArray = JSONArray.fromObject(list);
}
if (null == jsonArray) {
_log.info("存入缓存异常");
return;
}
String json = jsonArray.toString();
if (json != null) {
try {
putStringIntoCache(key, json, expire, dbSelect);
} catch (Exception e) {
_log.info("存入缓存异常");
e.printStackTrace();
return;
}
}
}
public static void updateSigninVerifyIssueTime(String key, String value, int timeOut) {
Jedis jedis = null;
try {
value = StringUtils.isBlank(value) ? "" : value;
jedis = getJedis();
jedis.set(key, value);
jedis.expire(key, timeOut);
} catch (Exception e) {
_log.error("Set key error : " + e);
}finally {
if(null != jedis){
jedis.close();
}
}
}
/**
* 返回集合中的所有成员
*
* @param key
* @return Set<String>
*/
public static Set<String> smembers(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.smembers(key);
} catch (Exception e) {
e.printStackTrace();
_log.error("返回集合中的所有成员出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 向集合添加一个成员,返回添加成功的数量
*
* @param key
* @param members
* @return Long
*/
public static Long sadd(String key, String members) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.sadd(key, members);
} catch (Exception e) {
e.printStackTrace();
_log.error("向集合添加一个成员出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 获取集合的成员数量
*
* @param key
* @return
*/
public static Long scard(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.scard(key);
} catch (Exception e) {
e.printStackTrace();
_log.error("获取集合的成员数出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 获取集合中指定数量的元素
*
* @param key
* @return
*/
public static List<String> srandmember(String key, int count) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.srandmember(key, count);
} catch (Exception e) {
e.printStackTrace();
_log.error("获取集合中指定数量的元素出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 移除集合中的一个成员元素
*
* @param key
* @return 1表示成功,0表示移除元素不是集合中的元素,-1表示出错
*/
public static Long srem(String key, String members) {
Jedis jedis = null;
try {
jedis = getJedis();
return jedis.srem(key, members);
} catch (Exception e) {
e.printStackTrace();
_log.error("移除集合中的一个成员元素出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return -1L;
}
/**
* 将一个值插入到列表头部,value可以重复,返回列表的长度
*
* @param key
* @param value
* String
* @return 返回List的长度 null表示出错
*/
public static Long lpush(String key, String value) {
Jedis jedis = null;
try {
jedis = getJedis();
Long length = jedis.lpush(key, value);
return length;
} catch (Exception e) {
e.printStackTrace();
_log.error("将一个值插入到列表头部出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 获取列表长度,key为空时返回0
*
* @param key
* @return Long null表示出错
*/
public static Long llen(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
Long length = jedis.llen(key);
return length;
} catch (Exception e) {
e.printStackTrace();
_log.error("获取列表长度出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 在列表中的尾部添加一个值,返回列表的长度
*
* @param key
* @param values
* @return Long null表示出错
*/
public static Long rpush(String key, String values) {
Jedis jedis = null;
try {
jedis = getJedis();
Long length = jedis.rpush(key, values);
return length;
} catch (Exception e) {
e.printStackTrace();
_log.error("在列表中的尾部添加一个值出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 移出并获取列表的第一个元素,当列表不存在或者为空时,返回Null
*
* @param key
* @return String 当列表不存在或者为空时,返回Null
*/
public static String lpop(String key) {
Jedis jedis = null;
try {
jedis = getJedis();
String value = jedis.lpop(key);
return value;
} catch (Exception e) {
e.printStackTrace();
_log.error("移出并获取列表的第一个元素出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
*
* 设置 key的有效时间(按秒计算)
*
* @param key
* key
* @param expireSeconds
* 秒
* @return 1表示成功,0表示key不存在,null表示出错
*/
public static Long expire(final String key, final int expireSeconds) {
Jedis jedis = null;
try {
jedis = getJedis();
Long value = jedis.expire(key, expireSeconds);
return value;
} catch (Exception e) {
e.printStackTrace();
_log.error("设置 key的有效时间(按秒计算)出错:", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
*
* @Description:
* @return
* String
*/
public static synchronized long getCount() {
Jedis jedis = null;
try {
jedis = getJedis();
Long rs = jedis.incr("transfer_file_count");
return rs;
} catch (Exception e) {
}finally {
if( null != jedis) {
jedis.close();
}
}
return 0;
}
/**
* 通过redis的incr特性保证key值的唯一
* @param key
* @param expireSeconds 过期时间,秒;仅第一次设置key时设置
* @return 返回增长次数,第一次是1,此后key未过期则会累计,出错返回0
*/
public static Long setIncrReturn(final String key, final int expireSeconds) {
Jedis jedis = null;
try {
RedisUtil.lockJedis.lock();
jedis = RedisUtil.getJedis();
String str = jedis.get(key); // 取一下
long count = jedis.incr(key);
if (count == 1 && (null == str || "".equals(str))) { // 取不到并且插入成功了 也就是第一次的情况持久化
jedis.expire(key, expireSeconds);
}
return count;
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisUtil.lockJedis.unlock();
if (jedis != null)
jedis.close();
}
return 0L;
}
/**
*
* @param key 关键字
* @param expireSeconds 第一次设置时key的过期时间,秒
* @return 返回原来value加1后的值,若原来key不存在,则value初始化为0然后加1返回1
*/
public static long setAndgetIncr(final String key, final int expireSeconds) {
Jedis jedis = null;
try {
RedisUtil.lockJedis.lock();
jedis = RedisUtil.getJedis();
String str = jedis.get(key); // 取一下
long count = jedis.incr(key);
if (count == 1 && (null == str || "".equals(str))) { // 取不到并且插入成功了 也就是第一次的情况持久化
jedis.expire(key, expireSeconds);
}
return count;
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisUtil.lockJedis.unlock();
if (jedis != null)
jedis.close();
}
return 0L;
}
}
以上就集成完了 可以正常使用了,工具类的方法非常全面,支持设置db;
上一篇: javascript - 求,大神们,推荐几本书,学习学习
下一篇: 二维数组中如何除去重复项呢