封装RedisUtils,静态调用超级简单。【xdxFramework】

2024-04-16 15:48

本文主要是介绍封装RedisUtils,静态调用超级简单。【xdxFramework】,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

这里做一个Reids的封装,可能相对有些复杂,但是很好用,全是静态方法直接调用,不需要每次都注入。
下面我的会详细的把过程列举出来,如果还是有问题可以联系我。


1、项目截图

在这里插入图片描述


2、代码

2-1:RedisConfig
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;import java.lang.reflect.Method;
import java.time.Duration;//继承CachingConfigurerSupport,为了自定义生成KEY的策略。可以不继承。
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {@Value("${spring.redis.jedis.pool.max-idle}")private Integer maxidle;@Value("${spring.redis.jedis.pool.min-idle}")private Integer minidle;@Value("${spring.redis.jedis.pool.max-active}")private Integer maxActive;@Value("${spring.redis.jedis.pool.min-idle}")private Integer maxWait;@Value("${spring.redis.host}")private String host;@Value("${spring.redis.port}")private Integer port;@Value("${spring.redis.database}")private Integer database;@Value("${spring.redis.password}")private String password;@Value("${spring.redis.timeout}")private Integer timeout;/*** 缓存管理器.* * @param redisTemplate* @return*/@Beanpublic CacheManager cacheManager(RedisConnectionFactory connectionFactory) {RedisCacheManager manager = RedisCacheManager.create(connectionFactory);return manager;}/*** JedisPoolConfig 连接池* * @return*/@Beanpublic JedisPoolConfig jedisPoolConfig() {JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();Integer maxidle = this.maxidle;Integer minidle = this.minidle;Integer maxActive = this.maxActive;Integer maxWait = this.maxWait;// 最大空闲数jedisPoolConfig.setMaxIdle(maxidle);jedisPoolConfig.setMinIdle(minidle);// 连接池的最大数据库连接数jedisPoolConfig.setMaxTotal(maxActive);// 最大建立连接等待时间jedisPoolConfig.setMaxWaitMillis(maxWait);// Idle时进行连接扫描jedisPoolConfig.setTestWhileIdle(true);// 表示idle object evitor两次扫描之间要sleep的毫秒数jedisPoolConfig.setTimeBetweenEvictionRunsMillis(30000);// 表示idle object evitor每次扫描的最多的对象数jedisPoolConfig.setNumTestsPerEvictionRun(10);// 表示一个对象至少停留在idle状态的最短时间,然后才能被idle object// evitor扫描并驱逐;这一项只有在timeBetweenEvictionRunsMillis大于0时才有意义jedisPoolConfig.setMinEvictableIdleTimeMillis(60000);// 在borrow一个jedis实例时,是否提前进行alidate操作jedisPoolConfig.setTestOnBorrow(true);// 在return给pool时,是否提前进行validate操作jedisPoolConfig.setTestOnReturn(true);return jedisPoolConfig;}@Beanpublic JedisConnectionFactory connectionFactory(JedisPoolConfig jedisPoolConfig) {String host = this.host;Integer port = this.port;Integer database = this.database;String password = this.password;Integer timeout = this.timeout;RedisStandaloneConfiguration rf = new RedisStandaloneConfiguration();rf.setHostName(host);rf.setPort(port);rf.setDatabase(database);rf.setPassword(RedisPassword.of(password));JedisClientConfiguration.JedisClientConfigurationBuilder jedisClientConfiguration = JedisClientConfiguration.builder();JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpb = jedisClientConfiguration.usePooling();jedisClientConfiguration.connectTimeout(Duration.ofMillis(timeout));// connection timeout// 连接池jpb.poolConfig(jedisPoolConfig);JedisConnectionFactory factory = new JedisConnectionFactory(rf,jedisClientConfiguration.build());return factory;}/*** 注解@Cache key生成规则*/@Bean@Overridepublic KeyGenerator keyGenerator() {return new KeyGenerator() {@Overridepublic Object generate(Object target, Method method, Object... params) {StringBuilder sb = new StringBuilder();sb.append(target.getClass().getName());sb.append(method.getName());for (Object obj : params) {sb.append(obj.toString());} return sb.toString();}};}// 设置数据存入 redis 的序列化方式@SuppressWarnings({ "rawtypes", "unchecked" })@Beanpublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {// 创建一个模板类RedisTemplate<Object, Object> template = new RedisTemplate<>();// 将redis连接工厂设置到模板类中template.setConnectionFactory(factory);// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值(默认使用JDK的序列化方式)Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);serializer.setObjectMapper(mapper);// 开启事务
//		template.setEnableTransactionSupport(true);template.setValueSerializer(serializer);// 使用StringRedisSerializer来序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.afterPropertiesSet(); return template;}
}

2-2:CacheContext
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.concurrent.TimeUnit;/*** 缓存管理工具* @author 小道仙* @date 2020年2月26日*/
public class CacheContext<T extends CacheManager> {static CacheManager cache;/*** 初始化方法** @author 小道仙* @date 2020年2月26日* @version 1.0*/@SuppressWarnings("unchecked")public void init() {Type type = this.getClass().getGenericSuperclass();if (type instanceof ParameterizedType) {Class<T> entityClass;Type[] parameterizedType = ((ParameterizedType) type).getActualTypeArguments();entityClass = (Class<T>) parameterizedType[0];try {cache = entityClass.newInstance();cache.init();} catch (InstantiationException | IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}/*** 批量删除对应的value* * @param keys*/public static void remove(final String... keys) {cache.remove(keys);}/*** 删除对应的value* * @param key*/public static boolean remove(final String key) {return cache.remove(key);}/*** 判断缓存中是否有对应的value* * @param key* @return*/public static boolean exists(final String key) {return cache.exists(key);}/*** 读取缓存* * @param key* @return*/public static Object get(final String key) {return cache.get(key);}/*** 写入缓存* * @param key* @param value* @return*/public static boolean set(final String key, Object value) {return cache.set(key, value);}/*** 写入缓存(可以配置过期时间-单位分钟)* * @param key* @param value* @return*/public static boolean set(final String key, Object value, long expireTime) {return cache.set(key, value, expireTime);}/*** 设置缓存时间,默认单位分钟* @param key* @param timeout* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/public static  Boolean expire(String key, final long timeout) {return cache.expire(key, timeout);}/*** 设置缓存时间* @param key* @param timeout* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/public static Boolean expire(String key, final long timeout, final TimeUnit unit) {return cache.expire(key, timeout,unit);} /*** 获取key有效期* * @param key* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/public static Long getExpire(String key) {return cache.getExpire(key);}
}

2-3:CacheManager

import java.util.concurrent.TimeUnit;public interface CacheManager {/*** 默认过期时间,单位分钟*/Long defaultExpirationTime =  30L;/*** 初始化方法* * @author 小道仙* @date 2020年2月26日* @version 1.0*/void init();/*** 批量删除对应的value* * @param keys*/void remove(final String... keys);/*** 删除对应的value* * @param key*/boolean remove(final String key);/*** 判断缓存中是否有对应的value* * @param key* @return*/boolean exists(final String key);/*** 读取缓存* * @param key* @return*/Object get(final String key);/*** 写入缓存* * @param key* @param value* @return*/boolean set(final String key, Object value);/*** 写入缓存(可以配置过期时间-单位分钟)* * @param key* @param value* @return*/boolean set(final String key, Object value, long expireTime);/*** 设置缓存时间,默认单位分钟* * @param key* @param timeout* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/Boolean expire(String key, final long timeout);/*** 设置缓存时间* * @param key* @param timeout* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/Boolean expire(String key, final long timeout, final TimeUnit unit);/*** 获取key有效期* * @param key* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/Long getExpire(String key);
}

2-4:RedisManager
import com.xdx97.framework.utils.SpringContextUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Set;
import java.util.concurrent.TimeUnit;@Component
public class RedisManager implements CacheManager {private final Logger logger = LoggerFactory.getLogger(RedisManager.class);@Resourceprotected RedisTemplate<Serializable, Object> redisTemplate;@Overridepublic void init() {@SuppressWarnings("unchecked")RedisTemplate<Serializable, Object> redisTemplate = (RedisTemplate<Serializable, Object>) SpringContextUtils.getBean("redisTemplate");if (redisTemplate != null && this.redisTemplate == null) {this.redisTemplate = redisTemplate;}}/*** 批量删除对应的value* * @param keys*/@Overridepublic void remove(final String... keys) {for (String key : keys) {remove(key);}}/*** 批量删除key(通配符)* * @param pattern*/public void removePattern(final String pattern) {Set<Serializable> keys = redisTemplate.keys(pattern);if (keys.size() > 0){redisTemplate.delete(keys);}}/*** 删除对应的value* * @param key*/@Overridepublic boolean remove(final String key) {if (exists(key)) {return redisTemplate.delete(key);}return true;}/*** 判断缓存中是否有对应的value* * @param key* @return*/@Overridepublic boolean exists(final String key) {return redisTemplate.hasKey(key);}/*** 读取缓存* * @param key* @return*/@Overridepublic Object get(final String key) {if (!exists(key)) {return null;}Object result = null;ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();result = operations.get(key);return result;}/*** 写入缓存* * @param key* @param value* @return*/@Overridepublic boolean set(final String key, Object value) {Integer expire = defaultExpirationTime.intValue() ;return set(key, value, expire);}/*** 写入缓存(可以配置过期时间-单位分钟)* * @param key* @param value* @return*/@Overridepublic boolean set(final String key, Object value, long expireTime) {boolean result = false;try {if (expireTime <= 0) {logger.warn("设置缓存时间不能小于0,key:{},value:{}", key, value);return result;}ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();operations.set(key, value);expire(key, expireTime);result = true;} catch (Exception e) {logger.warn("缓存设置失败,key:{},value:{}", key, value);}return result;}@Overridepublic Boolean expire(String key, final long timeout) {return redisTemplate.expire(key, timeout, TimeUnit.MINUTES);}@Overridepublic Boolean expire(String key, final long timeout, final TimeUnit unit) {return redisTemplate.expire(key, timeout, unit);}/*** 获取key有效期* * @param key* @return* @author 小道仙* @date 2020年2月26日* @version 1.0*/@Overridepublic Long getExpire(String key) {return redisTemplate.getExpire(key) == null ? 0 : redisTemplate.getExpire(key);}public void setRedisTemplate(RedisTemplate<Serializable, Object> redisTemplate) {this.redisTemplate = redisTemplate;}public RedisTemplate<Serializable, Object> getRedisTemplate() {return redisTemplate;}
}
2-5:RedisUtils
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;/*** RedisUtils** @DependsOn(value = "springContextUtils")* 作用是在这之前加载springContextUtils bean** @author 小道仙* @date 2020年2月26日*/
@Component
@DependsOn(value = "springContextUtils")
public class RedisUtils extends CacheContext<RedisManager>{public RedisUtils() {super.init();}
}

2-6:SpringContextUtils
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;/*** Spring Context 工具类* * @author 小道仙* @date 2020年2月26日*/
@Component
public class SpringContextUtils implements ApplicationContextAware {private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {SpringContextUtils.applicationContext = applicationContext;}public static ApplicationContext getApplicationContext() {assertApplicationContext();return applicationContext;}@SuppressWarnings("unchecked")public static <T> T getBean(String beanName) {assertApplicationContext();return (T) applicationContext.getBean(beanName);}public static <T> T getBean(Class<T> requiredType) {assertApplicationContext();return applicationContext.getBean(requiredType);}private static void assertApplicationContext() {if (SpringContextUtils.applicationContext == null) {throw new RuntimeException("applicaitonContext属性为null,请检查是否注入了SpringContextHolder!");}}}

2-7: yml

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-edpwGNM3-1582699118287)(https://www.xdx97.com:8185/api/preview?url=uploads/ARTICLE/root/article/2020-02-26/xdx_qXYi7XsGUzAdNIKx.png)]

    # redis配置redis:database: 0host: 47.100.60.252port: 8379password: fdE#84K$EW~timeout: 3000jedis:pool:max-active: 8max-idle: 8max-wait: -1min-idle: 0

3、使用

封装的时候有点麻烦,所以使用的时候超级简单了。

在这里插入图片描述


关注我吧,和我一起进步:
在这里插入图片描述

这篇关于封装RedisUtils,静态调用超级简单。【xdxFramework】的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/909227

相关文章

SpringBoot中@Value注入静态变量方式

《SpringBoot中@Value注入静态变量方式》SpringBoot中静态变量无法直接用@Value注入,需通过setter方法,@Value(${})从属性文件获取值,@Value(#{})用... 目录项目场景解决方案注解说明1、@Value("${}")使用示例2、@Value("#{}"php

Python 基于http.server模块实现简单http服务的代码举例

《Python基于http.server模块实现简单http服务的代码举例》Pythonhttp.server模块通过继承BaseHTTPRequestHandler处理HTTP请求,使用Threa... 目录测试环境代码实现相关介绍模块简介类及相关函数简介参考链接测试环境win11专业版python

Java调用Python脚本实现HelloWorld的示例详解

《Java调用Python脚本实现HelloWorld的示例详解》作为程序员,我们经常会遇到需要在Java项目中调用Python脚本的场景,下面我们来看看如何从基础到进阶,一步步实现Java与Pyth... 目录一、环境准备二、基础调用:使用 Runtime.exec()2.1 实现步骤2.2 代码解析三、

Python如何调用另一个类的方法和属性

《Python如何调用另一个类的方法和属性》在Python面向对象编程中,类与类之间的交互是非常常见的场景,本文将详细介绍在Python中一个类如何调用另一个类的方法和属性,大家可以根据需要进行选择... 目录一、前言二、基本调用方式通过实例化调用通过类继承调用三、高级调用方式通过组合方式调用通过类方法/静

C#控制台程序同步调用WebApi实现方式

《C#控制台程序同步调用WebApi实现方式》控制台程序作为Job时,需同步调用WebApi以确保获取返回结果后执行后续操作,否则会引发TaskCanceledException异常,同步处理可避免异... 目录同步调用WebApi方法Cls001类里面的写法总结控制台程序一般当作Job使用,有时候需要控制

python连接sqlite3简单用法完整例子

《python连接sqlite3简单用法完整例子》SQLite3是一个内置的Python模块,可以通过Python的标准库轻松地使用,无需进行额外安装和配置,:本文主要介绍python连接sqli... 目录1. 连接到数据库2. 创建游标对象3. 创建表4. 插入数据5. 查询数据6. 更新数据7. 删除

Jenkins的安装与简单配置过程

《Jenkins的安装与简单配置过程》本文简述Jenkins在CentOS7.3上安装流程,包括Java环境配置、RPM包安装、修改JENKINS_HOME路径及权限、启动服务、插件安装与系统管理设置... 目录www.chinasem.cnJenkins安装访问并配置JenkinsJenkins配置邮件通知

Python用Flask封装API及调用详解

《Python用Flask封装API及调用详解》本文介绍Flask的优势(轻量、灵活、易扩展),对比GET/POST表单/JSON请求方式,涵盖错误处理、开发建议及生产环境部署注意事项... 目录一、Flask的优势一、基础设置二、GET请求方式服务端代码客户端调用三、POST表单方式服务端代码客户端调用四

通过配置nginx访问服务器静态资源的过程

《通过配置nginx访问服务器静态资源的过程》文章介绍了图片存储路径设置、Nginx服务器配置及通过http://192.168.206.170:8007/a.png访问图片的方法,涵盖图片管理与服务... 目录1.图片存储路径2.nginx配置3.访问图片方式总结1.图片存储路径2.nginx配置

Python跨文件实例化、跨文件调用及导入库示例代码

《Python跨文件实例化、跨文件调用及导入库示例代码》在Python开发过程中,经常会遇到需要在一个工程中调用另一个工程的Python文件的情况,:本文主要介绍Python跨文件实例化、跨文件调... 目录1. 核心对比表格(完整汇总)1.1 自定义模块跨文件调用汇总表1.2 第三方库使用汇总表1.3 导