当前位置:   article > 正文

spring boot 集成 redis spring-boot-starter-data-redis 2.1.7.RELEASE jedis: pool: #连接池配置 及踩坑经验_error creating bean with name 'redisutils': unsati

error creating bean with name 'redisutils': unsatisfied dependency expressed

目录

先上一些踩坑报错,各类报错

  @org.springframework.beans.factory.annotation.Autowired(required=true)

Error creating bean with name 'redisUtil': Unsatisfied dependency expressed through field 'redisTemplate'; 

 ERROR org.apache.catalina.core.ContainerBase.

Command timed out after 300 millisecond(s)

ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)] with root cause

nested exception is org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized token 'sss': was expecting ('true', 'false' or 'null')

介绍

代码

依赖

介绍

参数值

配置加载参数类 RedisConfig

工具类 RedisUtil

调用测试类 RedistCtr

页面访问地址

踩坑记录及解决方法思路


先上一些踩坑报错,各类报错

 

  @org.springframework.beans.factory.annotation.Autowired(required=true)

  1. 2020-12-24 10:53:12.562 ERROR org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter - 
  2. ***************************
  3. APPLICATION FAILED TO START
  4. ***************************
  5. Description:
  6. Field redisTemplate in com.superman.uitl.redis.RedisUtil required a bean of type 'org.springframework.data.redis.core.RedisTemplate' that could not be found.
  7. The injection point has the following annotations:
  8.     - @org.springframework.beans.factory.annotation.Autowired(required=true)

  

Error creating bean with name 'redisUtil': Unsatisfied dependency expressed through field 'redisTemplate'; 

  1. Consider defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.
  2. 2020-12-24 11:04:08.689 ERROR org.springframework.boot.SpringApplication - Application run failed
  3. org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisUtil': Unsatisfied dependency expressed through field 'redisTemplate'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisTemplate' defined in class path resource [com/superman/globaldao/redis/RedisConfig.class]: Unsatisfied dependency expressed through method 'redisTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Invalid redis sentinel property 'host1:port'
  4. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
  5. at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
  6. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
  7. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1411)
  8. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
  9. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
  10. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  11. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  12. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  13. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  14. at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:845)
  15. at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
  16. at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
  17. at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
  18. at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:743)
  19. at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:390)
  20. at org.springframework.boot.SpringApplication.run(SpringApplication.java:312)
  21. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1214)
  22. at org.springframework.boot.SpringApplication.run(SpringApplication.java:1203)
  23. at com.superman.Provider_App.main(Provider_App.java:31)
  24. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  25. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  26. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  27. at java.lang.reflect.Method.invoke(Method.java:498)
  28. at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
  29. Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisTemplate' defined in class path resource [com/superman/globaldao/redis/RedisConfig.class]: Unsatisfied dependency expressed through method 'redisTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Invalid redis sentinel property 'host1:port'
  30. at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:769)
  31. at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:509)
  32. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
  33. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
  34. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
  35. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
  36. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  37. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  38. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  39. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  40. at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
  41. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
  42. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
  43. at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
  44. ... 24 common frames omitted
  45. Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'redisConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Invalid redis sentinel property 'host1:port'
  46. at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627)
  47. at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607)
  48. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321)
  49. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160)
  50. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
  51. at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
  52. at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
  53. at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
  54. at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
  55. at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
  56. at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
  57. at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1251)
  58. at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1171)
  59. at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:857)
  60. at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:760)
  61. ... 37 common frames omitted
  62. Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory]: Factory method 'redisConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Invalid redis sentinel property 'host1:port'
  63. at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
  64. at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622)
  65. ... 51 common frames omitted
  66. Caused by: java.lang.IllegalStateException: Invalid redis sentinel property 'host1:port'
  67. at org.springframework.boot.autoconfigure.data.redis.RedisConnectionConfiguration.createSentinels(RedisConnectionConfiguration.java:122)
  68. at org.springframework.boot.autoconfigure.data.redis.RedisConnectionConfiguration.getSentinelConfig(RedisConnectionConfiguration.java:81)
  69. at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.createLettuceConnectionFactory(LettuceConnectionConfiguration.java:80)
  70. at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration.redisConnectionFactory(LettuceConnectionConfiguration.java:76)
  71. at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$4d3d62c8.CGLIB$redisConnectionFactory$0(<generated>)
  72. at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$4d3d62c8$$FastClassBySpringCGLIB$$375d6246.invoke(<generated>)
  73. at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244)
  74. at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363)
  75. at org.springframework.boot.autoconfigure.data.redis.LettuceConnectionConfiguration$$EnhancerBySpringCGLIB$$4d3d62c8.redisConnectionFactory(<generated>)
  76. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  77. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  78. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  79. at java.lang.reflect.Method.invoke(Method.java:498)
  80. at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
  81. ... 52 common frames omitted
  82. Caused by: java.lang.NumberFormatException: For input string: "port"
  83. at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
  84. at java.lang.Integer.parseInt(Integer.java:580)
  85. at java.lang.Integer.valueOf(Integer.java:766)
  86. at org.springframework.boot.autoconfigure.data.redis.RedisConnectionConfiguration.createSentinels(RedisConnectionConfiguration.java:119)
  87. ... 65 common frames omitted
  88. 2020-12-24 14:12:15.874 ERROR org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter -
  89. ***************************
  90. APPLICATION FAILED TO START

 

 ERROR org.apache.catalina.core.ContainerBase.

  1. Description:
  2. The bean 'redisConnectionFactory', defined in class path resource [org/springframework/boot/autoconfigure/data/redis/LettuceConnectionConfiguration.class], could not be registered. A bean with that name has already been defined in BeanDefinition defined in class path resource [com/superman/globaldao/redis/RedisConfig.class] and overriding is disabled.
  3. Action:
  4. Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true
  5. 2020-12-24 15:57:58.669 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.NullPointerException] with root cause
  6. java.lang.NullPointerException: null
  7. at com.superman.global.core.ctr.RedistCtr.query(RedistCtr.java:44)
  8. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  9. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  10. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  11. at java.lang.reflect.Method.invoke(Method.java:498)
  12. at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
  13. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
  14. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
  15. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
  16. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
  17. at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  18. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
  19. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
  20. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
  21. at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
  22. at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
  23. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
  24. at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
  25. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
  26. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  27. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  28. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  29. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  30. at com.superman.conf.filter.XssAndSqlFilter.doFilter(XssAndSqlFilter.java:81)
  31. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  32. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  33. at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
  34. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
  35. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  36. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  37. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
  38. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
  39. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
  40. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
  41. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  42. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
  43. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
  44. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
  45. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
  46. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
  47. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
  48. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  49. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  50. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  51. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  52. at java.lang.Thread.run(Thread.java:748)
  53. 2020-12-24 16:08:16.013 ERROR org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter -
  54. ***************************
  55. APPLICATION FAILED TO START
  56. ***************************

  

