特别说明:本文针对的是新版 spring boot 2.1.3,其 spring data 依赖为 spring-boot-starter-data-redis,且其默认连接池为 lettuce

​  redis 作为一个高性能的内存数据库,如果不会用就太落伍了,之前在 node.js 中用过 redis,本篇记录如何将 redis 集成到 spring boot 中。提供 redis 操作类,和注解使用 redis 两种方式。主要内容如下:

  • docker 安装 redis
  • springboot 集成 redis
  • 编写 redis 操作类
  • 通过注解使用 redis

安装 redis

  通过 docker 安装,docker compose 编排文件如下:

# docker-compose.yml
version: "2"
services:
  redis:
    container_name: redis
    image: redis:3.2.10
    ports:
      - "6379:6379"
复制代码

  然后在docker-compose.yml所在目录使用docker-compose up -d命令,启动 redis。

集成 springboot

  说明:springboot 版本为 2.1.3

添加 maven 依赖

  只需添加spring-boot-starter-data-redis依赖即可,并排除 lettuce 依赖,然后引入 jedis 和 jedis 的依赖 commons-pool2

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId><exclusions><exclusion><groupId>io.lettuce</groupId><artifactId>lettuce-core</artifactId></exclusion></exclusions>
</dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId>
</dependency><dependency><groupId>redis.clients</groupId><artifactId>jedis</artifactId>
</dependency>
复制代码

编写 springboot 配置文件

  配置文件如下:

server:
  port: 8081
  servlet:
    context-path: /sso
spring:
  application:
    name: SSO
  cache:
    type: redis
  redis:
    database: 0
    host: 192.168.226.5
    port: 6379# 有密码填密码,没有密码不填
    password:# 连接超时时间(ms)
    timeout: 1000ms# 高版本springboot中使用jedis或者lettuce
    jedis:
      pool:# 连接池最大连接数(负值表示无限制)
        max-active: 8# 连接池最大阻塞等待时间(负值无限制)
        max-wait: 5000ms# 最大空闲链接数
        max-idle: 8# 最小空闲链接数
        min-idle: 0
复制代码

编写配置类

  配置类代码如下:

@EnableCaching//开启缓存
@Configuration
public class RedisConfig extends CachingConfigurerSupport {/*** 设置缓存管理器,这里可以配置默认过期时间等** @param connectionFactory 连接池* @return*/@Beanpublic CacheManager cacheManager(RedisConnectionFactory connectionFactory) {RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofSeconds(60));//注意:请勿使用先new 配置对象,然后在调用entryTtl方法的方式来操作//会导致配置不生效,原因是调用.entryTtl方法会返回一个新的配置对象,而不是在原来的配置对象上修改RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);RedisCacheManager manager = new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);return manager;}@SuppressWarnings("all")@Beanpublic RedisTemplate<String, String> redisTemplate(JedisConnectionFactory factory) {StringRedisTemplate template = new StringRedisTemplate(factory);Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);jackson2JsonRedisSerializer.setObjectMapper(om);RedisSerializer stringSerializer = new StringRedisSerializer();template.setKeySerializer(stringSerializer);template.setValueSerializer(jackson2JsonRedisSerializer);template.setHashKeySerializer(stringSerializer);template.setHashValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();return template;}//使用jedis连接池建立jedis连接工厂@Beanpublic JedisConnectionFactory jedisConnectionFactory() {logger.info("jedisConnectionFactory:初始化了");JedisPoolConfig config = new JedisPoolConfig();config.setMaxIdle(maxIdle);config.setMinIdle(minIdle);config.setMaxWaitMillis(maxWaitMillis);config.setMaxTotal(maxActive);//链接耗尽时是否阻塞,默认trueconfig.setBlockWhenExhausted(true);//是否启用pool的jmx管理功能,默认trueconfig.setJmxEnabled(true);JedisConnectionFactory factory = new JedisConnectionFactory();factory.setPoolConfig(config);factory.setHostName(host);factory.setPort(port);factory.setPassword(password);factory.setDatabase(database);factory.setTimeout(timeout);return factory;}
}
复制代码

