场景

SpringBoot中操作spring redis的工具类:

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

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

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

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

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

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

        <!-- redis 缓存操作 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!-- 阿里JSON解析器 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.75</version></dependency>

注:

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

实现

1、新建Redis的配置类

package com.badao.demo.config;import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;/*** redis配置**/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{@Bean@SuppressWarnings(value = { "unchecked", "rawtypes" })@Primarypublic RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory){RedisTemplate<Object, Object> template = new RedisTemplate<>();template.setConnectionFactory(connectionFactory);FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);ObjectMapper mapper = new ObjectMapper();mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);serializer.setObjectMapper(mapper);template.setValueSerializer(serializer);// 使用StringRedisSerializer来序列化和反序列化redis的key值template.setKeySerializer(new StringRedisSerializer());template.afterPropertiesSet();return template;}
}

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

package com.badao.demo.config;import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;import java.nio.charset.Charset;/*** Redis使用FastJson序列化** @author ruoyi*/
public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T>
{@SuppressWarnings("unused")private ObjectMapper objectMapper = new ObjectMapper();public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");private Class<T> clazz;static{ParserConfig.getGlobalInstance().setAutoTypeSupport(true);}public FastJson2JsonRedisSerializer(Class<T> clazz){super();this.clazz = clazz;}@Overridepublic byte[] serialize(T t) throws SerializationException{if (t == null){return new byte[0];}return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);}@Overridepublic T deserialize(byte[] bytes) throws SerializationException{if (bytes == null || bytes.length <= 0){return null;}String str = new String(bytes, DEFAULT_CHARSET);return JSON.parseObject(str, clazz);}public void setObjectMapper(ObjectMapper objectMapper){Assert.notNull(objectMapper, "'objectMapper' must not be null");this.objectMapper = objectMapper;}protected JavaType getJavaType(Class<?> clazz){return TypeFactory.defaultInstance().constructType(clazz);}
}

3、新建redis的工具类

package com.badao.demo.utils;import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundSetOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;/*** spring redis 工具类***/
@SuppressWarnings(value = { "unchecked", "rawtypes" })
@Component
public class RedisCache
{@Autowiredpublic RedisTemplate redisTemplate;/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值* @return 缓存的对象*/public <T> ValueOperations<String, T> setCacheObject(String key, T value){ValueOperations<String, T> operation = redisTemplate.opsForValue();operation.set(key, value);return operation;}/*** 缓存基本的对象,Integer、String、实体类等** @param key 缓存的键值* @param value 缓存的值* @param timeout 时间* @param timeUnit 时间颗粒度* @return 缓存的对象*/public <T> ValueOperations<String, T> setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit){ValueOperations<String, T> operation = redisTemplate.opsForValue();operation.set(key, value, timeout, timeUnit);return operation;}/*** 获得缓存的基本对象。** @param key 缓存键值* @return 缓存键值对应的数据*/public <T> T getCacheObject(String key){ValueOperations<String, T> operation = redisTemplate.opsForValue();return operation.get(key);}/*** 删除单个对象** @param key*/public void deleteObject(String key){redisTemplate.delete(key);}/*** 删除集合对象** @param collection*/public void deleteObject(Collection collection){redisTemplate.delete(collection);}/*** 缓存List数据** @param key 缓存的键值* @param dataList 待缓存的List数据* @return 缓存的对象*/public <T> ListOperations<String, T> setCacheList(String key, List<T> dataList){ListOperations listOperation = redisTemplate.opsForList();if (null != dataList){int size = dataList.size();for (int i = 0; i < size; i++){listOperation.leftPush(key, dataList.get(i));}}return listOperation;}/*** 获得缓存的list对象** @param key 缓存的键值* @return 缓存键值对应的数据*/public <T> List<T> getCacheList(String key){List<T> dataList = new ArrayList<T>();ListOperations<String, T> listOperation = redisTemplate.opsForList();Long size = listOperation.size(key);for (int i = 0; i < size; i++){dataList.add(listOperation.index(key, i));}return dataList;}/*** 缓存Set** @param key 缓存键值* @param dataSet 缓存的数据* @return 缓存数据的对象*/public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet){BoundSetOperations<String, T> setOperation = redisTemplate.boundSetOps(key);Iterator<T> it = dataSet.iterator();while (it.hasNext()){setOperation.add(it.next());}return setOperation;}/*** 获得缓存的set** @param key* @return*/public <T> Set<T> getCacheSet(String key){Set<T> dataSet = new HashSet<T>();BoundSetOperations<String, T> operation = redisTemplate.boundSetOps(key);dataSet = operation.members();return dataSet;}/*** 缓存Map** @param key* @param dataMap* @return*/public <T> HashOperations<String, String, T> setCacheMap(String key, Map<String, T> dataMap){HashOperations hashOperations = redisTemplate.opsForHash();if (null != dataMap){for (Map.Entry<String, T> entry : dataMap.entrySet()){hashOperations.put(key, entry.getKey(), entry.getValue());}}return hashOperations;}/*** 获得缓存的Map** @param key* @return*/public <T> Map<String, T> getCacheMap(String key){Map<String, T> map = redisTemplate.opsForHash().entries(key);return map;}/*** 获得缓存的基本对象列表** @param pattern 字符串前缀* @return 对象列表*/public Collection<String> keys(String pattern){return redisTemplate.keys(pattern);}
}

4、存储数据测试

