当前位置:   article > 正文

SpringBoot中集成Redis实现对redis中数据的解析和存储_springboot cache redis json 存储

springboot cache redis json 存储

场景

SpringBoot中操作spring redis的工具类:

SpringBoot中操作spring redis的工具类_霸道流氓气质的博客-CSDN博客

上面讲的操作redis的工具类,但是对于redis的集成并没做细讲。

下面参考若依框架的实现,从中抽离出集成redis的部分实现。

若依前后端分离版本地搭建开发环境并运行项目的教程:

若依前后端分离版手把手教你本地搭建环境并运行项目_霸道流氓气质的博客-CSDN博客

新建SpringBoot项目之后,添加redsi以及fastjson的相关依赖

  1.         <!-- redis 缓存操作 -->
  2.         <dependency>
  3.             <groupId>org.springframework.boot</groupId>
  4.             <artifactId>spring-boot-starter-data-redis</artifactId>
  5.         </dependency>
  6.         <!-- 阿里JSON解析器 -->
  7.         <dependency>
  8.             <groupId>com.alibaba</groupId>
  9.             <artifactId>fastjson</artifactId>
  10.             <version>1.2.75</version>
  11.         </dependency>

注:

博客:
霸道流氓气质的博客_CSDN博客-C#,架构之路,SpringBoot领域博主

实现

1、新建Redis的配置类

  1. package com.badao.demo.config;
  2. import org.springframework.cache.annotation.CachingConfigurerSupport;
  3. import org.springframework.cache.annotation.EnableCaching;
  4. import org.springframework.context.annotation.Bean;
  5. import org.springframework.context.annotation.Configuration;
  6. import org.springframework.context.annotation.Primary;
  7. import org.springframework.data.redis.connection.RedisConnectionFactory;
  8. import org.springframework.data.redis.core.RedisTemplate;
  9. import org.springframework.data.redis.serializer.StringRedisSerializer;
  10. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  11. import com.fasterxml.jackson.annotation.JsonTypeInfo;
  12. import com.fasterxml.jackson.annotation.PropertyAccessor;
  13. import com.fasterxml.jackson.databind.ObjectMapper;
  14. import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
  15. /**
  16.  * redis配置
  17.  *
  18.  */
  19. @Configuration
  20. @EnableCaching
  21. public class RedisConfig extends CachingConfigurerSupport
  22. {
  23.     @Bean
  24.     @SuppressWarnings(value = { "unchecked", "rawtypes" })
  25.     @Primary
  26.     public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
  27.     {
  28.         RedisTemplate<Object, Object> template = new RedisTemplate<>();
  29.         template.setConnectionFactory(connectionFactory);
  30.         FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
  31.         ObjectMapper mapper = new ObjectMapper();
  32.         mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  33.         mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
  34.         serializer.setObjectMapper(mapper);
  35.         template.setValueSerializer(serializer);
  36.         // 使用StringRedisSerializer来序列化和反序列化redis的key
  37.         template.setKeySerializer(new StringRedisSerializer());
  38.         template.afterPropertiesSet();
  39.         return template;
  40.     }
  41. }

