当前位置:   article > 正文

SpringBoot整合Spring Cache实现Redis缓存_springboot cache redis

springboot cache redis

1. Spring Cache 简介

Spring Cache是Spring框架提供的一种缓存抽象,它简化了缓存的使用,并通过注解的方式让开发者能够轻松地为方法或类添加缓存功能。从Spring 3.1版本开始,Spring Cache提供了对缓存的支持。

Spring Cache不是一个具体的缓存实现方案,而是一个对缓存使用的抽象。这意味着开发者可以在不改变既有代码逻辑的情况下,通过添加少量的注解来实现缓存功能。Spring Cache支持多种主流的缓存解决方案,如EhCache、OSCache等,同时也提供了开箱即用的缓存临时存储方案。

Spring Cache的主要功能包括:

  1. 缓存注解:Spring Cache提供了一系列注解,如@Cacheable@CachePut@CacheEvict等,用于标记需要缓存的方法或类。这些注解可以方便地控制缓存的行为,如缓存的存储、更新和移除等。
  2. 缓存管理器:Spring Cache通过CacheManager接口来管理缓存。开发者可以根据需要自定义CacheManager,或者使用Spring Cache提供的默认实现。
  3. 缓存策略:Spring Cache支持多种缓存策略,如基于方法的返回值、基于方法的参数等。同时,开发者还可以使用SpEL(Spring Expression Language)来定义缓存的key和各种条件。

总之,Spring Cache是一个强大而灵活的缓存抽象,它可以帮助开发者轻松地实现高性能的缓存功能,提高应用程序的性能和响应速度。

2.加入依赖

  1. <!--redis-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-data-redis</artifactId>
  5. </dependency>
  6. <!--Spring Cache-->
  7. <dependency>
  8. <groupId>org.springframework.boot</groupId>
  9. <artifactId>spring-boot-starter-cache</artifactId>
  10. </dependency>

3.设置application.properties

  1. #毫秒为单位
  2. spring.cache.type=redis
  3. spring.cache.redis.time-to-live=3600000
  4. #如果指定了前缀就用我们指定的前缀,如果没有就默认使用缓存的名字作为前缀
  5. spring.cache.redis.key-prefix=CACHE_
  6. spring.cache.redis.use-key-prefix=true
  7. #是否缓存空值。防止缓存穿透
  8. spring.cache.redis.cache-null-values=true

 4.自定义缓存配置类,将redis缓存数据的格式修改为JSON格式,使用 @EnableCaching 注解来开启缓存支持

  1. package com.company.project.configurer;
  2. import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
  3. import org.springframework.boot.autoconfigure.cache.CacheProperties;
  4. import org.springframework.cache.annotation.EnableCaching;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  8. import org.springframework.data.redis.serializer.RedisSerializationContext;
  9. import org.springframework.data.redis.serializer.StringRedisSerializer;
  10. @Configuration
  11. @EnableCaching
  12. public class MyCacheConfig{
  13. @Bean
  14. RedisCacheConfiguration redisCacheConfiguration(CacheProperties cacheProperties){
  15. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
  16. // config =config.entryTtl();
  17. config = config.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()));
  18. config = config.serializeValuesWith(RedisSerializationContext .SerializationPair.fromSerializer(new GenericFastJsonRedisSerializer()));
  19. CacheProperties.Redis redisProperties = cacheProperties.getRedis();//将配,置文件中的所有配置都生效
  20. if (redisProperties.getTimeToLive() != null) {
  21. config = config.entryTtl(redisProperties.getTimeToLive());
  22. }
  23. if (redisProperties.getKeyPrefix() != null) {
  24. config = config.prefixCacheNameWith(redisProperties.getKeyPrefix());
  25. }
  26. if (!redisProperties.isCacheNullValues()) {
  27. config = config.disableCachingNullValues();
  28. }
  29. if (!redisProperties.isUseKeyPrefix()) {
  30. config = config.disableKeyPrefix();
  31. }
  32. return config;
  33. }
  34. }

 5.在需要缓存的方法上使用 Spring Cache 的注解,如 @Cacheable@CachePut 和 @CacheEvict

6.测试:查看效果

7.出现的异常,不加缓存配置类时,也就是使用默认的缓存配置类,这是对应的返回值要实现Serializable。

从错误日志中,我们可以看到问题出在尝试从Redis中反序列化数据时。具体地说,问题出现在尝试将存储的值(在这种情况下是200)解析为com.company.project.core.ResultCode枚举类型时。Fastjson库抛出了一个JSONException,说明它无法将值"200"解析为该枚举类型。

