SpringBoot中整合Redis

将用户频繁访问的内容存放在离用户最近,访问速度最快的地方,提高用户的响应速度,今天先来讲下在springboot中整合redis的详细步骤。

1.安装步骤

安装步骤地址
如果通过wget获取不下来我们可以去redis官网上面下载源码,然后解压安装

2.整合到SpringBoot中去

1.首先新建一个SpringBoot工程,打开application.yml文件,在里面加入以下内容,没有application.yml的可以在resource目录下新建一个该文件,或者改用application.properties文件格式,个人喜欢yml格式

spring:##默认密码为空redis:#主机iphost: 127.0.0.1# Redis服务器连接端口port: 6379jedis:pool:#连接池最大连接数(使用负值表示没有限制)max-active: 100# 连接池中的最小空闲连接max-idle: 10# 连接池最大阻塞等待时间(使用负值表示没有限制)max-wait: 100000# 连接超时时间(毫秒)timeout: 5000#默认是索引为0的数据库database: 15


2.添加依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--SpringBoot和redis的整合starter--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--很好用的一个自动生成getter,setter方法的idea插件--><!-- https://mvnrepository.com/artifact/org.projectlombok/lombok --><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><version>1.18.8</version><scope>provided</scope></dependency><!--因为我们序列化的方式为fastjson,所以引入一下包--><!-- https://mvnrepository.com/artifact/com.alibaba/fastjson --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>

3.编写redis配置类,当然网上的redis配置序列化方式很多种,而我采用以下这种