Command timed out after 300 millisecond(s)

  1. Consider revisiting the entries above or defining a bean of type 'org.springframework.data.redis.core.RedisTemplate' in your configuration.
  2. 2020-12-24 16:29:10.795 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)] with root cause
  3. io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)
  4. at io.lettuce.core.ExceptionFactory.createTimeoutException(ExceptionFactory.java:51)
  5. at io.lettuce.core.protocol.CommandExpiryWriter.lambda$potentiallyExpire$0(CommandExpiryWriter.java:167)
  6. at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)
  7. at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:127)
  8. at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66)
  9. at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
  10. at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
  11. at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
  12. at java.lang.Thread.run(Thread.java:748)
  13. 2020-12-24 16:29:32.654 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)] with root cause
  14. io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)
  15. at io.lettuce.core.ExceptionFactory.createTimeoutException(ExceptionFactory.java:51)
  16. at io.lettuce.core.protocol.CommandExpiryWriter.lambda$potentiallyExpire$0(CommandExpiryWriter.java:167)
  17. at io.netty.util.concurrent.PromiseTask$RunnableAdapter.call(PromiseTask.java:38)
  18. at io.netty.util.concurrent.ScheduledFutureTask.run(ScheduledFutureTask.java:127)
  19. at io.netty.util.concurrent.DefaultEventExecutor.run(DefaultEventExecutor.java:66)
  20. at io.netty.util.concurrent.SingleThreadEventExecutor$5.run(SingleThreadEventExecutor.java:918)
  21. at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
  22. at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
  23. at java.lang.Thread.run(Thread.java:748)
  24. 2020-12-24 16:31:15.241 ERROR org.apache.catalina.core.Conta

 

ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)] with root cause

  1. 2020-12-24 16:38:30.727 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)] with root cause
  2. io.lettuce.core.RedisCommandTimeoutException: Command timed out after 300 millisecond(s)
  3. at io.lettuce.core.ExceptionFactory.createTimeoutException(ExceptionFactory.java:51)
  4. at io.lettuce.core.LettuceFutures.awaitOrCancel(LettuceFutures.java:114)
  5. at io.lettuce.core.FutureSyncInvocationHandler.handleInvocation(FutureSyncInvocationHandler.java:69)
  6. at io.lettuce.core.internal.AbstractInvocationHandler.invoke(AbstractInvocationHandler.java:80)
  7. at com.sun.proxy.$Proxy104.get(Unknown Source)
  8. at org.springframework.data.redis.connection.lettuce.LettuceStringCommands.get(LettuceStringCommands.java:66)
  9. at org.springframework.data.redis.connection.DefaultedRedisConnection.get(DefaultedRedisConnection.java:253)
  10. at org.springframework.data.redis.core.DefaultValueOperations$1.inRedis(DefaultValueOperations.java:57)
  11. at org.springframework.data.redis.core.AbstractOperations$ValueDeserializingRedisCallback.doInRedis(AbstractOperations.java:59)
  12. at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:224)
  13. at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:184)
  14. at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:95)
  15. at org.springframework.data.redis.core.DefaultValueOperations.get(DefaultValueOperations.java:53)
  16. at com.superman.uitl.redis.RedisUtil.get(RedisUtil.java:90)
  17. at com.superman.global.core.ctr.RedistCtr.query(RedistCtr.java:43)
  18. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  19. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  20. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  21. at java.lang.reflect.Method.invoke(Method.java:498)
  22. at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
  23. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
  24. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
  25. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
  26. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
  27. at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  28. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
  29. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
  30. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
  31. at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
  32. at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
  33. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
  34. at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
  35. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
  36. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  37. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  38. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  39. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  40. at com.superman.conf.filter.XssAndSqlFilter.doFilter(XssAndSqlFilter.java:81)
  41. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  42. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  43. at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
  44. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
  45. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  46. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  47. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
  48. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
  49. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
  50. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
  51. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  52. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
  53. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
  54. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
  55. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
  56. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
  57. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
  58. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  59. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  60. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  61. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  62. at java.lang.Thread.run(Thread.java:748)

 