使用方法

  有两种方法来进行缓存操作,一种是在方法上添加缓存注解实现各种操作,一种是手动控制。个人比较喜欢手动控制,觉得这样都在自己的掌控中。

通过注解使用

  主要有以下 5 个注解:

  • @CacheConfig: 类级别缓存,设置缓存 key 前缀之类的
  • @Cacheable: 触发缓存入口
  • @CacheEvict: 触发移除缓存
  • @CachePut: 更新缓存
  • @Caching: 组合缓存

@CacheConfig

  该注解可以将缓存分类,它是类级别注解,主要用于给某个类的缓存全局配置,例子如下:

@CacheConfig(cacheNames = "redis_test")
@Service
public class RedisService {//....
}
复制代码

上面 CacheConfig 会给类下通过注解生成的 key 加上 redis_test 的前缀。

@Cacheable

  方法级别注解,根据 key 查询缓存:

  • 如果 key 不存在,将方法返回值缓存到 redis 中
  • 如果 key 存在,直接从缓存中取值 例子如下:
    /*** 缓存时间,首次查询后会缓存结果,key中的值可使用表达式计算.* 如不提供key,将使用默认key构造方法生成一个key* @return long*/@Cacheable(key = "'currentTime'")public long getTime() {return System.currentTimeMillis();}
复制代码

多次调用此段代码会发现每次返回的值都是一样的。

CachePut

  用于更新缓存,每次调用都会想 db 请求,缓存数据

  • 如果 key 存在,更新内容
  • 如果 key 不存在,插入内容

代码如下:

/*** 一般用于更新查插入操作,每次都会请求db*/@CachePut(key = "'currentTime'+#id")public long updateTime(String id) {return System.currentTimeMillis();}
复制代码

每次调用此方法都会根据 key 刷新 redis 中的缓存数据。

@CacheEvict

  根据 key 删除缓存中的数据。allEntries=true 表示删除缓存中所有数据。 代码如下:

    @CacheEvict(key = "'currentTime'+#id",allEntries=false)public void deleteTime(String id) {}
复制代码

@Caching

  本注解可将其他注解组合起来使用。比如下面的例子:

    //value属性为key指定前缀@Caching(put = {@CachePut(value = "user", key = "'name_'+#user.name"),@CachePut(value = "user", key = "'pass_'+#user.password")})public User testCaching(User user) {return user;}
复制代码

上面的代码执行后将在 redis 中插入两条记录。使用keys *将看到如下结果:

手动控制

  手动控制就相当于 mybatis 的手写 sql 语句,需要调用redisTemplate中的各种方法来进行缓存查询,缓存更新,缓存删除等操作。

  使用方法参见 util/RedisUtil 中的方法。redisTemplate基本可以实现所有的 redis 操作。

本篇原创发布于:springboot 整合 redis

项目源码::github