package com.kanavi.bootredis.config;import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;/*** redis配置类*/
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisConfig {/*** @Date: 2020/4/26 0026* @Author: thl* @Description: 使用fastjson序列化* @Param: [redisConnectionFactory]* @Return: org.springframework.data.redis.core.RedisTemplate<java.lang.Object,java.lang.Object>*/@Bean@ConditionalOnMissingBean(name = "redisTemplate")public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {RedisTemplate<Object, Object> template = new RedisTemplate<>();//使用fastjson序列化FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(Object.class);// value值的序列化采用fastJsonRedisSerializertemplate.setValueSerializer(fastJsonRedisSerializer);template.setHashValueSerializer(fastJsonRedisSerializer);// key的序列化采用StringRedisSerializertemplate.setKeySerializer(new StringRedisSerializer());template.setHashKeySerializer(new StringRedisSerializer());template.setConnectionFactory(redisConnectionFactory);return template;}/*** @Date: 2020/4/26 0026* @Author: thl* @Description: 用字符串序列化* @Param: [redisConnectionFactory]* @Return: org.springframework.data.redis.core.StringRedisTemplate*/@Bean@ConditionalOnMissingBean(StringRedisTemplate.class)public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) {StringRedisTemplate template = new StringRedisTemplate();template.setConnectionFactory(redisConnectionFactory);return template;}}

4.引入一个RedisUtil类

package com.kanavi.bootredis.utils;import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** redis工具类*/
@Component
public final class RedisUtil{@Resourceprivate RedisTemplate<String, Object> redisTemplate;public Set<String> keys(String keys,String name){try {return redisTemplate.keys(keys);}catch (Exception e){e.printStackTrace();return null;}}/*** 指定缓存失效时间* @param key 键* @param time 时间(秒)* @return*/public boolean expire(String key, long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据key 获取过期时间* @param key 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/*** 判断key是否存在* @param key 键* @return true 存在 false不存在*/public boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除缓存* @param key 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(CollectionUtils.arrayToList(key));}}}/*** 普通缓存获取* @param key 键* @return 值*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 普通缓存放入* @param key 键* @param value 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入, 不存在放入,存在返回* @param key 键* @param value 值* @return true成功 false失败*/public boolean setnx(String key, Object value) {try {redisTemplate.opsForValue().setIfAbsent(key,value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间* @param key 键* @param value 值* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间,不存在放入,存在返回* @param key 键* @param value 值* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean setnx(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().setIfAbsent(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 递增* @param key 键* @param delta 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减* @param key 键* @param delta 要减少几(小于0)* @return*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}/*** HashGet* @param key 键 不能为null* @param item 项 不能为null* @return 值*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 获取hashKey对应的所有键值* @param key 键* @return 对应的多个键值*/public Map<Object, Object> hmget(String key) {return redisTemplate.opsForHash().entries(key);}/*** HashSet* @param key 键* @param map 对应多个键值* @return true 成功 false 失败*/public boolean hmset(String key, Map<String, Object> map) {try {redisTemplate.opsForHash().putAll(key, map);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** HashSet 并设置时间* @param key 键* @param map 对应多个键值* @param time 时间(秒)* @return true成功 false失败*/public boolean hmset(String key, Map<String, Object> map, long time) {try {redisTemplate.opsForHash().putAll(key, map);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建* @param key 键* @param item 项* @param value 值* @return true 成功 false失败*/public boolean hset(String key, String item, Object value) {try {redisTemplate.opsForHash().put(key, item, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 向一张hash表中放入数据,如果不存在将创建* @param key 键* @param item 项* @param value 值* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间* @return true 成功 false失败*/public boolean hset(String key, String item, Object value, long time) {try {redisTemplate.opsForHash().put(key, item, value);if (time > 0) {expire(key, time);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除hash表中的值* @param key 键 不能为null* @param item 项 可以使多个 不能为null*/public void hdel(String key, Object... item) {redisTemplate.opsForHash().delete(key, item);}/*** 判断hash表中是否有该项的值* @param key 键 不能为null* @param item 项 不能为null* @return true 存在 false不存在*/public boolean hHasKey(String key, String item) {return redisTemplate.opsForHash().hasKey(key, item);}/*** hash递增 如果不存在,就会创建一个 并把新增后的值返回* @param key 键* @param item 项* @param by 要增加几(大于0)* @return*/public double hincr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, by);}/*** hash递减* @param key 键* @param item 项* @param by 要减少记(小于0)* @return*/public double hdecr(String key, String item, double by) {return redisTemplate.opsForHash().increment(key, item, -by);}/*** 根据key获取Set中的所有值* @param key 键* @return*/public Set<Object> sGet(String key) {try {return redisTemplate.opsForSet().members(key);} catch (Exception e) {e.printStackTrace();return null;}}/*** 根据value从一个set中查询,是否存在* @param key 键* @param value 值* @return true 存在 false不存在*/public boolean sHasKey(String key, Object value) {try {return redisTemplate.opsForSet().isMember(key, value);} catch (Exception e) {e.printStackTrace();return false;}}/*** 将数据放入set缓存* @param key 键* @param values 值 可以是多个* @return 成功个数*/public long sSet(String key, Object... values) {try {return redisTemplate.opsForSet().add(key, values);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 将set数据放入缓存* @param key 键* @param time 时间(秒)* @param values 值 可以是多个* @return 成功个数*/public long sSetAndTime(String key, long time, Object... values) {try {Long count = redisTemplate.opsForSet().add(key, values);if (time > 0)expire(key, time);return count;} catch (Exception e) {e.printStackTrace();return 0;}}/*** 获取set缓存的长度* @param key 键* @return*/public long sGetSetSize(String key) {try {return redisTemplate.opsForSet().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 移除值为value的* @param key 键* @param values 值 可以是多个* @return 移除的个数*/public long setRemove(String key, Object... values) {try {Long count = redisTemplate.opsForSet().remove(key, values);return count;} catch (Exception e) {e.printStackTrace();return 0;}}// ===============================list=================================/*** 获取list缓存的内容* @param key 键* @param start 开始* @param end 结束 0 到 -1代表所有值* @return*/public List<Object> lGet(String key, long start, long end) {try {return redisTemplate.opsForList().range(key, start, end);} catch (Exception e) {e.printStackTrace();return null;}}/*** 获取list缓存的长度* @param key 键* @return*/public long lGetListSize(String key) {try {return redisTemplate.opsForList().size(key);} catch (Exception e) {e.printStackTrace();return 0;}}/*** 通过索引 获取list中的值* @param key 键* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推* @return*/public Object lGetIndex(String key, long index) {try {return redisTemplate.opsForList().index(key, index);} catch (Exception e) {e.printStackTrace();return null;}}/*** 将list放入缓存* @param key 键* @param value 值* @return*/public boolean lSet(String key, Object value) {try {redisTemplate.opsForList().rightPush(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存* @param key 键* @param value 值* @param time 时间(秒)* @return*/public boolean lSet(String key, Object value, long time) {try {redisTemplate.opsForList().rightPush(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存* @param key 键* @param value 值* @return*/public boolean lSet(String key, List<Object> value) {try {redisTemplate.opsForList().rightPushAll(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 将list放入缓存** @param key 键* @param value 值* @param time 时间(秒)* @return*/public boolean lSet(String key, List<Object> value, long time) {try {redisTemplate.opsForList().rightPushAll(key, value);if (time > 0)expire(key, time);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据索引修改list中的某条数据* @param key 键* @param index 索引* @param value 值* @return*/public boolean lUpdateIndex(String key, long index, Object value) {try {redisTemplate.opsForList().set(key, index, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 移除N个值为value* @param key 键* @param count 移除多少个* @param value 值* @return 移除的个数*/public long lRemove(String key, long count, Object value) {try {Long remove = redisTemplate.opsForList().remove(key, count, value);return remove;} catch (Exception e) {e.printStackTrace();return 0;}}}

5.进入测试类测试,以下是SpringBoot2.2.6单元测试方式,对应版本测试方式可以自行寻找

package com.kanavi.bootredis;import com.kanavi.bootredis.entity.Days;
import com.kanavi.bootredis.utils.RedisUtil;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;@SpringBootTest
class BootredisApplicationTests {@Autowiredprivate RedisUtil redisUtil;@Testvoid contextLoads() {Days d=new Days();d.setDate("123");d.setDaysId("456");d.setItemNumber(123);d.setOpenId("dawda");d.setTitle("title");redisUtil.set("days",d);System.out.println(redisUtil.get("days"));}}



至此,我们的SpringBoot项目和redis就整合完成了

SpringBoot整合redis实现简单的操作demo相关推荐

  1. SpringBoot2.X 整合Redis实现简单缓存操作

    文章包含项目全部文件代码: pom文件 application.propertis 配置文件 SpringBoot启动类 Redis配置类 Controller测试类 一.pom文件 web依赖,非必 ...

  2. RedisTemplate操作redis五大类型用法详解(springboot整合redis版本)

    1.案例说明 springboot整合redis之后,提供了操作redis的简便方式 通过通用对象redisTemplate方式操作String,Hash,List,Set SortSet五大数据类型 ...

  3. 不要再找了,Java操作Redis、Spring整合Redis及SpringBoot整合Redis这里都有

    文章开始之前先抛出一个问题:Jedis.Lettuce.Redisson以及RedisTemplate几者之间有什么区别,又有什么联系? 如果你心中已经很清晰的有了答案,那么本文你可以很轻松的阅读过去 ...

  4. Docker 部署 SpringBoot 项目整合 Redis 镜像做访问计数Demo

    Docker 部署SpringBoot项目整合 Redis 镜像做访问计数Demo 最终效果如下 大概就几个步骤 1.安装 Docker CE 2.运行 Redis 镜像 3.Java 环境准备 4. ...

  5. springboot 整合minio client 简单使用 视频流展示demo

    springboot 整合minio client 简单使用 视频流展示demo 不好意思 本人没有强迫症 代码随便造 知识来源于百度,感谢百度合作伙伴以及各位网友demo的帮助 源码:https:/ ...

  6. springboot整合redis,推荐整合和使用案例(2021版)

    背景:手下新人在初次使用springboot整合redis,大部分人习惯从网上检索到一份配置,然后不知其所以然的复制粘贴到项目中,网上搜索到的配置良莠不齐但又万变不离其宗.由于springboot最大 ...

  7. Springboot整合redis实现缓存及其缓存运行原理浅析

    声明:小白,学习阶段,主要目的是为了记录学习过程,本文仅供参考,如有不足的地方欢迎指出讨论交流 本文基于Springboot2.1.3版本开发: 准备阶段 首先是pom.xml文件所需的依赖: < ...

  8. SpringBoot整合Redis缓存

    SpringBoot整合Redis缓存 一.缓存概念知识 1.是什么缓存 2.缓存的优缺点 3.为什么使用缓存 二.Redis概念知识 1.Redis简介 2.为什么用Redis作为缓存 3.Redi ...

  9. SpringBoot整合Redis+Redis缓存应用+Redis实现Session共享+...

    一.SpringBoot整合Redis 1.导入依赖 <!--存在Redis依赖--> <dependency><groupId>org.springframewo ...

最新文章

  1. 组合特征(一)tfidf(word+article)
  2. 技术人的不惑之路...... | 每日趣闻
  3. 树莓派python蓝牙_Fen9Pi-05.树莓派 UNO蓝牙通信
  4. python什么时候用类_python中什么时候使用自定义类
  5. 注意!!一定要谨慎使用c/c++原生指针
  6. sqlserver数据库大型应用解决方案总结 数据库负载均衡
  7. c语言高函数正确形式,计算机二级C语言考点解析:函数
  8. const参数,const返回值与const函数
  9. SPSS操作(四):系统聚类分析
  10. python实践项目(四)
  11. mac os maven_如何在Mac OS上安装Maven
  12. STM32F407 + Codec AK4556 + NAND Flash MX30LF2G 录音机实现
  13. CRM 实施计划和准备的8个步骤!
  14. 考研经验计算机信息技术,考研经验:失败者的4条血泪教训
  15. java文件一行一行读取_java一行一行写入或读取文件
  16. vmbox主机和虚拟机无法共通网络服务 主机无法使用虚拟机的网络服务 虚拟机无法使用主机的网络服务
  17. PyTorch实战使用Resnet迁移学习
  18. 计算机键盘的tab键是哪个,电脑键盘中的Tab键都有哪些妙用
  19. 如何创建PostgreSQL 生成列
  20. 服务器怎么修改内存大小,服务器怎么改内存大小

热门文章

  1. 魔方机器人02 使用opencv-python进行颜色识别及K-Means聚类算法
  2. rebar3使用介绍(七)测试
  3. html中常用的三种列表,在html语言中,常用的列表有哪三种
  4. 大咖|英特尔中国研究院院长宋继强:我们是如何与李宇春打造全球第一支三维人脸特效的音乐视频的
  5. 失败的过去式英文翻译_失败的英语怎么说
  6. java 只获取年月日_Java获取当前时间的年月日方法
  7. XBee模块数字和模拟采样详解
  8. 网络通信时字节序转换原理与网络字节序、大端和小端模式 .
  9. 信息化监理会走向何方?
  10. 一个非常好用的代码搜索引擎