ResultCode枚举类型可能定义了一些特定的枚举值,而"200"可能不是这些值中的一个。这通常是因为枚举值和存储的值不匹配导致的。

  1. 2024-02-29 09:15:44.865 ERROR 16264 --- [io-15510-exec-1] c.c.project.configurer.WebMvcConfigurer : 接口 [/record/list] 出现异常,方法:com.company.project.web.RecordController$$EnhancerBySpringCGLIB$$6c0c2d4.list,异常摘要:Could not deserialize: parse enum com.company.project.core.ResultCode error, value : 200; nested exception is com.alibaba.fastjson.JSONException: parse enum com.company.project.core.ResultCode error, value : 200
  2. org.springframework.data.redis.serializer.SerializationException: Could not deserialize: parse enum com.company.project.core.ResultCode error, value : 200; nested exception is com.alibaba.fastjson.JSONException: parse enum com.company.project.core.ResultCode error, value : 200
  3. at com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer.deserialize(GenericFastJsonRedisSerializer.java:37)
  4. at org.springframework.data.redis.serializer.DefaultRedisElementReader.read(DefaultRedisElementReader.java:48)
  5. at org.springframework.data.redis.serializer.RedisSerializationContext$SerializationPair.read(RedisSerializationContext.java:272)
  6. at org.springframework.data.redis.cache.RedisCache.deserializeCacheValue(RedisCache.java:260)
  7. at org.springframework.data.redis.cache.RedisCache.lookup(RedisCache.java:94)
  8. at org.springframework.cache.support.AbstractValueAdaptingCache.get(AbstractValueAdaptingCache.java:58)
  9. at org.springframework.cache.interceptor.AbstractCacheInvoker.doGet(AbstractCacheInvoker.java:73)
  10. at org.springframework.cache.interceptor.CacheAspectSupport.findInCaches(CacheAspectSupport.java:571)
  11. at org.springframework.cache.interceptor.CacheAspectSupport.findCachedItem(CacheAspectSupport.java:536)
  12. at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:402)
  13. at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:346)
  14. at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:61)
  15. at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186)
  16. at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.proceed(CglibAopProxy.java:749)
  17. at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:691)
  18. at com.company.project.web.RecordController$$EnhancerBySpringCGLIB$$6c0c2d4.list(<generated>)
  19. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  20. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  21. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  22. at java.lang.reflect.Method.invoke(Method.java:498)
  23. at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190)
  24. at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138)
  25. at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:105)
  26. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:878)
  27. at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:792)
  28. at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
  29. at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
  30. at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
  31. at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
  32. at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
  33. at javax.servlet.http.HttpServlet.service(HttpServlet.java:652)
  34. at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
  35. at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
  36. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
  37. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  38. at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
  39. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  40. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  41. at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
  42. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  43. at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
  44. at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
  45. at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
  46. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  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:201)
  50. at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
  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:97)
  55. at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
  56. at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
  57. at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
  58. at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
  59. at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
  60. at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
  61. at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
  62. at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
  63. at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
  64. at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
  65. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
  66. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
  67. at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
  68. at java.lang.Thread.run(Thread.java:748)
  69. Caused by: com.alibaba.fastjson.JSONException: parse enum com.company.project.core.ResultCode error, value : 200
  70. at com.alibaba.fastjson.parser.deserializer.EnumDeserializer.deserialze(EnumDeserializer.java:125)
  71. at com.alibaba.fastjson.parser.deserializer.DefaultFieldDeserializer.parseField(DefaultFieldDeserializer.java:85)
  72. at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.parseField(JavaBeanDeserializer.java:1251)
  73. at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:866)
  74. at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:288)
  75. at com.alibaba.fastjson.parser.deserializer.JavaBeanDeserializer.deserialze(JavaBeanDeserializer.java:284)
  76. at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:395)
  77. at com.alibaba.fastjson.parser.DefaultJSONParser.parse(DefaultJSONParser.java:1401)
  78. at com.alibaba.fastjson.parser.deserializer.JavaObjectDeserializer.deserialze(JavaObjectDeserializer.java:46)
  79. at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:688)
  80. at com.alibaba.fastjson.JSON.parseObject(JSON.java:396)
  81. at com.alibaba.fastjson.JSON.parseObject(JSON.java:359)
  82. at com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer.deserialize(GenericFastJsonRedisSerializer.java:35)
  83. ... 65 common frames omitted

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

闽ICP备14008679号