你知道如何在springboot中使用redis吗相关推荐

  1. springboot怎么替代jsp_如何在SpringBoot中使用JSP ?但强烈不推荐,果断改Themeleaf吧...

    做WEB项目,一定都用过JSP这个大牌.Spring MVC里面也可以很方便的将JSP与一个View关联起来,使用还是非常方便的.当你从一个传统的Spring MVC项目转入一个Spring Boot ...

  2. springboot中使用redis详解

    一.redis简介 redis是一款高性能key-value(键值对)内存型数据库,是非关系型数据库的一种,它采用单线程的架构方式,避免了多线程存在的锁处理造成的资源耗费,读取速度非常快,非常适合变化 ...

  3. php中redis设置队列过期时间,如何在php中使用redis队列操作

    如何在php中使用redis队列操作 发布时间:2021-02-04 18:36:00 来源:亿速云 阅读:90 作者:Leah 这篇文章给大家介绍如何在php中使用redis队列操作,内容非常详细, ...

  4. 如何在springboot中实现简单的草稿箱

    如何在springboot中实现简单的草稿箱 建表 sql语句 相关代码 建表 我们只需要给表加一个状态的字段来进行判断他是不是草稿即可 例如 CREATE TABLE `recipe` (`id` ...

  5. SpringBoot中集成Redis实现对redis中数据的解析和存储

    场景 SpringBoot中操作spring redis的工具类: SpringBoot中操作spring redis的工具类_霸道流氓气质的博客-CSDN博客 上面讲的操作redis的工具类,但是对 ...

  6. SpringBoot中使用Redis保存对象或集合

    1,引入SpringBoot中Redis依赖 <!-- redis --> <dependency><groupId>org.springframework.boo ...

  7. SpringBoot中使用redis事务

    本文基于SpringBoot 2.X 事务在关系型数据库的开发中经常用到,其实非关系型数据库,比如redis也有对事务的支持,本文主要探讨在SpringBoot中如何使用redis事务. 事务的相关介 ...

  8. Docker中搭建redis分片集群,搭建redis哨兵结构,实现springboot中对redis分片集群、哨兵结构的访问,Redis缓存雪崩、缓存击穿处理(非关系型数据库技术课程 第十二周)

    文章目录 一.要求: 二.知识总结 缓存雪崩 解决方案 docker中redis分片集群搭建 配置好配置文件 redis-6380.conf redis-6381.conf redis-6382.co ...

  9. redis:01入门指南以及在springboot中使用redis

    https://redis.io/download step1:参考官网的安装很简单 wget http://download.redis.io/releases/redis-5.0.6.tar.gz ...

最新文章

  1. mysql 视图列信息_MySQL 中获取用户表、用户视图、用户表中列信息
  2. 【转载】目前为止看到描述VSCode编写C++配置文件最清楚的一篇文章
  3. 腾讯云【人脸识别】服务的一次尝试(JAVA)
  4. FL2440的U-boot-2009.08移植(三)支持Nor FLASH
  5. 探究php底层运行机制
  6. 大剑无锋之Hadoop的三个作业调度器【面试推荐】
  7. sqlite like concat 怎么 替代_Joplin:真正的 Evernote 开源替代品
  8. linux mysql 释放x锁_MySQL 加锁处理分析-转载
  9. 【并查集】【图论】旅行(ssl 1312)
  10. 今天的解放过后的蜡笔小新
  11. 重学数据结构——快速排序,二分法查找
  12. oracle11 dataguard,探索Oracle之11g DataGuard
  13. cocoStudio工具的使用-----场景编辑器
  14. 六面体单元的体积计算方法
  15. opencv--轮廓拟合函数 boundingRect(),minAreaRect(),minEnclosingCircle(),fitEllipse(),fitLine()
  16. 棋圣高调搬弄名人日本棋圣挟五冠搬弄对手
  17. 计算机新建表格2,(Word表格的制作计算机基础2.doc
  18. 如今做网商还能以前一样吗?网站必不可少
  19. [react] redux react-redux
  20. SAP PP 笔记(二)物料

热门文章

  1. AI产品经理入门手册(下)
  2. 「SAP技术」SAP 如何看序列号被包在哪些HU里?
  3. 深度学习原理—代码分析线性分类与神经网络分类的区别
  4. 机器学习中的数学基础(1)——向量和范数
  5. 深度学习经典案例解析:YOLO系列
  6. P3项目全球模板狗血设置之一 --- 发货到成本中心需要输入Customer
  7. 人工智能的挑战远未到来
  8. 分析 | MEMS传感器市场报告
  9. SpaceX再发射58颗星链卫星 总数达到538颗
  10. 养成一个新习惯,只需要这个大脑区域兴奋0.5秒