Spring Boot 集成 Redis 实现数据缓存,只要添加一些注解方法,就可以动态的去操作缓存了,减少代码的操作。

在这个例子中我使用的是 Redis,其实缓存类型还有很多,例如 Ecache、Mamercache、Caffeine  等。

Redis 简介

Redis 是一个开源,高级的键值存储和一个适用的解决方案,用于构建高性能,可扩展的 Web 应用程序。

Redis 相关的知识就不在这里赘述了,感兴趣的可以公众号回复 Redis 看下 Redis 系列文章。

下面我们在 Spring Boot 中集成 Redis 来实现数据缓存。

Spring Boot 集成 Redis 实现缓存

Spring Boot 集成 Redis 实现缓存主要分为以下三步:

  1. 加入 Redis 依赖
  2. 加入 Redis 配置
  3. 演示 Redis 缓存

加入依赖

首先创建一个项目,在项目中加入 Redis 依赖,项目依赖如下所示(由于使用 Redis 连接池,需额外引入 commons-pool2):

org.springframework.bootspring-boot-starter-weborg.springframework.bootspring-boot-starter-data-redisorg.apache.commonscommons-pool2

spring-boot-starter-data-redis 1.X 版本默认使用 Jedis 客户端,在 2.X 版本默认开始使用 Lettuce 客户端,如果习惯使用 Jedis 的话,可以从 spring-boot-starter-data-redis 中排除 Lettuce 并引入 Jedis。

加入配置

在配置文件 application.properties 中配置 Redis 的相关参数,具体内容如下:

#Redis 索引(0~15,默认为 0)spring.redis.database=0spring.redis.host=127.0.0.1#Redis 密码,如果没有就默认不配置此参数spring.redis.password=spring.redis.port=6379#Redis 连接的超时时间spring.redis.timeout=1000#连接池最大连接数(使用负值表示没有限制)spring.redis.lettuce.pool.max-active=20#连接池最大阻塞等待时间(使用负值表示没有限制)spring.redis.lettuce.pool.max-wait=-1#连接池中的最大空闲连接spring.redis.lettuce.pool.max-idle=10#连接池中的最小空闲连接spring.redis.lettuce.pool.min-idle=0

接下来在 config 包下创建一个 Redis 配置类 RedisConfig,在配置类上加入注解 @Configuration,注入一个 CacheManager 来配置一些相关信息,代码如下:

@Configurationpublic class RedisConfig {

    @Bean    public CacheManager cacheManager(RedisConnectionFactory factory) {        RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()                .entryTtl(Duration.ofMinutes(30))                .prefixKeysWith("cache:user:")                .disableCachingNullValues()                .serializeKeysWith(keySerializationPair())                .serializeValuesWith(valueSerializationPair());        return RedisCacheManager.builder(factory)                .withCacheConfiguration("user", redisCacheConfiguration).build();    }

    private RedisSerializationContext.SerializationPair keySerializationPair() {        return RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer());    }

    private RedisSerializationContext.SerializationPair valueSerializationPair() {        return RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer());    }}

首先通过 RedisCacheConfiguration 生成默认配置,然后对缓存进行自定义化配置,比如过期时间、缓存前缀、key/value 序列化方法等,然后构建出一个 RedisCacheManager,其中通过 keySerializationPair 方法为 key 配置序列化,valueSerializationPair 为 value 配置序列化。

定义用户实体类

domain 包下创建一个用户实体类:

public class User {

    private Long id;

    private String name;

    private String password;    // 省略 getter/setter}

在服务中使用 SpringCache 注解

service 包下定义用户接口,分别包含添加用户、查询用户、更新用户以及删除用户四个接口,具体代码如下:

public interface UserService {

    void addUser(User user);

    User getUserById(Long id);

    User updateUser(User user);

