Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门
文章目录
为了提高性能,减少数据库的压力,使用缓存是非常好的手段之一。本文,讲解 Spring Boot 如何集成缓存管理。
声明式缓存
Spring 定义 CacheManager 和 Cache 接口用来统一不同的缓存技术。例如 JCache、 EhCache、 Hazelcast、 Guava、 Redis 等。在使用 Spring 集成 Cache 的时候,我们需要注册实现的 CacheManager 的 Bean。
Spring Boot默认集成CacheManager
Spring Boot 为我们自动配置了多个 CacheManager 的实现。
Spring Boot 为我们自动配置了 JcacheCacheConfiguration、 EhCacheCacheConfiguration、HazelcastCacheConfiguration、GuavaCacheConfiguration、RedisCacheConfiguration、SimpleCacheConfiguration 等。
默认的 ConcurrenMapCacheManager
Spring 从 Spring3.1 开始基于 java.util.concurrent.ConcurrentHashMap 实现的缓存管理器。所以, Spring Boot 默认使用 ConcurrentMapCacheManager 作为缓存技术。
以下是我们不引入其他缓存依赖情况下,控制台打印的日志信息。
- Bean 'cacheManager' of type [class org.springframework.cache.concurrent.ConcurrentMapCacheManager]
实战演练
Maven 依赖
首先,我们先创建一个 POM 文件。
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>1.3.3.RELEASE</version>
- </parent>
- <groupId>com.lianggzone.demo</groupId>
- <artifactId>springboot-action-cache</artifactId>
- <version>0.1</version>
- <packaging>jar</packaging>
- <name>springboot-action-cache</name>
- <dependencies>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-cache</artifactId>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <configuration>
- <defaultLibBundleDir>lib</defaultLibBundleDir>
- <source>1.7</source>
- <target>1.7</target>
- <encoding>UTF-8</encoding>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-resources-plugin</artifactId>
- <configuration>
- <encoding>UTF-8</encoding>
- <useDefaultDelimiters>false</useDefaultDelimiters>
- <escapeString>\</escapeString>
- <delimiters>
- <delimiter>${*}</delimiter>
- </delimiters>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
- </project>
其中,最核心的是添加 spring-boot-starter-cache 依赖。
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-cache</artifactId>
- </dependency>
开启缓存支持
在 Spring Boot 中使用 @EnableCaching 开启缓存支持。
- @Configuration
- @EnableCaching
- public class CacheConfiguration {}
服务层
创建一个服务类
- @Service("concurrenmapcache.cacheService")
- public class CacheService {
- }
首先,我们先来讲解下 @Cacheable 注解。@Cacheable 在方法执行前 Spring 先查看缓存中是否有数据,如果有数据,则直接返回缓存数据;若没有数据,调用方法并将方法返回值放进缓存。有两个重要的值, value,返回的内容将存储在 value 定义的缓存的名字对象中。key,如果不指定将使用默认的 KeyGenerator 生成。
我们在查询方法上,添加 @Cacheable 注解,其中缓存名称为 concurrenmapcache。
- @Cacheable(value = "concurrenmapcache")
- public long getByCache() {
- try {
- Thread.sleep(3 * 1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- return new Timestamp(System.currentTimeMillis()).getTime();
- }
@CachePut 与 @Cacheable 类似,但是它无论什么情况,都会将方法的返回值放到缓存中, 主要用于数据新增和修改方法。
- @CachePut(value = "concurrenmapcache")
- public long save() {
- long timestamp = new Timestamp(System.currentTimeMillis()).getTime();
- System.out.println("进行缓存:" + timestamp);
- return timestamp;
- }
@CacheEvict 将一条或多条数据从缓存中删除, 主要用于删除方法,用来从缓存中移除相应数据。
- @CacheEvict(value = "concurrenmapcache")
- public void delete() {
- System.out.println("删除缓存");
- }
控制层
为了展现效果,我们先定义一组简单的 RESTful API 接口进行测试。
- @RestController("concurrenmapcache.cacheController")
- @RequestMapping(value = "/concurrenmapcache/cache")
- public class CacheController {
- @Autowired
- private CacheService cacheService;
- /**
- * 查询方法
- */
- @RequestMapping(value = "", method = RequestMethod.GET)
- public String getByCache() {
- Long startTime = System.currentTimeMillis();
- long timestamp = this.cacheService.getByCache();
- Long endTime = System.currentTimeMillis();
- System.out.println("耗时: " + (endTime - startTime));
- return timestamp+"";
- }
- /**
- * 保存方法
- */
- @RequestMapping(value = "", method = RequestMethod.POST)
- public void save() {
- this.cacheService.save();
- }
- /**
- * 删除方法
- */
- @RequestMapping(value = "", method = RequestMethod.DELETE)
- public void delete() {
- this.cacheService.delete();
- }
- }
运行
- @RestController
- @EnableAutoConfiguration
- @ComponentScan(basePackages = { "com.lianggzone.springboot" })
- public class WebMain {
- public static void main(String[] args) throws Exception {
- SpringApplication.run(WebMain.class, args);
- }
- }
课后作业
我们分为几个场景进行测试。
- 多次调用查询接口,查看缓存信息是否变化,控制台日志是否如下?你得到的结论是什么?
- 调用保存接口,再调用查询接口,查看缓存信息是否变化?你得到的结论是什么?
- 调用删除接口,再调用查询接口,接口响应是否变慢了?你再看看控制台日志,你得到的结论是什么?
扩展阅读
如果想更深入理解 Spring 的 Cache 机制,这边推荐两篇不错的文章。
源代码
相关示例完整代码: springboot-action
(完)
如果觉得我的文章对你有帮助,请随意打赏。

- 版权声明:本文由 梁桂钊 发表于 梁桂钊的博客
- 转载声明:自由转载-非商用-非衍生-保持署名(创意共享3.0许可证),非商业转载请注明作者及出处,商业转载请联系作者本人。
- 文章标题:Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门
- 文章链接:http://blog.720ui.com/2017/springboot_02_data_cache_concurrenmapcache/
Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门的更多相关文章
- Spring Boot 揭秘与实战(二) 数据缓存篇 - Redis Cache
文章目录 1. Redis Cache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 Redis Cache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存 ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - Guava Cache
文章目录 1. Guava Cache 集成 2. 个性化配置 3. 源代码 本文,讲解 Spring Boot 如何集成 Guava Cache,实现缓存. 在阅读「Spring Boot 揭秘与实 ...
- Spring Boot 揭秘与实战(二) 数据缓存篇 - EhCache
文章目录 1. EhCache 集成 2. 源代码 本文,讲解 Spring Boot 如何集成 EhCache,实现缓存. 在阅读「Spring Boot 揭秘与实战(二) 数据缓存篇 - 快速入门 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - 声明式事务管理
文章目录 1. 声明式事务 2. Spring Boot默认集成事务 3. 实战演练4. 源代码 3.1. 实体对象 3.2. DAO 相关 3.3. Service 相关 3.4. 测试,测试 本文 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - ElasticSearch
文章目录 1. 版本须知 2. 环境依赖 3. 数据源 3.1. 方案一 使用 Spring Boot 默认配置 3.2. 方案二 手动创建 4. 业务操作5. 总结 4.1. 实体对象 4.2. D ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MongoDB
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用mongoTemplate操作4. 总结 3.1. 实体对象 3 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - Redis
文章目录 1. 环境依赖 2. 数据源 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 3. 使用 redisTemplate 操作4. 总结 3.1. 工具类 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - JPA整合
文章目录 1. 环境依赖 2. 数据源 3. 脚本初始化 4. JPA 整合方案一 通过继承 JpaRepository 接口 4.1. 实体对象 4.2. DAO相关 4.3. Service相关 ...
- Spring Boot 揭秘与实战(二) 数据存储篇 - MyBatis整合
文章目录 1. 环境依赖 2. 数据源3. 脚本初始化 2.1. 方案一 使用 Spring Boot 默认配置 2.2. 方案二 手动创建 4. MyBatis整合5. 总结 4.1. 方案一 通过 ...
随机推荐
- weblogic隐藏版本号教程(10.3.6为例)
隐藏版本号,如同大多数中间件都是取消Server头的发送:weblogic而言其默认就是不发送Server头的(即下边的“发送服务器标头”默认就是没钩选的). 写此教程的原因,一是以防Server头被 ...
- IO库----IO类,文件输入输出,string流
一.IO类 1.IO库类型和头文件表: 头文件 类型 iostream istream,wistream 从流读取数据 ostream,wostream 向流写入数据 iostream,wiostre ...
- 【框架】用excel管理测试用例需要的参数数据(二)
一.总体思路 以类为excel名,测试方法名为sheet名,建立excel文件.用jxl包里的方法去读取excel文件里的内容,然后用testng里的dataprovider,将数据传递给测试用例 二 ...
- Win10系列:UWP界面布局基础3
在实际项目开发中,为控件属性赋值时经常会遇到属性值在设计时处于未知状态,而只有在应用程序运行时才能获取到.这种情况下,直接赋值方法是无法满足的,可以使用XAML标记扩展(Markup Extensio ...
- day03_python_1124
01 昨日内容回顾 while 条件: 循环体 如何终止循环: 1,改变条件. 2,break. 3,exit() quit() 不推荐. 关键字: break continue while else ...
- 容错机制和熔断(Hystrix)
雪崩效应 在微服务架构中,由于服务众多,通常会涉及多个服务层级的调用,而一旦基础服务发生故障,很可能会导致级联故障,进而造成整个系统不可用,这种现象被称为服务雪崩效应.服务雪崩效应是一种因“服务提供者 ...
- nginx:负载均衡实战(二) keepalived入门
1.keepalived介绍 顾名思义,keepalived就是保持网络在线的,用来保证集群高可用HA的服务软件.主要防止出现单点故障(坏了一个点导致整个系统架构不可用) 2.详解keepalived ...
- day043 前端css样式
标签嵌套规则 块级标签能够嵌套某些块级标签和内敛标签(行内标签) 内敛标签不能块级标签,只能嵌套内联标签 块级标签能够设置高度和宽度 内敛标签不能设置,设置没有效果 Css样式 高度宽度: Width ...
- python nltk 安装及配置说明
本教程采用pip安装方式,前期需要在本机安装setuptools 及pip 网上铺天盖地的说了很多关于nltk的说明,特别是后期nltk_data 手动下载操作,多数都不好使,这里整理 用pip安装n ...
- tf.nn.conv2d
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None) input: 指需要做卷积的输入图像,它 ...