nested exception is org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized token 'sss': was expecting ('true', 'false' or 'null')

  1. 2020-12-24 16:50:07.288 ERROR org.apache.catalina.core.ContainerBase.[Tomcat].[localhost].[/].[dispatcherServlet] - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.redis.serializer.SerializationException: Could not read JSON: Unrecognized token 'sss': was expecting ('true', 'false' or 'null')
  2. at [Source: (byte[])"sss"; line: 1, column: 7]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'sss': was expecting ('true', 'false' or 'null')
  3. at [Source: (byte[])"sss"; line: 1, column: 7]] with root cause
  4. com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'sss': was expecting ('true', 'false' or 'null')
  5. at [Source: (byte[])"sss"; line: 1, column: 7]
  6. at com.fasterxml.jackson.core.JsonParser._constructError(JsonParser.java:1804)
  7. at com.fasterxml.jackson.core.base.ParserMinimalBase._reportError(ParserMinimalBase.java:703)
  8. at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._reportInvalidToken(UTF8StreamJsonParser.java:3532)
  9. at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._handleUnexpectedValue(UTF8StreamJsonParser.java:2627)
  10. at com.fasterxml.jackson.core.json.UTF8StreamJsonParser._nextTokenNotInObject(UTF8StreamJsonParser.java:832)
  11. at com.fasterxml.jackson.core.json.UTF8StreamJsonParser.nextToken(UTF8StreamJsonParser.java:729)
  12. at com.fasterxml.jackson.databind.ObjectMapper._initForReading(ObjectMapper.java:4141)
  13. at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4000)
  14. at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3129)
  15. at org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer.deserialize(Jackson2JsonRedisSerializer.java:73)
  16. at org.springframework.data.redis.core.AbstractOperations.deserializeValue(AbstractOperations.java:334)
  17. at org.springframework.data.redis.core.AbstractOperations$ValueDeserializingRedisCallback.doInRedis(AbstractOperations.java:60)
  18. at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:224)
  19. at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:184)
  20. at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:95)
  21. at org.springframework.data.redis.core.DefaultValueOperations.get(DefaultValueOperations.java:53)
  22. at com.superman.uitl.redis.RedisUtil.get(RedisUtil.java:90)
  23. at com.superman.global.core.ctr.RedistCtr.query(RedistCtr.java:43)
  24. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  25. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  26. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  27. at java.lang.reflect.Method.invoke(Method.java:498)
  28. at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
  29. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
  30. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
  31. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892)
  32. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797)
  33. at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  34. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1039)
  35. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
  36. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
  37. at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
  38. at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
  39. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
  40. at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
  41. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
  42. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  43. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  44. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  45. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  46. at com.superman.conf.filter.XssAndSqlFilter.doFilter(XssAndSqlFilter.java:81)
  47. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  48. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  49. at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
  50. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:118)
  51. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  52. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  53. at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
  54. at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
  55. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
  56. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
  57. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  58. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
  59. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
  60. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
  61. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
  62. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
  63. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
  64. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  65. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
  66. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
  67. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  68. at java.lang.Thread.run(Thread.java:748)

 

 

 