    void deleteById(Long id);}

然后编写实现类,为了方便演示,在这里使用 Map userMap,没有去连接数据库,其中用到的注解有 @CacheConfig、@Cacheable、@CachePut 以及 @CacheEvict,具体代码如下:

@Service@CacheConfig(cacheNames = "user")public class UserServiceImpl implements UserService {

    Map userMap = Collections.synchronizedMap(new HashMap<>());@Overridepublic void addUser(User user) {        userMap.put(user.getId(), user);    }@Override@Cacheable(key = "#id")public User getUserById(Long id) {if (!userMap.containsKey(id)) {return null;        }return userMap.get(id);    }@Override@CachePut(key = "#user.id")public User updateUser(User user) {if (!userMap.containsKey(user.getId())) {throw new RuntimeException("不存在该用户");        }        User newUser = userMap.get(user.getId());        newUser.setPassword(user.getPassword());        userMap.put(newUser.getId(), newUser);return newUser;    }@Override@CacheEvict(key = "#id")public void deleteById(Long id) {        userMap.remove(id);    }}

在这里说下这几个注解:

@CacheConfig 类级别的缓存注解,允许共享缓存名称

@Cacheable 触发缓存入口

一般用于查询操作,根据 key 查询缓存.

  1. 如果 key 不存在,查询 db,并将结果更新到缓存中。
  2. 如果 key 存在,直接查询缓存中的数据。

@CacheEvict 触发移除缓存

根据 key 删除缓存中的数据。

@CacahePut 更新缓存

一般用于更新和插入操作,每次都会请求 db,通过 key 去 Redis 中进行操作。

  1. 如果 key 存在,更新内容
  2. 如果 key 不存在,插入内容。

最后,在 controller 包下创建一个 UserController 类,提供用户 API 接口(未使用数据库),代码如下:

@RestController@RequestMapping("/user")public class UserController {

    @Autowired    private UserService userService;

    @GetMapping("/{id}")    public ResponseEntity getUser(@PathVariable Long id) {        return ResponseEntity.status(HttpStatus.CREATED).body(userService.getUserById(id));    }

    @PostMapping    public ResponseEntity createUser(@RequestBody User user) {        userService.addUser(user);        return ResponseEntity.status(HttpStatus.CREATED).body("SUCCESS");    }

    @PutMapping    public ResponseEntity updateUser(@RequestBody User user) {        return ResponseEntity.status(HttpStatus.CREATED).body(userService.updateUser(user));    }

    @DeleteMapping("/{id}")    public ResponseEntity deleteUser(@PathVariable Long id) {        userService.deleteById(id);        return ResponseEntity.status(HttpStatus.CREATED).body("SUCCESS");    }}

启动类添加开启缓存注解

@SpringBootApplication@EnableCachingpublic class RedisCacheApplication {

    public static void main(String[] args) {        SpringApplication.run(RedisCacheApplication.class, args);    }}

@EnableCaching 表明开启缓存,Spring Boot 会自动配置 Redis 缓存的 CacheManager。

启动项目,先调用添加用户接口,添加用户 wupx,id 为 1,在 getUserById 方法打断点,第一次调用 getUser 接口获取用户的时候,会运行到断点处,第二次调用 getUser 不会运行到断点处,而是直接从 Redis 中读取缓存数据。

通过 Redis 可视化工具 RedisDesktopManager 查看,结果如图所示:


到此为止,我们就完成了 Spring Boot 与 Redis 的集成实现数据缓存。

总结

Spring Boot 集成 Redis 实现数据缓存还是比较轻松的,Spring 提供了缓存注解,使用这些注解可以有效简化编程过程,大家可以自己动手实践下。

本文的完整代码在 https://github.com/wupeixuan/SpringBoot-Learn 的 redis-cache 目录下。

留言讨论

最好的关系就是互相成就,大家的点赞、在看、分享、留言四连就是我创作的最大动力。

参考

https://github.com/wupeixuan/SpringBoot-Learn

   ●Spring Boot 集成阿里云 OSS 进行文件存储●Spring Boot 集成 Elasticsearch 实战●Spring Boot 集成 WebSocket 实现服务端推送消息到客户端

spring boot 缓存_Spring Boot 集成 Redis 实现数据缓存相关推荐

  1. redis lettuce 超时_Spring Cache 操作 Redis 实现数据缓存(上)

    点击上方☝SpringForAll社区 轻松关注!及时获取有趣有料的技术文章 本文来源:http://www.mydlq.club/article/55/ . 一.缓存概念知识 . 1.是什么缓存 . ...

