企业级-实现Redis封装层

ops/2024/11/8 16:24:03/

作者: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);@Autowiredprivate ApplicationContext context;/*** 执行程序启动时初始化加载操作* * @param args* @throws Exception* @see CommandLineRunner#run(String[])*/@Overridepublic 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"); //申请端电子文书数据源keyCoreConstants.DOC_REDIS_DBINDEX = Integer.parseInt(torchBundle.getString("doc.redis.index")); // redis库IDCoreConstants.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);// 获取连接时的最大等待毫秒数,小于零:阻塞不确定的时间,默认-1long 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);}}}

三、总结

简洁


http://www.ppmy.cn/ops/131976.html

相关文章

masm汇编字符输入换行输出演示

从键盘读取一个字符并换行输出 assume cs:codecode segmentstart:mov ah, 1int 21hmov bl, almov dl, 10 mov ah, 2int 21h mov dl, blmov ah, 2int 21hmov ah, 4chint 21hcode ends end start 效果演示&#xff1a;

2-143 基于matlab-GUI的脉冲响应不变法实现音频滤波功能

基于matlab-GUI的脉冲响应不变法实现音频滤波功能&#xff0c;输入加噪信号&#xff0c;通过巴特沃斯模拟滤波器脉冲响应不变法进行降噪。效果较好。程序已调通&#xff0c;可直接运行。 下载源程序请点链接&#xff1a;2-143 基于matlab-GUI的脉冲响应不变法实现音频滤波功能…

dell 服务器 安装 centos 7.9 系统

dell 服务器 安装系统 cat /etc/redhat-release CentOS Linux release 7.9.2009 (Core) uname -r 3.10.0-1160.el7.x86_64 固定IP地址 ip addr 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000link/loopback 00:00:0…

Angular数据绑定详解

具体使用 插值绑定 (Interpolation)&#xff1a; 使用双大括号 {{ }} 来绑定组件类中的数据属性。例如&#xff1a; <h1>{{ title }}</h1>属性绑定 (Property Binding)&#xff1a; 通过方括号 [ ] 来绑定元素的属性。比如&#xff1a; <img [src]"imag…

c++设计模式demo

模式设计原则 依赖倒置原则 ⾼层模块不应该依赖低层模块&#xff0c;⼆者都应该依赖抽象 &#xff1b; 抽象不应该依赖具体实现&#xff0c;具体实现应该依赖于抽象&#xff1b; ⾃动驾驶系统公司是⾼层&#xff0c;汽⻋⽣产⼚商为低层&#xff0c;它们不应该互相依赖&#x…

Oracle Sql查询和性能优化(持续更新)

目录 索引优化 查询重写 EXISTS vs. IN 避免全表扫描 合理使用UNION操作符 优化子查询 执行计划分析 表设计优化 规范化与反规范化 分区表 存储参数调整 SGA配置 共享池 数据缓冲区 SGA自动管理 PGA配置 RAID配置 日志文件优化 性能诊断工具 AWR ASH 定期…

数据库基础知识总结

一、数据库简介 数据库是按照数据结构来组织、存储和管理数据的仓库。它就像是一个精心设计的文件柜&#xff0c;用于存放海量的数据信息&#xff0c;并且能够方便地对这些数据进行操作和检索。在当今数字化的时代&#xff0c;数据库在各个领域都有着至关重要的作用&#xff0c…

Spring Security 框架篇-深入了解 Spring Security 的授权核心功能(RBAC 权限模型、自定义异常处理器、校验权限方法)

&#x1f525;博客主页&#xff1a; 【小扳_-CSDN博客】 ❤感谢大家点赞&#x1f44d;收藏⭐评论✍ 文章目录 1.0 权限系统 1.1 引入 1.2 RBAC 权限模型 1.3 数据库设计 2.0 Spring Security 核心功能-授权 2.1 思路分析 2.2 编写 SQL 语句 2.3 将用户权限进行封装 2.4 获取用户…