介绍

1.加载依赖

2.加载配置

3.spring 配置类 bean 自动读取使用配置

4.工具类

5.调用服务控制层

6.调用测试

ok

 

代码

依赖

  1. <!-- 集成redis使用 -->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. <version>2.1.7.RELEASE</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-cache</artifactId>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.apache.commons</groupId>
  13. <artifactId>commons-pool2</artifactId>
  14. <version>2.1</version>
  15. </dependency>
  16. <!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-context -->
  17. <dependency>
  18. <groupId>org.springframework.cloud</groupId>
  19. <artifactId>spring-cloud-context</artifactId>
  20. <version>2.1.6.RELEASE</version>
  21. </dependency>
  22. <!-- 集成redis使用 -->

介绍

有缺少json的可以再把json 搞上 import com.fasterxml.jackson.annotation.JsonAutoDetect; 如下,或网上搜搜挺多的

  1. <dependency>
  2. <groupId>com.fasterxml.jackson.core</groupId>
  3. <artifactId>jackson-annotations</artifactId>
  4. </dependency>

 

参数值

  1. spring:
  2. redis:
  3. #url: redis://user:password@127.0.0.1:6379 #该地址配置以后会重置host,port,password的规则。
  4. host: 127.0.0.1
  5. port: 6379
  6. #密码
  7. password: 123456
  8. database: 0 #指定数据库,默认为0
  9. timeout: 300 #连接超时时间,单位毫秒,默认为0
  10. ssl: false # 是否启用SSL连接,默认false
  11. jedis:
  12. pool: #连接池配置
  13. max-active: 8 #最大活跃连接数,默认8个。
  14. max-idle: 8 #最大空闲连接数,默认8个。
  15. max-wait: -1 #获取连接的最大等待时间,默认-1,表示无限制,单位毫秒。默认值可能会因为获取不到连接,导致事务无法提交,数据库被锁,大量线程处于等待状态的情况。
  16. min-idle: 0 #最小空闲连接数,默认0
  17. #sentinel:
  18. # master: mymaster #哨兵mastser
  19. # nodes: host1:port,host2:port #哨兵节点
  20. #cluster:
  21. # max-redirects: # 集群模式下,集群最大转发的数量
  22. # nodes: host1:port,host2:port # 集群节点

这个spring 前边有可能有个空格注意,不过也没啥大事,启动的时候要是系统报错也就看到了,你肯定没关注这句话,也可能页面自动给加载没了那个空格,自行关注吧

 

配置加载参数类 RedisConfig

  1. package com.superman.globaldao.redis;
  2. import org.springframework.context.annotation.Bean;
  3. import org.springframework.context.annotation.Configuration;
  4. import org.springframework.data.redis.connection.RedisConnectionFactory;
  5. import org.springframework.data.redis.core.RedisTemplate;
  6. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  7. import org.springframework.data.redis.serializer.StringRedisSerializer;
  8. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  9. import com.fasterxml.jackson.annotation.PropertyAccessor;
  10. import com.fasterxml.jackson.databind.ObjectMapper;
  11. /**
  12. * redis 配置<br/>
  13. * ----redisTemplate 中的 判断key是否纯在 接口 会一直返回false <br/>
  14. * ----采用 get(key)==null 来判断是否存在<br/>
  15. * <label style="color:red;">
  16. * 这里服务使用json 序列号,所以 上传的每个key val 要使用这里服务的 get set 如果直接使用redis-cli 有时候会解析不出来
  17. * </label>
  18. *
  19. * @author jianghy
  20. *
  21. * @version 1.0
  22. */
  23. @Configuration
  24. public class RedisConfig {
  25. @Bean
  26. @SuppressWarnings("all")
  27. public RedisTemplate<String, Object> redisTemplate( RedisConnectionFactory factory) {
  28. RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
  29. template.setConnectionFactory(factory);
  30. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer( Object.class);
  31. ObjectMapper om = new ObjectMapper();
  32. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  33. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  34. jackson2JsonRedisSerializer.setObjectMapper(om);
  35. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  36. // key采用String的序列化方式
  37. template.setKeySerializer(stringRedisSerializer);
  38. // hash的key也采用String的序列化方式
  39. template.setHashKeySerializer(stringRedisSerializer);
  40. // value序列化方式采用jackson
  41. template.setValueSerializer(jackson2JsonRedisSerializer);
  42. // hash的value序列化方式采用jackson
  43. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  44. template.afterPropertiesSet();
  45. return template;
  46. }
  47. }

 

