自定义一个RedisTemplate

2024-04-27 14:28
文章标签 自定义 redistemplate

本文主要是介绍自定义一个RedisTemplate,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1.引入依赖

        <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId></dependency>

2.创建工具类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import javax.annotation.PostConstruct;/*** @创建人 lr* @创建时间 2024-04-14* @描述*/
@Component
@Slf4j
public class MyRedisTemplate {public static String KEY = "test:old:boot:";@Value("${jeecg_redis.host:local_use1}")public String host;@Value("${jeecg_redis.port:6379}")public Integer port;@Value("${jeecg_redis.password:}")public String password;@Value("${jeecg_redis.db:4}")public Integer db;RedisTemplate<String, String> redisTemplate = null;@PostConstructpublic RedisTemplate<String, String> getResisTemplate() {RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(host, port);if(password !=null && !"".equals(password))configuration.setPassword(password);configuration.setDatabase(db);JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(configuration);//让配置生效 否则会报错//java.lang.IllegalStateException: JedisConnectionFactory was not initialized through afterPropertiesSet()jedisConnectionFactory.afterPropertiesSet();redisTemplate = new RedisTemplate<>();redisTemplate.setConnectionFactory(jedisConnectionFactory);GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();redisTemplate.setKeySerializer(RedisSerializer.string());redisTemplate.setHashKeySerializer(RedisSerializer.string());redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);redisTemplate.afterPropertiesSet();return redisTemplate;}/*** 保存字符串类型数据* @param str_name 保存字符串名字* @param str_value	保存字符串值* @param expire_minutes	保存字符串时间,是分钟* @return*/public boolean insertStr(String str_name,String str_value,Long expire_minutes){str_name = getKey(str_name);try {log.info("redisService保存redis字符串str_name:{}---str_value:{}--expire_time:{}",str_name,str_value,expire_minutes);redisTemplate.opsForValue().set(str_name, str_value, expire_minutes, TimeUnit.MINUTES);return true;} catch (Exception e) {log.error("redisService保存系统异常:",e.getLocalizedMessage());e.printStackTrace();return false;}}/*** 更新字符串类型数据* @param str_name	字符串名字* @param str_value	字符串值* @param expire_time	字符串时间,是分钟* @return*/public boolean updateStr(String str_name,String str_value,Long expire_time){str_name = getKey(str_name);try {log.info("redisService更新redis字符串str_name:{}---str_value:{}--expire_time:{}",str_name,str_value,expire_time);//如果存在直接删除Boolean hasKey = redisTemplate.hasKey(str_name);if(hasKey){redisTemplate.delete(str_name);}//重新保存redisTemplate.opsForValue().set(str_name, str_value, expire_time, TimeUnit.MINUTES);return true;} catch (Exception e) {log.error("redisService更新系统异常:",e.getLocalizedMessage());e.printStackTrace();return false;}}/*** 删除字符串类型数据* @param str_name	字符串名字* @return*/public Boolean deleteStr(String str_name){str_name = getKey(str_name);try {log.info("redisService删除redis字符串str_name:{}",str_name);//如果存在就获取Boolean hasKey = redisTemplate.hasKey(str_name);if(hasKey){redisTemplate.delete(str_name);}return true;} catch (Exception e) {log.error("redisService删除系统异常:",e.getLocalizedMessage());e.printStackTrace();return false;}}public Boolean exist(String str_name) {str_name = getKey(str_name);return redisTemplate.hasKey(str_name);}/*** 查找字符串类型数据* @param str_name	字符串名字* @return*/public String selectStr(String str_name){str_name = getKey(str_name);try {log.info("redisService保存redis字符串str_name:{}",str_name);//如果存在就获取Boolean hasKey = redisTemplate.hasKey(str_name);Object str = null;if(hasKey){str= redisTemplate.opsForValue().get(str_name);log.info("redisService查找redis字符串str_name:{}--str_value:{}",str_name,str);}return str!=null?str.toString():"";} catch (Exception e) {log.error("redisService查询系统异常:",e.getLocalizedMessage());e.printStackTrace();return null;}}public boolean expire(String token, long minutes) {Boolean expire = redisTemplate.expire(token, minutes, TimeUnit.MINUTES);return expire;}public String getKey(String key) {return new StringBuffer(KEY).append(key).toString();}}

3.记录异常

java.lang.IllegalStateException: JedisConnectionFactory was not initialized through afterPropertiesSet()at org.springframework.util.Assert.state(Assert.java:76)at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.assertInitialized(JedisConnectionFactory.java:970)at org.springframework.data.redis.connection.jedis.JedisConnectionFactory.getConnection(JedisConnectionFactory.java:509)at org.springframework.data.redis.core.RedisConnectionUtils.fetchConnection(RedisConnectionUtils.java:193)at org.springframework.data.redis.core.RedisConnectionUtils.doGetConnection(RedisConnectionUtils.java:144)at org.springframework.data.redis.core.RedisConnectionUtils.getConnection(RedisConnectionUtils.java:105)at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:211)at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:191)at org.springframework.data.redis.core.RedisTemplate.hasKey(RedisTemplate.java:782)at org.jeecg.common.util.easy.MyRedisTemplate.selectStr(MyRedisTemplate.java:132)at org.jeecg.config.shiro.ShiroRealm.checkUserTokenIsEffect(ShiroRealm.java:121)at org.jeecg.config.shiro.ShiroRealm.doGetAuthenticationInfo(ShiroRealm.java:111)at org.apache.shiro.realm.AuthenticatingRealm.getAuthenticationInfo(AuthenticatingRealm.java:571)at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doSingleRealmAuthentication(ModularRealmAuthenticator.java:180)at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doAuthenticate(ModularRealmAuthenticator.java:273)at org.apache.shiro.authc.AbstractAuthenticator.authenticate(AbstractAuthenticator.java:198)at org.apache.shiro.mgt.AuthenticatingSecurityManager.authenticate(AuthenticatingSecurityManager.java:106)at org.apache.shiro.mgt.DefaultSecurityManager.login(DefaultSecurityManager.java:275)at org.apache.shiro.subject.support.DelegatingSubject.login(DelegatingSubject.java:260)at org.jeecg.config.shiro.filters.JwtFilter.executeLogin(JwtFilter.java:74)at org.jeecg.config.shiro.filters.JwtFilter.isAccessAllowed(JwtFilter.java:50)at org.apache.shiro.web.filter.AccessControlFilter.onPreHandle(AccessControlFilter.java:162)at org.apache.shiro.web.filter.PathMatchingFilter.isFilterChainContinued(PathMatchingFilter.java:223)at org.apache.shiro.web.filter.PathMatchingFilter.preHandle(PathMatchingFilter.java:198)at org.jeecg.config.shiro.filters.JwtFilter.preHandle(JwtFilter.java:108)at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:131)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:154)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:154)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:458)at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:373)at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:370)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:154)at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:354)at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.springframework.boot.actuate.web.trace.servlet.HttpTraceFilter.doFilterInternal(HttpTraceFilter.java:88)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:154)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:154)at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:458)at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:373)at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:370)at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:154)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:96)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:168)at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:481)at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:130)at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:390)at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:928)at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1794)at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)at java.lang.Thread.run(Thread.java:748)