package com.badao.demo;import com.badao.demo.utils.RedisCache;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;import java.util.concurrent.TimeUnit;@SpringBootTest
class TcpdemoApplicationTests {@AutowiredRedisCache redisCache;@Testvoid test1() {redisCache.setCacheObject("bbb","222",10, TimeUnit.SECONDS);String aaa = redisCache.getCacheObject("bbb");System.out.println(aaa);}}

SpringBoot中集成Redis实现对redis中数据的解析和存储相关推荐

  1. maven mybatis mysql_Java Web学习系列——Maven Web项目中集成使用Spring、MyBatis实现对MySQL的数据访问...

    标签: 本篇内容还是建立在上一篇Java Web学习系列--Maven Web项目中集成使用Spring基础之上,对之前的Maven Web项目进行升级改造,实现对MySQL的数据访问. 添加依赖Ja ...

  2. 如何用程序实现对IE中scripts的控制(禁止和允许)

    如何用程序实现对IE中scripts的控制(禁止和允许) Delphi / Windows SDK/API http://www.delphi2007.net/DelphiAPI/html/delph ...

  3. 在MATLAB中采用M文件实现对Simulink中的S函数程序实现自动调参数

    在做研究的时候我们经常需要对模型的参数就行相应的选择,然而有没有觉得每次更改一个参数都需要运行一次仿真程序觉得很无聊呀,运行完程序还要看效果怎么样,然后再根据效果来调整参数,再次运行程序,如此反复. ...

  4. python中load_iris_在python中利用KNN实现对iris进行分类的方法

    如下所示: from sklearn.datasets import load_iris iris = load_iris() print iris.data.shape from sklearn.c ...

  5. SpringBoot通过WorkBook快速实现对Excel的导入和导出(包括数据校验)

    之前转载过一篇对Excel基本操作相关的文章,这篇文章的浏览量迅速飙升,以至于在我博客的热门文章中排到了第三的位置,不过那篇转载的文章实用性差并且讲解不是很清晰,所以打算趁着今天休息,写一篇关于Spr ...

  6. springboot项目集成dolphinscheduler调度器 实现datax数据同步任务

    Datax安装及基本使用请查看上一篇文章: 文章目录 Datax概述 1.概述 2.功能清单 3.==说明==:本项目只支持mysql及hbase之间的数据同步 代码模块 配置文件 pom.xml D ...

  7. 使用underscore模块的template功能实现对HTML的数据注入+template实现数据注入(后面更新)

    使用underscore模块的template功能实现对HTML的数据注入 安装underscore 代码是:npm i underscore 查看是否安装成功 server.js文件 var htt ...

  8. byte数组添加数据_C#基于S7协议实现对PLC中DB块字节数据的获取及自定义textbox实现数据解析...

    实现思路 C#通过sharp7.cs 读取DB块中的数据.(这里是字节数组). 然后对字节数据进行解析,并绑定在textbox控件中进行显示. 需求 1-基于Sharp7.cs二次编写的访问PLC类. ...

  9. 实现对ListView中的条目进行排序

    1.对ListView中的条目进行排序我的思路就是在我们队ListView进行设置Adapter的时候就先对List中的数据进行排序,对List进行排序就可以通过 Collections.sort() ...

最新文章

  1. ubuntu 下利用ndiswrapper安装无线网卡驱动
  2. Objective-C:MRC(引用计数器)获得对象所有权的方式(init、retain、copy等)
  3. Py之Seaborn:数据可视化Seaborn库的柱状图、箱线图(置信区间图)、散点图/折线图、核密度图/等高线图、盒形图/小提琴图/LV多框图的组合图/矩阵图实现
  4. 计算机图形软件---OpenGL简介
  5. 工业4.0提出者孔翰宁详解工业4.0
  6. GO国内镜像加速模块下载
  7. python技术文档_Python技术文档最佳实践
  8. lisp医院化验系统_浅谈医院化验室信息系统(LIS)的建设
  9. POJ3264——Balanced Lineup(线段树)
  10. 用SegNet进行室内布局语义分割
  11. 根据需求进行批量新增
  12. APM32 系列 MCU 获得 IAR Embedded Workbench 和 SEGGER J-Link Debug Probes 的全面支持
  13. openjudge 1.9.14 铺地毯
  14. 启动RocketMQ报错:Please set the JAVA_HOME variable in your environment, We need java 64
  15. 高等数学(第七版)同济大学 习题11-2 个人解答
  16. Android GNSS 模块分析(四)HAL 层
  17. 全球IT服务“十分天下有其一”,中软国际的底气来自何方?
  18. MyBatis从入门到精通__刘增辉(著)_ 电子工业出版社PDF下载
  19. Spring框架之AOP详解(带实战详细步骤)
  20. 数据分析案例——客户流失分析与预测

热门文章

  1. 通过配置光猫路由器实现家用主机远程桌面连接
  2. Vue联动下拉框默认选中
  3. C语言中pthread或Windows API在多线程编程中的基本应用
  4. ffmpeg 命令行总结
  5. Manjaro 安装MySQL
  6. 利用Vultr主机安转宝塔Web面板搭建wordpress博客建站教程
  7. 精准医学中的深度学习和影像组学
  8. STM32_3 时钟初始化分析
  9. Dubbo远程传输协议详解
  10. oracle12c ora 12560,12C安装历险记----ORA-12560和ORA-12537的解决方案