  2. Spring整合Redis做数据缓存(Windows环境)

    当我们一个项目的数据量很大的时候,就需要做一些缓存机制来减轻数据库的压力,提升应用程序的性能,对于java项目来说,最常用的缓存组件有Redis.Ehcache和Memcached. Ehcache是 ...

  3. Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache

    文章目录 1. EhCache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 EhCache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门 ...

  4. Spring Boot 揭秘与实战(二) 数据缓存篇 - Guava Cache

    本文,讲解 Spring Boot 如何集成 Guava Cache,实现缓存. 博客地址:blog.720ui.com/ 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门」 ...

  5. SpringBoot+Redis完成数据缓存(内容丰富度一定超出你的想象)

    SpringBoot+Redis完成数据缓存 去年今日此门中 人面桃花相映红 人面不知何处去 桃花依旧笑春风 感谢相遇!感谢自己,努力的样子很给力! 为了更多朋友看见,还是和大家说一声抱歉,限制为粉丝 ...

  6. 【Java项目中 利用Redis实现数据缓存】

    文章目录 Java SpringBoot项目中 用Redis实现数据缓存 1 环境搭建 1.1 maven坐标 1.2 配置文件 1.3 配置类 2 实现缓存短信验证码 3 缓存菜品数据 4 Spri ...

  7. mysql springboot 缓存_Spring Boot 整合 Redis 实现缓存操作

    摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『 产品没有价值,开发团队再优秀也无济于事 – <启示录> 』 本文提纲 一.缓 ...

  8. 学习Spring Boot:(二十五)使用 Redis 实现数据缓存

    前言 由于 Ehcache 存在于单个 java 程序的进程中,无法满足多个程序分布式的情况,需要将多个服务器的缓存集中起来进行管理,需要一个缓存的寄存器,这里使用的是 Redis. 正文 当应用程序 ...

  9. 开启注解缓存_Spring Boot 2.x基础教程:进程内缓存的使用与Cache注解详解

    随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一.Spring 3开始提供了强大的基于注解的缓 ...

最新文章

  1. 遇事不决,量子力学:谷歌量子计算模拟化学反应登上Science封面
  2. aspnetcore mvc 异常处理_深入探究ASP.NET Core异常处理中间件
  3. java   web servelt
  4. Android自定义sleep图,android自定义view实现钟表效果
  5. django2中关于时间处理策略
  6. java重新开始循环_java for循环只进行第一次循环
  7. 团队作业7——第二次项目冲刺(Beta版本)
  8. CSS - Iconfont
  9. 阿里云物联网平台mqtt测试工具
  10. Java源码阅读绘图规范手册--[捷特版]
  11. 【kafka】Kafka 可视化工具Kafka Eagle安装和使用
  12. 名帖347 怀素 草书《大草千字文》
  13. 回望2019,不仅是“自由自在“,更是 AI 领域不平凡的一年
  14. Could not calculate build plan: Plugin org.apache.maven.plugins:maven-war-plugin:3.2.2
  15. 浙江独立学院计算机专业排名2015,2018中国独立学院排行榜发布,浙江这所独立学院独占鳌头!...
  16. mysql 除法和四舍五入
  17. python+selenium爬虫,使用selenium爬取热门微博数据
  18. fleury MATLAB,数学建模部分源码分享
  19. Docker技术研究
  20. 用Python写一个量化交易策略

热门文章

  1. 微软重组变两大事业部:Windows主管离职
  2. Identity Service - 解析微软微服务架构eShopOnContainers(二)
  3. 升级.Net Core RC1的类库项目
  4. android 把异常写入到文本里,尝试在Android中将文件写入sdcard时发生FileNotFoundException(权限被拒绝)...
  5. php 合并 字符串_PHP如何去重合并字符串
  6. 实验2 java_《Java程序设计》实验2
  7. mysql中局部变量说法正确的是_mysql全局变量和局部变量
  8. mysql sql语句书写之面试部分
  9. 推荐一简单易用的脑图制作工具
  10. windows 常用系统变量