2、新建Redis使用FastJson序列化的工具类

  1. package com.badao.demo.config;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.parser.ParserConfig;
  4. import com.alibaba.fastjson.serializer.SerializerFeature;
  5. import com.fasterxml.jackson.databind.JavaType;
  6. import com.fasterxml.jackson.databind.ObjectMapper;
  7. import com.fasterxml.jackson.databind.type.TypeFactory;
  8. import org.springframework.data.redis.serializer.RedisSerializer;
  9. import org.springframework.data.redis.serializer.SerializationException;
  10. import org.springframework.util.Assert;
  11. import java.nio.charset.Charset;
  12. /**
  13.  * Redis使用FastJson序列化
  14.  *
  15.  * @author ruoyi
  16.  */
  17. public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
  18. {
  19.     @SuppressWarnings("unused")
  20.     private ObjectMapper objectMapper = new ObjectMapper();
  21.     public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
  22.     private Class<T> clazz;
  23.     static
  24.     {
  25.         ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
  26.     }
  27.     public FastJson2JsonRedisSerializer(Class<T> clazz)
  28.     {
  29.         super();
  30.         this.clazz = clazz;
  31.     }
  32.     @Override
  33.     public byte[] serialize(T t) throws SerializationException
  34.     {
  35.         if (t == null)
  36.         {
  37.             return new byte[0];
  38.         }
  39.         return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
  40.     }
  41.     @Override
  42.     public T deserialize(byte[] bytes) throws SerializationException
  43.     {
  44.         if (bytes == null || bytes.length <= 0)
  45.         {
  46.             return null;
  47.         }
  48.         String str = new String(bytes, DEFAULT_CHARSET);
  49.         return JSON.parseObject(str, clazz);
  50.     }
  51.     public void setObjectMapper(ObjectMapper objectMapper)
  52.     {
  53.         Assert.notNull(objectMapper, "'objectMapper' must not be null");
  54.         this.objectMapper = objectMapper;
  55.     }
  56.     protected JavaType getJavaType(Class<?> clazz)
  57.     {
  58.         return TypeFactory.defaultInstance().constructType(clazz);
  59.     }
  60. }