工具类 RedisUtil

  1. package com.superman.uitl.redis;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.stereotype.Component;
  5. import org.springframework.util.CollectionUtils;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Set;
  9. import java.util.concurrent.TimeUnit;
  10. @Component
  11. public final class RedisUtil {
  12. @Autowired
  13. private RedisTemplate<String, Object> redisTemplate;
  14. // =============================common============================
  15. /**
  16. * 指定缓存失效时间
  17. * @param key 键
  18. * @param time 时间(秒)
  19. */
  20. public boolean expire(String key, long time) {
  21. try {
  22. if (time > 0) {
  23. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  24. }
  25. return true;
  26. } catch (Exception e) {
  27. e.printStackTrace();
  28. return false;
  29. }
  30. }
  31. /**
  32. * 根据key 获取过期时间
  33. * @param key 键 不能为null
  34. * @return 时间(秒) 返回0代表为永久有效
  35. */
  36. public long getExpire(String key) {
  37. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  38. }
  39. /**
  40. * 判断key是否存在 (不建议使用)
  41. * 由于序列号等各类型原因不方便,还是直接使用 Object c = get(key); c==null 来判断使用
  42. * @param key 键
  43. * @return true 存在 false不存在
  44. */
  45. public boolean hasKey(String key) {
  46. try {
  47. // Object c = redisTemplate.opsForValue().get(key);
  48. // return c==null?false:true;
  49. //由于序列化的原因,hasKey 一直返回false 可以使用上边方法,或使用修改redis修改序列号实现下边使用
  50. return redisTemplate.hasKey(key);
  51. } catch (Exception e) {
  52. e.printStackTrace();
  53. return false;
  54. }
  55. }
  56. /**
  57. * 删除缓存
  58. * @param key 可以传一个值 或多个
  59. */
  60. @SuppressWarnings("unchecked")
  61. public void del(String... key) {
  62. if (key != null && key.length > 0) {
  63. if (key.length == 1) {
  64. redisTemplate.delete(key[0]);
  65. } else {
  66. redisTemplate.delete(CollectionUtils.arrayToList(key));
  67. }
  68. }
  69. }
  70. // ============================String=============================
  71. /**
  72. * 普通缓存获取
  73. * @param key 键
  74. * @return 值
  75. */
  76. public Object get(String key) {
  77. return key == null ? null : redisTemplate.opsForValue().get(key);
  78. }
  79. /**
  80. * 普通缓存放入
  81. * @param key 键
  82. * @param value 值
  83. * @return true成功 false失败
  84. */
  85. public boolean set(String key, Object value) {
  86. try {
  87. redisTemplate.opsForValue().set(key, value);
  88. return true;
  89. } catch (Exception e) {
  90. e.printStackTrace();
  91. return false;
  92. }
  93. }
  94. /**
  95. * 普通缓存放入并设置时间
  96. * @param key 键
  97. * @param value 值
  98. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  99. * @return true成功 false 失败
  100. */
  101. public boolean set(String key, Object value, long time) {
  102. try {
  103. if (time > 0) {
  104. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  105. } else {
  106. set(key, value);
  107. }
  108. return true;
  109. } catch (Exception e) {
  110. e.printStackTrace();
  111. return false;
  112. }
  113. }
  114. /**
  115. * 递增
  116. * @param key 键
  117. * @param delta 要增加几(大于0)
  118. */
  119. public long incr(String key, long delta) {
  120. if (delta < 0) {
  121. throw new RuntimeException("递增因子必须大于0");
  122. }
  123. return redisTemplate.opsForValue().increment(key, delta);
  124. }
  125. /**
  126. * 递减
  127. * @param key 键
  128. * @param delta 要减少几(小于0)
  129. */
  130. public long decr(String key, long delta) {
  131. if (delta < 0) {
  132. throw new RuntimeException("递减因子必须大于0");
  133. }
  134. return redisTemplate.opsForValue().increment(key, -delta);
  135. }
  136. // ================================Map=================================
  137. /**
  138. * HashGet
  139. * @param key 键 不能为null
  140. * @param item 项 不能为null
  141. */
  142. public Object hget(String key, String item) {
  143. return redisTemplate.opsForHash().get(key, item);
  144. }
  145. /**
  146. * 获取hashKey对应的所有键值
  147. * @param key 键
  148. * @return 对应的多个键值
  149. */
  150. public Map<Object, Object> hmget(String key) {
  151. return redisTemplate.opsForHash().entries(key);
  152. }
  153. /**
  154. * HashSet
  155. * @param key 键
  156. * @param map 对应多个键值
  157. */
  158. public boolean hmset(String key, Map<String, Object> map) {
  159. try {
  160. redisTemplate.opsForHash().putAll(key, map);
  161. return true;
  162. } catch (Exception e) {
  163. e.printStackTrace();
  164. return false;
  165. }
  166. }
  167. /**
  168. * HashSet 并设置时间
  169. * @param key 键
  170. * @param map 对应多个键值
  171. * @param time 时间(秒)
  172. * @return true成功 false失败
  173. */
  174. public boolean hmset(String key, Map<String, Object> map, long time) {
  175. try {
  176. redisTemplate.opsForHash().putAll(key, map);
  177. if (time > 0) {
  178. expire(key, time);
  179. }
  180. return true;
  181. } catch (Exception e) {
  182. e.printStackTrace();
  183. return false;
  184. }
  185. }
  186. /**
  187. * 向一张hash表中放入数据,如果不存在将创建
  188. *
  189. * @param key 键
  190. * @param item 项
  191. * @param value 值
  192. * @return true 成功 false失败
  193. */
  194. public boolean hset(String key, String item, Object value) {
  195. try {
  196. redisTemplate.opsForHash().put(key, item, value);
  197. return true;
  198. } catch (Exception e) {
  199. e.printStackTrace();
  200. return false;
  201. }
  202. }
  203. /**
  204. * 向一张hash表中放入数据,如果不存在将创建
  205. *
  206. * @param key 键
  207. * @param item 项
  208. * @param value 值
  209. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  210. * @return true 成功 false失败
  211. */
  212. public boolean hset(String key, String item, Object value, long time) {
  213. try {
  214. redisTemplate.opsForHash().put(key, item, value);
  215. if (time > 0) {
  216. expire(key, time);
  217. }
  218. return true;
  219. } catch (Exception e) {
  220. e.printStackTrace();
  221. return false;
  222. }
  223. }
  224. /**
  225. * 删除hash表中的值
  226. *
  227. * @param key 键 不能为null
  228. * @param item 项 可以使多个 不能为null
  229. */
  230. public void hdel(String key, Object... item) {
  231. redisTemplate.opsForHash().delete(key, item);
  232. }
  233. /**
  234. * 判断hash表中是否有该项的值
  235. *
  236. * @param key 键 不能为null
  237. * @param item 项 不能为null
  238. * @return true 存在 false不存在
  239. */
  240. public boolean hHasKey(String key, String item) {
  241. return redisTemplate.opsForHash().hasKey(key, item);
  242. }
  243. /**
  244. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  245. *
  246. * @param key 键
  247. * @param item 项
  248. * @param by 要增加几(大于0)
  249. */
  250. public double hincr(String key, String item, double by) {
  251. return redisTemplate.opsForHash().increment(key, item, by);
  252. }
  253. /**
  254. * hash递减
  255. *
  256. * @param key 键
  257. * @param item 项
  258. * @param by 要减少记(小于0)
  259. */
  260. public double hdecr(String key, String item, double by) {
  261. return redisTemplate.opsForHash().increment(key, item, -by);
  262. }
  263. // ============================set=============================
  264. /**
  265. * 根据key获取Set中的所有值
  266. * @param key 键
  267. */
  268. public Set<Object> sGet(String key) {
  269. try {
  270. return redisTemplate.opsForSet().members(key);
  271. } catch (Exception e) {
  272. e.printStackTrace();
  273. return null;
  274. }
  275. }
  276. /**
  277. * 根据value从一个set中查询,是否存在
  278. *
  279. * @param key 键
  280. * @param value 值
  281. * @return true 存在 false不存在
  282. */
  283. public boolean sHasKey(String key, Object value) {
  284. try {
  285. return redisTemplate.opsForSet().isMember(key, value);
  286. } catch (Exception e) {
  287. e.printStackTrace();
  288. return false;
  289. }
  290. }
  291. /**
  292. * 将数据放入set缓存
  293. *
  294. * @param key 键
  295. * @param values 值 可以是多个
  296. * @return 成功个数
  297. */
  298. public long sSet(String key, Object... values) {
  299. try {
  300. return redisTemplate.opsForSet().add(key, values);
  301. } catch (Exception e) {
  302. e.printStackTrace();
  303. return 0;
  304. }
  305. }
  306. /**
  307. * 将set数据放入缓存
  308. *
  309. * @param key 键
  310. * @param time 时间(秒)
  311. * @param values 值 可以是多个
  312. * @return 成功个数
  313. */
  314. public long sSetAndTime(String key, long time, Object... values) {
  315. try {
  316. Long count = redisTemplate.opsForSet().add(key, values);
  317. if (time > 0)
  318. expire(key, time);
  319. return count;
  320. } catch (Exception e) {
  321. e.printStackTrace();
  322. return 0;
  323. }
  324. }
  325. /**
  326. * 获取set缓存的长度
  327. *
  328. * @param key 键
  329. */
  330. public long sGetSetSize(String key) {
  331. try {
  332. return redisTemplate.opsForSet().size(key);
  333. } catch (Exception e) {
  334. e.printStackTrace();
  335. return 0;
  336. }
  337. }
  338. /**
  339. * 移除值为value的
  340. *
  341. * @param key 键
  342. * @param values 值 可以是多个
  343. * @return 移除的个数
  344. */
  345. public long setRemove(String key, Object... values) {
  346. try {
  347. Long count = redisTemplate.opsForSet().remove(key, values);
  348. return count;
  349. } catch (Exception e) {
  350. e.printStackTrace();
  351. return 0;
  352. }
  353. }
  354. // ===============================list=================================
  355. /**
  356. * 获取list缓存的内容
  357. *
  358. * @param key 键
  359. * @param start 开始
  360. * @param end 结束 0 到 -1代表所有值
  361. */
  362. public List<Object> lGet(String key, long start, long end) {
  363. try {
  364. return redisTemplate.opsForList().range(key, start, end);
  365. } catch (Exception e) {
  366. e.printStackTrace();
  367. return null;
  368. }
  369. }
  370. /**
  371. * 获取list缓存的长度
  372. *
  373. * @param key 键
  374. */
  375. public long lGetListSize(String key) {
  376. try {
  377. return redisTemplate.opsForList().size(key);
  378. } catch (Exception e) {
  379. e.printStackTrace();
  380. return 0;
  381. }
  382. }
  383. /**
  384. * 通过索引 获取list中的值
  385. *
  386. * @param key 键
  387. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  388. */
  389. public Object lGetIndex(String key, long index) {
  390. try {
  391. return redisTemplate.opsForList().index(key, index);
  392. } catch (Exception e) {
  393. e.printStackTrace();
  394. return null;
  395. }
  396. }
  397. /**
  398. * 将list放入缓存
  399. *
  400. * @param key 键
  401. * @param value 值
  402. */
  403. public boolean lSet(String key, Object value) {
  404. try {
  405. redisTemplate.opsForList().rightPush(key, value);
  406. return true;
  407. } catch (Exception e) {
  408. e.printStackTrace();
  409. return false;
  410. }
  411. }
  412. /**
  413. * 将list放入缓存
  414. * @param key 键
  415. * @param value 值
  416. * @param time 时间(秒)
  417. */
  418. public boolean lSet(String key, Object value, long time) {
  419. try {
  420. redisTemplate.opsForList().rightPush(key, value);
  421. if (time > 0)
  422. expire(key, time);
  423. return true;
  424. } catch (Exception e) {
  425. e.printStackTrace();
  426. return false;
  427. }
  428. }
  429. /**
  430. * 将list放入缓存
  431. *
  432. * @param key 键
  433. * @param value 值
  434. * @return
  435. */
  436. public boolean lSet(String key, List<Object> value) {
  437. try {
  438. redisTemplate.opsForList().rightPushAll(key, value);
  439. return true;
  440. } catch (Exception e) {
  441. e.printStackTrace();
  442. return false;
  443. }
  444. }
  445. /**
  446. * 将list放入缓存
  447. *
  448. * @param key 键
  449. * @param value 值
  450. * @param time 时间(秒)
  451. * @return
  452. */
  453. public boolean lSet(String key, List<Object> value, long time) {
  454. try {
  455. redisTemplate.opsForList().rightPushAll(key, value);
  456. if (time > 0)
  457. expire(key, time);
  458. return true;
  459. } catch (Exception e) {
  460. e.printStackTrace();
  461. return false;
  462. }
  463. }
  464. /**
  465. * 根据索引修改list中的某条数据
  466. *
  467. * @param key 键
  468. * @param index 索引
  469. * @param value 值
  470. * @return
  471. */
  472. public boolean lUpdateIndex(String key, long index, Object value) {
  473. try {
  474. redisTemplate.opsForList().set(key, index, value);
  475. return true;
  476. } catch (Exception e) {
  477. e.printStackTrace();
  478. return false;
  479. }
  480. }
  481. /**
  482. * 移除N个值为value
  483. *
  484. * @param key 键
  485. * @param count 移除多少个
  486. * @param value 值
  487. * @return 移除的个数
  488. */
  489. public long lRemove(String key, long count, Object value) {
  490. try {
  491. Long remove = redisTemplate.opsForList().remove(key, count, value);
  492. return remove;
  493. } catch (Exception e) {
  494. e.printStackTrace();
  495. return 0;
  496. }
  497. }
  498. }

 