造成问题原因:  

jedisConnectionFactory没有让配置生效

这篇关于自定义一个RedisTemplate的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



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

相关文章

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

基于Spring实现自定义错误信息返回详解

《基于Spring实现自定义错误信息返回详解》这篇文章主要为大家详细介绍了如何基于Spring实现自定义错误信息返回效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录背景目标实现产出背景Spring 提供了 @RestConChina编程trollerAdvice 用来实现 HTT

SpringSecurity 认证、注销、权限控制功能(注销、记住密码、自定义登入页)

《SpringSecurity认证、注销、权限控制功能(注销、记住密码、自定义登入页)》SpringSecurity是一个强大的Java框架,用于保护应用程序的安全性,它提供了一套全面的安全解决方案... 目录简介认识Spring Security“认证”(Authentication)“授权” (Auth

SpringBoot自定义注解如何解决公共字段填充问题

《SpringBoot自定义注解如何解决公共字段填充问题》本文介绍了在系统开发中,如何使用AOP切面编程实现公共字段自动填充的功能,从而简化代码,通过自定义注解和切面类,可以统一处理创建时间和修改时间... 目录1.1 问题分析1.2 实现思路1.3 代码开发1.3.1 步骤一1.3.2 步骤二1.3.3

dubbo3 filter(过滤器)如何自定义过滤器

《dubbo3filter(过滤器)如何自定义过滤器》dubbo3filter(过滤器)类似于javaweb中的filter和springmvc中的intercaptor,用于在请求发送前或到达前进... 目录dubbo3 filter(过滤器)简介dubbo 过滤器运行时机自定义 filter第一种 @A

CSS自定义浏览器滚动条样式完整代码

《CSS自定义浏览器滚动条样式完整代码》:本文主要介绍了如何使用CSS自定义浏览器滚动条的样式,包括隐藏滚动条的角落、设置滚动条的基本样式、轨道样式和滑块样式,并提供了完整的CSS代码示例,通过这些技巧,你可以为你的网站添加个性化的滚动条样式,从而提升用户体验,详细内容请阅读本文,希望能对你有所帮助...

SpringBoot 自定义消息转换器使用详解

《SpringBoot自定义消息转换器使用详解》本文详细介绍了SpringBoot消息转换器的知识,并通过案例操作演示了如何进行自定义消息转换器的定制开发和使用,感兴趣的朋友一起看看吧... 目录一、前言二、SpringBoot 内容协商介绍2.1 什么是内容协商2.2 内容协商机制深入理解2.2.1 内容

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06