3、新建redis的工具类

  1. package com.badao.demo.utils;
  2. import java.util.ArrayList;
  3. import java.util.Collection;
  4. import java.util.HashSet;
  5. import java.util.Iterator;
  6. import java.util.List;
  7. import java.util.Map;
  8. import java.util.Set;
  9. import java.util.concurrent.TimeUnit;
  10. import org.springframework.beans.factory.annotation.Autowired;
  11. import org.springframework.data.redis.core.BoundSetOperations;
  12. import org.springframework.data.redis.core.HashOperations;
  13. import org.springframework.data.redis.core.ListOperations;
  14. import org.springframework.data.redis.core.RedisTemplate;
  15. import org.springframework.data.redis.core.ValueOperations;
  16. import org.springframework.stereotype.Component;
  17. /**
  18.  * spring redis 工具类
  19.  *
  20.  **/
  21. @SuppressWarnings(value = { "unchecked", "rawtypes" })
  22. @Component
  23. public class RedisCache
  24. {
  25.     @Autowired
  26.     public RedisTemplate redisTemplate;
  27.     /**
  28.      * 缓存基本的对象,Integer、String、实体类等
  29.      *
  30.      * @param key 缓存的键值
  31.      * @param value 缓存的值
  32.      * @return 缓存的对象
  33.      */
  34.     public <T> ValueOperations<String, T> setCacheObject(String key, T value)
  35.     {
  36.         ValueOperations<String, T> operation = redisTemplate.opsForValue();
  37.         operation.set(key, value);
  38.         return operation;
  39.     }
  40.     /**
  41.      * 缓存基本的对象,Integer、String、实体类等
  42.      *
  43.      * @param key 缓存的键值
  44.      * @param value 缓存的值
  45.      * @param timeout 时间
  46.      * @param timeUnit 时间颗粒度
  47.      * @return 缓存的对象
  48.      */
  49.     public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit)
  50.     {
  51.         ValueOperations<String, T> operation = redisTemplate.opsForValue();
  52.         operation.set(key, value, timeout, timeUnit);
  53.         return operation;
  54.     }
  55.     /**
  56.      * 获得缓存的基本对象。
  57.      *
  58.      * @param key 缓存键值
  59.      * @return 缓存键值对应的数据
  60.      */
  61.     public <T> T getCacheObject(String key)
  62.     {
  63.         ValueOperations<String, T> operation = redisTemplate.opsForValue();
  64.         return operation.get(key);
  65.     }
  66.     /**
  67.      * 删除单个对象
  68.      *
  69.      * @param key
  70.      */
  71.     public void deleteObject(String key)
  72.     {
  73.         redisTemplate.delete(key);
  74.     }
  75.     /**
  76.      * 删除集合对象
  77.      *
  78.      * @param collection
  79.      */
  80.     public void deleteObject(Collection collection)
  81.     {
  82.         redisTemplate.delete(collection);
  83.     }
  84.     /**
  85.      * 缓存List数据
  86.      *
  87.      * @param key 缓存的键值
  88.      * @param dataList 待缓存的List数据
  89.      * @return 缓存的对象
  90.      */
  91.     public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList)
  92.     {
  93.         ListOperations listOperation = redisTemplate.opsForList();
  94.         if (null != dataList)
  95.         {
  96.             int size = dataList.size();
  97.             for (int i = 0; i < size; i++)
  98.             {
  99.                 listOperation.leftPush(key, dataList.get(i));
  100.             }
  101.         }
  102.         return listOperation;
  103.     }
  104.     /**
  105.      * 获得缓存的list对象
  106.      *
  107.      * @param key 缓存的键值
  108.      * @return 缓存键值对应的数据
  109.      */
  110.     public <T> List<T> getCacheList(String key)
  111.     {
  112.         List<T> dataList = new ArrayList<T>();
  113.         ListOperations<String, T> listOperation = redisTemplate.opsForList();
  114.         Long size = listOperation.size(key);
  115.         for (int i = 0; i < size; i++)
  116.         {
  117.             dataList.add(listOperation.index(key, i));
  118.         }
  119.         return dataList;
  120.     }
  121.     /**
  122.      * 缓存Set
  123.      *
  124.      * @param key 缓存键值
  125.      * @param dataSet 缓存的数据
  126.      * @return 缓存数据的对象
  127.      */
  128.     public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet)
  129.     {
  130.         BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);
  131.         Iterator<T> it = dataSet.iterator();
  132.         while (it.hasNext())
  133.         {
  134.             setOperation.add(it.next());
  135.         }
  136.         return setOperation;
  137.     }
  138.     /**
  139.      * 获得缓存的set
  140.      *
  141.      * @param key
  142.      * @return
  143.      */
  144.     public <T> Set<T> getCacheSet(String key)
  145.     {
  146.         Set<T> dataSet = new HashSet<T>();
  147.         BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);
  148.         dataSet = operation.members();
  149.         return dataSet;
  150.     }
  151.     /**
  152.      * 缓存Map
  153.      *
  154.      * @param key
  155.      * @param dataMap
  156.      * @return
  157.      */
  158.     public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap)
  159.     {
  160.         HashOperations hashOperations = redisTemplate.opsForHash();
  161.         if (null != dataMap)
  162.         {
  163.             for (Map.Entry<String, T> entry : dataMap.entrySet())
  164.             {
  165.                 hashOperations.put(key, entry.getKey(), entry.getValue());
  166.             }
  167.         }
  168.         return hashOperations;
  169.     }
  170.     /**
  171.      * 获得缓存的Map
  172.      *
  173.      * @param key
  174.      * @return
  175.      */
  176.     public <T> Map<String, T> getCacheMap(String key)
  177.     {
  178.         Map<String, T> map = redisTemplate.opsForHash().entries(key);
  179.         return map;
  180.     }
  181.     /**
  182.      * 获得缓存的基本对象列表
  183.      *
  184.      * @param pattern 字符串前缀
  185.      * @return 对象列表
  186.      */
  187.     public Collection<String> keys(String pattern)
  188.     {
  189.         return redisTemplate.keys(pattern);
  190.     }
  191. }

4、存储数据测试

  1. package com.badao.demo;
  2. import com.badao.demo.utils.RedisCache;
  3. import org.junit.jupiter.api.Test;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import java.util.concurrent.TimeUnit;
  7. @SpringBootTest
  8. class TcpdemoApplicationTests {
  9.     @Autowired
  10.     RedisCache redisCache;
  11.     @Test
  12.     void test1() {
  13.         redisCache.setCacheObject("bbb","222",10, TimeUnit.SECONDS);
  14.         String aaa = redisCache.getCacheObject("bbb");
  15.         System.out.println(aaa);
  16.     }
  17. }

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

闽ICP备14008679号