调用测试类 RedistCtr

  1. package com.superman.global.core.ctr;
  2. import javax.servlet.http.HttpServletRequest;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.RequestMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. import com.alibaba.druid.support.logging.Log;
  7. import com.alibaba.druid.support.logging.LogFactory;
  8. import com.superman.uitl.redis.RedisUtil;
  9. /**
  10. * 调用redis服务
  11. *
  12. * @author jianghy
  13. *
  14. * @version 1.0
  15. */
  16. @RestController
  17. @RequestMapping("/RedisttestCtr")
  18. public class RedisttestCtr {
  19. private final static Log log = LogFactory.getLog(RedisttestCtr.class);
  20. @Autowired
  21. private RedisUtil ru;
  22. /**
  23. * reids 查看 key
  24. *
  25. * @param key 查询key
  26. *
  27. * @return
  28. */
  29. @RequestMapping(value="/query", produces = "text/html;charset=UTF-8;")
  30. public String query(HttpServletRequest req){
  31. String userid = req.getParameter("userid");
  32. String key = req.getParameter("key")==null?"":req.getParameter("key");
  33. log.info(userid+" get redis key:"+key);
  34. if(key.equals(""))return "params error";
  35. Object c = ru.get(key);
  36. System.out.println(c);
  37. return c==null?"null":c.toString();
  38. }
  39. /**
  40. * reids 添加 key
  41. *
  42. * @param key 查询key
  43. * @param val 查询val
  44. *
  45. * @return
  46. */
  47. @RequestMapping(value="/execute", produces = "text/html;charset=UTF-8;")
  48. public String execute(HttpServletRequest req){
  49. String userid = req.getParameter("userid");
  50. String key = req.getParameter("key")==null?"":req.getParameter("key");
  51. String val = req.getParameter("val")==null?"":req.getParameter("val");
  52. log.info(userid+" get redis key:"+key);
  53. if(key.equals(""))return "params error";
  54. boolean rest = ru.set(key,val);
  55. return rest==true?"success":"fial";
  56. }
  57. }

 

页面访问地址

https://localhost:9087/RedisttestCtr/query?key=aa

https://localhost:9087/RedisttestCtr/execute?key=aa&val=ss

 

踩坑记录及解决方法思路

踩坑种类

1.序列化问题

2.未启动redis

3.redis 加载卡住

4.加载参数为加载

5.jedis 和 其他pool 的问题

6.泛型<Stirng,String> <String,Object>

7.各类问题,使用如上这批代码即可

8.hashKey 一直返回false 问题

9.redis-cli 上传的 set  值 和 程序set 上的值不一样,导致无法解析出报错

10.都用如上这批代码即可

 

 

 

 

 

 

ok

 

 

 

 

 

 

持续更新

 

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/2023面试高手/article/detail/251164
推荐阅读
相关标签
  

闽ICP备14008679号