企业级-实现Redis封装层
作者:fyupeng
技术专栏:☞ https://github.com/fyupeng
项目地址:☞ https://github.com/fyupeng/distributed-blog-system-api
留给读者
封装 Redis
客户端Dao
层、分布式锁等。
一、介绍
二、代码
DataInitialLoadRunner.java
/**
* @ClassName: DataInitialLoadRunner
* @Description: 程序启动时初始化加载操作
*
*/
@Component
@Order(value = 1)
public class DataInitialLoadRunner implements CommandLineRunner {
protected final static Logger logger = LoggerFactory.getLogger(DataInitialLoadRunner.class);
@Autowired
private ApplicationContext context;
/**
* 执行程序启动时初始化加载操作
*
* @param args
* @throws Exception
* @see CommandLineRunner#run(String[])
*/
@Override
public void run(String... args) throws Exception {
logger.info(">>>>>>>>>common系统初始化数据操作开始<<<<<<<<<<");
// 开始时间
long begin = System.currentTimeMillis();
//获取当前启动参数
CoreConstants.PROFILE_NAME = context.getEnvironment().getActiveProfiles()[0];
logger.info(">>>>>>>>>当前启动参数:"+CoreConstants.PROFILE_NAME);
// 加载redis连接池
RedisManager.init();
// 加载获取gwssi-core.properties配置文件
ResourceBundle torchBundle = ResourceBundle.getBundle("gwssi-core");
//电子文书文件参数初始化设置
CoreConstants.DOC_APPLY_DATASOURCE_KEY=torchBundle.getString("doc.apply.datasource.key"); //申请端电子文书数据源key
CoreConstants.DOC_REDIS_DBINDEX = Integer.parseInt(torchBundle.getString("doc.redis.index")); // redis库ID
CoreConstants.DOC_CONFIG_PATH = torchBundle.getString("doc.config.path"); // 电子文书xml文件路径
CoreConstants.DOC_BASE_URL_PATH = torchBundle.getString("doc.base.url.path");
//CoreConstants.FILE_IDENTITY_PATH= torchBundle.getString("file.identity.path"); //身份认证文件上传路径
String initLoad = torchBundle.getString("init.load");
// 检查程序每次启动时是否都要再加载一遍XML文件放入缓存中
if (StringUtil.isNotBlank(initLoad.trim()) && "true".equals(initLoad.trim())) {
logger.info("文书配置加载完成");
}
long end = System.currentTimeMillis(); // 结束时间
logger.info(">>>>>>>>>系统初始化数据操作结束:" + (end - begin) + "ms<<<<<<<<<<");
}
}
RedisManager.java
/**
* redis连接池获取数据源连接
*
*/
public class RedisManager {
private static Pool<Jedis> pool;
protected final static Logger logger = LoggerFactory.getLogger(RedisManager.class);
/**
* 初始化redis连接池连接
*/
public static void init() throws Exception {
// 加载读取application.properties文件
String profile = CoreConstants.PROFILE_NAME;
String profilename = "application";
if (StringUtils.isNotBlank(profile)) {
profilename += ("-" + profile);
}
logger.info("profilename=" + profilename);
ResourceBundle torchBundle = ResourceBundle.getBundle(profilename);
//>>>>>>>>初始化Redis连接池<<<<<<<<
if (torchBundle == null) {
throw new RuntimeException("没有找到redis配置文件");
}
String host = torchBundle.getString("spring.redis.host"); // redis IP地址
int port = Integer.valueOf(torchBundle.getString("spring.redis.port")); // 端口号
String password = "";
if (torchBundle.containsKey("spring.redis.password")) {
password = torchBundle.getString("spring.redis.password"); // 密码
}
logger.info("redis.host=" + host + "----redis.port=" + port);
// 创建jedis池配置实例
JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
// 设置池配置项值
// 最大连接数
int poolMaxTotal = Integer.valueOf(torchBundle.getString("spring.redis.maxActive").trim());
jedisPoolConfig.setMaxTotal(poolMaxTotal);
// 最大空闲连接数
int poolMaxIdle = Integer.valueOf(torchBundle.getString("spring.redis.maxIdle").trim());
int poolMinIdle = Integer.valueOf(torchBundle.getString("spring.redis.MinIdle").trim());
jedisPoolConfig.setMaxIdle(poolMaxIdle);
jedisPoolConfig.setMinIdle(poolMinIdle);
jedisPoolConfig.setMaxTotal(200);
// 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1
long poolMaxWaitMillis = Long.valueOf(torchBundle.getString("spring.redis.maxWaitMillis").trim());
jedisPoolConfig.setMaxWaitMillis(poolMaxWaitMillis);
//拿到连接的时候是否进行校验操作
jedisPoolConfig.setTestOnBorrow(true);
//连接归还池进行校验
jedisPoolConfig.setTestOnReturn(true);
//表示idle object evitor两次扫描之间要sleep的毫秒数
jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
//表示idle object evitor每次扫描的最多的对象数
jedisPoolConfig.setNumTestsPerEvictionRun(10);
//表示一个对象至少停留在idle状态的最短时间,然后才能被idle object evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义
jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);
// 添加连接池
if (StringUtils.isNotBlank(password)) {
int timeOut = Integer.valueOf(torchBundle.getString("spring.redis.timeOut")); // 超时时间
pool = new JedisPool(jedisPoolConfig, host, port, timeOut, password);
} else {
pool = new JedisPool(jedisPoolConfig, host, port);
}
logger.info("redis 初始化完成");
}
/**
* 获取Jedis对象
*
* @return
*/
public static Jedis getResource() {
Jedis jedis = pool.getResource();
return jedis;
}
/**
* 获取Jedis对象
*
* @param db 数据库序号
* @return
*/
public static Jedis getResource(int db) {
//索引0 =线程
//索引1 =这个
//索引2 =直接呼叫者,可以是自己。
//索引3 ... n =相互调用以获得索引2及以下的类和方法。
/*StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
for (int i = 0; i < stackTrace.length; i++)
{
StackTraceElement s = stackTrace[i];
System.out.format(" ClassName:%d\t%s\n", i, s.getClassName());
System.out.format("MethodName:%d\t%s\n", i, s.getMethodName());
System.out.format(" FileName:%d\t%s\n", i, s.getFileName());
System.out.format("LineNumber:%d\t%s\n\n", i, s.getLineNumber());
}*/
Jedis jedis = pool.getResource();
jedis.select(db);
return jedis;
}
/**
* 销毁
*
* @throws Exception
*/
public static void destroy() throws Exception {
pool.destroy();
}
}
Redis
工具类
/**
* redis工具类
*
*/
public class RedisUtils {
protected final static Logger logger = LoggerFactory.getLogger(RedisUtils.class);
private static final long sleepTime = 100L;
/**
* 根据dbindex删除缓存
*
* @param dbIndex
*/
public static void flushDB(int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
jedis.flushDB();
} catch (Exception e) {
logger.error("redis-flushDB异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set集合
*
* @param key
* @param value
*/
public static void set(String key, Object value, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (value instanceof String) {
jedis.set(key, String.valueOf(value));
} else {
jedis.set(key.getBytes(), serialize(value));
}
} catch (Exception e) {
logger.error("redis-set异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* set集合, 有过期时间
*
* @param key
* @param value
* @param second
*/
public static void setex(String key, int second, Object value, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (value instanceof String) {
jedis.setex(key, second, String.valueOf(value));
} else {
jedis.setex(key.getBytes(), second, serialize(value));
}
} catch (Exception e) {
logger.error("redis-set异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* @param 参数
* @return void 返回类型
* @throws
* @Title: expire
* @Description: 设置时间
*/
public static void expire(String key, int secends, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
jedis.expire(key.getBytes(), secends);
} catch (Exception e) {
logger.error("redis-expire异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 从redis缓存中获取key的值
*/
public static String get(String key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
return jedis.get(key);
} catch (Exception e) {
logger.error("redis-get异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* @param 参数
* @return Object 返回类型
* @throws
* @Title: get
* @Description: key查询返回Object对象
*/
public static Object get(byte[] key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
logger.info("redis取值:" + key.toString());
return unserialize(jedis.get(key));
} catch (Exception e) {
logger.error("redis-get异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 根据key删除缓存
*
* @param key
*/
public static void delete(String[] key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
logger.info("redis删除:" + key);
jedis.del(key);
} catch (Exception e) {
logger.error("redis-delete异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 设置 map
*
* @param <T>
* @param key
* @param value
*/
public static <T> void setMap(String key, Map<String, T> map, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
jedis.set(key.getBytes(), serialize(map));
} catch (Exception e) {
logger.error("redis-setMap异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 获取list
*
* @param <T>
* @param key
* @return list
*/
public static <T> Map<String, T> getMap(String key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (jedis == null || !jedis.exists(key.getBytes())) {
return null;
}
byte[] in = jedis.get(key.getBytes());
@SuppressWarnings("unchecked")
Map<String, T> map = (Map<String, T>) unserialize(in);
return map;
} catch (Exception e) {
logger.error("redis-getMap异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 设置object
*
* @param <T>
* @param key
* @param object
*/
public static <T> void setObject(String key, Object object, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
jedis.set(key.getBytes(), serialize(object));
} catch (Exception e) {
logger.error("redis-setObject异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 获取object
*
* @param <T>
* @param key
* @return list
*/
public static <T> T getObject(String key, int dbIndex) {
Jedis jedis = null;
Object object = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (jedis == null || !jedis.exists(key.getBytes())) {
return null;
}
byte[] in = jedis.get(key.getBytes());
object = unserialize(in);
} catch (Exception e) {
logger.error("redis-getObject异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return object==null?null:(T)object;
}
/**
* 设置 String
*
* @param key
* @param value
*/
public static void setString(String key, String value, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
// value = StringUtil.isNullOrEmpty(value) ? "" : value;
jedis.set(key, value);
} catch (Exception e) {
logger.error("redis-setString异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 设置 过期时间
*
* @param key
* @param seconds 以秒为单位
* @param value
*/
public static void setString(String key, int seconds, String value, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
// value = StringUtil.isNullOrEmpty(value) ? "" : value;
jedis.setex(key, seconds, value);
} catch (Exception e) {
logger.error("redis-setString异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 获取String值
*
* @param key
* @return value
*/
public static String getString(String key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (jedis == null || !jedis.exists(key)) {
return null;
}
return jedis.get(key);
} catch (Exception e) {
logger.error("redis-getString异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 设置 list
*
* @param <T>
* @param key
* @param list
*/
public static <T> void setList(String key, List<T> list, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
jedis.set(key.getBytes(), serialize(list));
} catch (Exception e) {
logger.error("redis-setList异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
}
/**
* 获取list
*
* @param <T>
* @param key
* @return list
*/
@SuppressWarnings("unchecked")
public static <T> List<T> getList(String key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (jedis == null || !jedis.exists(key.getBytes())) {
return null;
}
byte[] in = jedis.get(key.getBytes());
List<T> list = (List<T>) unserialize(in);
return list;
} catch (Exception e) {
logger.error("redis-getList异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
public static byte[] getbyte(String key, int secends, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (null == jedis.get(key.getBytes())) {
return null;
} else {
// 更新过期时间
jedis.expire(key, secends);// 1小时
}
return jedis.get(key.getBytes());
} catch (Exception e) {
logger.error("session取Redis出现错误", e);
return null;
} finally {
jedis.close();
}
}
/*
* 序列化对象
*/
public static byte[] serialize(Object value) {
if (value == null) {
throw new NullPointerException("Can't serialize null");
}
byte[] rv = null;
ByteArrayOutputStream bos = null;
ObjectOutputStream os = null;
try {
bos = new ByteArrayOutputStream();
os = new ObjectOutputStream(bos);
os.writeObject(value);
rv = bos.toByteArray();
} catch (IOException e) {
logger.error("redis-serialize异常", e);
throw new IllegalArgumentException("Non-serializable object", e);
} finally {
try {
if (os != null)
os.close();
if (bos != null)
bos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
/**
* 反序列化对象
*
* @return Object
*/
public static Object unserialize(byte[] in) {
Object rv = null;
ByteArrayInputStream bis = null;
ObjectInputStream is = null;
try {
if (in != null) {
bis = new ByteArrayInputStream(in);
is = new ObjectInputStream(bis);
rv = is.readObject();
}
} catch (Exception e) {
logger.error("redis-unserialize异常", e);
} finally {
try {
if (is != null)
is.close();
if (bis != null)
bis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
return rv;
}
public static Long incr(String key, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (jedis == null) {
return null;
}
return jedis.incr(key);
} catch (Exception e) {
logger.error("redis-getString异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* Jedis执行Lua脚本,获取结果
*
* @param lua Lua字符串
* @param keys keys
* @param args 其他Lua需要参数
* @param dbIndex 索引
* @return
*/
public static Object evalLua(String lua, List<String> keys, List<String> args, int dbIndex) {
Jedis jedis = null;
try {
jedis = RedisManager.getResource(dbIndex);
if (jedis == null) {
return null;
}
return jedis.eval(lua, keys, args);
} catch (Exception e) {
logger.error("redis-执行Lua异常", e);
} finally {
if (jedis != null) {
jedis.close();
}
}
return null;
}
/**
* 自定义获取锁的超时时间
*
* @param key
* @param timeout
* @param waitTime
* @param timeUnit
* @return
* @throws InterruptedException
*/
public static boolean tryLock(String key, int timeout, long waitTime, TimeUnit timeUnit) throws InterruptedException {
try (Jedis jedis = RedisManager.getResource(LOCK_DB_INDEX)) {
long timeoutSeconds = timeUnit.toSeconds(timeout);
long waitTimeMicroSeconds = timeUnit.toMicros(waitTime);
while (waitTimeMicroSeconds >= 0) {
String result = jedis.set(key, "1", "nx", "ex", timeoutSeconds);
if ("OK".equals(result)) {
return true;
}
waitTimeMicroSeconds -= sleepTime;
Thread.sleep(sleepTime);
}
} catch (Exception e) {
logger.error("redis-setString异常", e);
}
return false;
}
/**
* 使用Lua脚本进行解锁操纵,解锁的时候验证value值
*
* @param key
* @return
*/
public static void unlock(String key) {
try (Jedis jedis = RedisManager.getResource(LOCK_DB_INDEX)) {
String luaScript = "if redis.call('get',KEYS[1]) == ARGV[1] then " +
"return redis.call('del',KEYS[1]) else return 0 end";
jedis.eval(luaScript, Collections.singletonList(key), Collections.singletonList("1")).equals(1L);
} catch (Exception e) {
logger.error("redis-setString异常", e);
}
}
}
三、总结
简洁
原文地址:https://blog.csdn.net/F15217283411/article/details/143568532
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!