使用Spring Cache
Spring提供了Cache抽象,它允许我们声明哪些bean的哪些方法的外部调用需要使用Cache。方法调用使用了Cache后,在调用真实方法前会先从缓存中获取结果,缓存中如果没有则会调用真实方法,这也是基于AOP实现的。关于Spring Cache的介绍不是本文的重点,如有需要可以参考笔者写的http://elim.iteye.com/blog/2123030。
在Spring Boot应用中使用Spring Cache需要在@SpringBootConfiguration
标注的Class上添加@EnableCaching
,这样就启用了Spring Cache。Spring Boot将根据Classpath下提供的Spring Cache实现类选择合适的实现者进行自动配置,支持的实现有基于Ehcache的实现、基于Redis的实现等,详情可参考org.springframework.boot.autoconfigure.cache.CacheConfiguration
的源码。如果没有找到,则会使用基于ConcurrentMap的实现。
下面的代码中就启用了Spring Cache。
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(Application.class);
app.setAddCommandLineProperties(false);
app.run(args);
}
}
然后就可以在bean中使用Spring Cache提供的注解进行缓存的定义了,下面的代码中就定义了getTime()
将使用名称为cacheName1
的缓存。
@Component
public class SimpleService {
@Cacheable("cacheName1")
public long getTime() {
return System.currentTimeMillis();
}
}
简单的验证缓存生效的单元测试如下。
@SpringBootTest(classes=Application.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class CacheTest {
@Autowired
private SimpleService simpleService;
@Test
public void testGetTime() throws Exception {
long time1 = this.simpleService.getTime();
TimeUnit.MILLISECONDS.sleep(100);
long time2 = this.simpleService.getTime();
Assert.assertEquals(time1, time2);
}
}
使用Ehcache实现
需要使用Spring Cache的Ehcache实现,首先需要在pom.xml中加入如下依赖。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
</dependency>
然后最简单的方式是在Classpath的根路径下放一个ehcache.xml
文件,这样Spring Boot默认就会启用Spring Cache的Ehcache实现了。Ehcache的自动配置由EhCacheCacheConfiguration
定义。如果Ehcache的配置文件不是存放在Classpath根路径,则可以通过spring.cache.ehcache.config
来指定,比如下面的代码指定了在Classpath下的config目录下寻找ehcache.xml文件作为Ehcache的配置文件。
spring.cache.ehcache.config=classpath:/config/ehcache.xml
Spring Cache的自动配置的属性定义类是CacheProperties,参考其API文档或源码可以查看选择的Spring Cache的实现可以指定的详细的配置信息。
SimpleService的getTime()
指定了使用的Cache是名称为cacheName1的Cache。所以在ehcache.xml中需要定义一个名为cacheName1的Cache,配置如下:
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
maxBytesLocalHeap="100M">
<defaultCache maxElementsInMemory="10000" eternal="false"
timeToIdleSeconds="120" timeToLiveSeconds="120"
maxElementsOnDisk="10000000" diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU">
<persistence strategy="localTempSwap" />
</defaultCache>
<cache name="cacheName1" />
</ehcache>
如果应用中应用了很多不同名称的Cache,如果都把它们在ehcache.xml中定义一次,可能你会觉得太麻烦。可能你想把一些主要的Cache在ehcache.xml中定义,进行充分的自定义配置。然后其它的则能够在使用的时候自动创建,并使用默认的默认的缓存配置,则可以定义自己的EhCacheCacheManager实现bean,实现getMissingCache()
的逻辑为不存在则创建。这样Spring Boot将不再自动创建EhCacheCacheManager bean。下面的代码是一个简单的示例。
@Component
public class MyEhCacheCacheManager extends EhCacheCacheManager {
@Override
protected Cache getMissingCache(String name) {
Cache cache = super.getMissingCache(name);
if (cache == null) {
Ehcache ehcache = super.getCacheManager().addCacheIfAbsent(name);
cache = new EhCacheCache(ehcache);
}
return cache;
}
}
使用Redis实现
需要使用Redis实现需要在pom.xml中添加spring-boot-starter-data-redis
依赖,这样Spring Boot将自动创建RedisTemplate bean,有了RedisTemplate bean后Spring Boot将自动创建基于Redis实现的Spring Cache的CacheManager,RedisCacheManager。
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
Spring Boot默认创建的RedisTemplate将使用localhost作为服务地址,端口号是6379,数据库索引为0,可以通过spring.redis.host
指定Redis服务IP,spring.redis.port
指定Redis服务监听端口号,spring.redis.database
指定需要使用的数据库索引号。下面的代码中就指定了使用的是10.10.10.3
这台主机上的Redis,数据库索引号是1。关于Redis的更多配置信息可以参考org.springframework.boot.autoconfigure.data.redis.RedisProperties
的API文档。
spring.redis.host=10.10.10.3
spring.redis.database=1
默认Spring Cache的Redis实现存入Redis中的Key是cacheName::cacheKey
的形式,其中cacheName是当前Spring Cache的name,cacheKey是Spring Cache传递过来的Key。可以通过spring.cache.redis.key-prefix
指定存入Redis中的Key的前缀,当指定了该属性时,生成的Key将是该前缀加上Spring Cache传递过来的Key。比如下面的代码中指定了前缀是test-spring-cache::
,如果Spring Cache传递的Key是key1,则最终存入Redis中的Key将是test-spring-cache::key1
。
spring.cache.redis.key-prefix=test-spring-cache::
可以通过spring.cache.redis.timeToLive
指定Redis缓存的Key的存活时间。下面的代码中就指定了缓存的有效时间是60秒。
spring.cache.redis.timeToLive=60s
关于Spring Cache的Redis实现的更多配置可以参考org.springframework.boot.autoconfigure.cache.CacheProperties.Redis
的API文档。
指定Cache实现
当Classpath下同时存放了多个Spring Cache的实现类,并且同时有多个Spring Cache实现类可以满足启用条件时,Spring Boot将按照一定的顺序进行选择,一旦应用了某个类型的Spring Cache实现后,其它类型的Spring Cache实现将是非启用的,因为这些自动启用的前提都要求当前环境中尚未有Spring Cache的CacheManager类型的bean。自动启用的顺序是按照org.springframework.boot.autoconfigure.cache.CacheType
这个枚举中定义的顺序来的,它的定义如下。
/**
* Generic caching using 'Cache' beans from the context.
*/
GENERIC,
/**
* JCache (JSR-107) backed caching.
*/
JCACHE,
/**
* EhCache backed caching.
*/
EHCACHE,
/**
* Hazelcast backed caching.
*/
HAZELCAST,
/**
* Infinispan backed caching.
*/
INFINISPAN,
/**
* Couchbase backed caching.
*/
COUCHBASE,
/**
* Redis backed caching.
*/
REDIS,
/**
* Caffeine backed caching.
*/
CAFFEINE,
/**
* Simple in-memory caching.
*/
SIMPLE,
/**
* No caching.
*/
NONE
所以一旦Classpath下同时拥有Ehcache和Redis的Spring Cache实现时,将优先使用Ehcache的实现,如果想使用Redis的实现,可以通过spring.cache.type=redis
指定使用Redis的实现。
指定Cache实现仅针对于自动配置生效,如果是自己定义了CacheManager实现,则该配置无效。
CacheManagerCustomizer
CacheManagerCustomizer是用来对CacheManager进行自定义扩展的,其定义如下:
@FunctionalInterface
public interface CacheManagerCustomizer<T extends CacheManager> {
/**
* Customize the cache manager.
* @param cacheManager the {@code CacheManager} to customize
*/
void customize(T cacheManager);
}
当需要对某个CacheManager实现进行一些自定义时,可以实现CacheManagerCustomizer接口,指定泛型为需要进行自定义的CacheManager实现类,然后把它定义为一个Spring bean。下面的代码就对Ehcache实现的CacheManager进行了一些自定义,其在EhCacheCacheManager初始化后采用默认的Cache配置创建了一些Cache。
@Component
public class EhcacheCacheManagerCustomizer implements CacheManagerCustomizer<EhCacheCacheManager> {
@Override
public void customize(EhCacheCacheManager cacheManager) {
List<String> cacheNames = Arrays.asList("cacheName1", "cacheName2", "cacheName3", "cacheName4", "cacheName5", "cacheName6");
cacheNames.forEach(cacheManager.getCacheManager()::addCacheIfAbsent);
}
}
关于Spring Cache的自动配置可以参考org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration
的源码或API文档。
(注:本文是基于Spring Boot 2.0.3所写)
相关推荐
1.39 Spring Boot Cache理论篇 1.40 Spring Boot集成EHCache实现缓存机制 1.41 Spring Boot分布式Session状态保存Redis 1.42 Spring Boot Shiro权限管理 1.43 Spring Boot Shiro权限管理 1.44 Spring Boot Shiro权限...
本书系统介绍了Spring Boot 2的主要技术,侧重于两个方面,一方面是极速开发一个Web应用系统,详细介绍Spring Boot框架、Spring MVC、视图技术...使用Spring Session实现系统水平扩展,使用Spring Cache提高系统性能。
包括使用Spring实现RESTful架构,在Spring Boot框架下使用Redis、MongoDB、ZooKeeper、Elasticsearch等流行技术,使用Spring Session实现系统水平扩展,使用Spring Cache提高系统性能。 2.面对系统模块增加,性能和...
核心技术采用Eureka、Fegin、Ribbon、Zuul、Hystrix、Security、OAth、Mybatis、Ace-cache等主要框架和中间件,UI采用Bootstrap、jquery等前端组件 spring boot项目是使用spring boot + thymeleaf 开发个人博客项目
- Spring Boot 缓存,包括redis、ehcache、spring-cache、memcached、使用redis实现session共享 等。 - springboot-templates - Spring Boot 模板,包括thymeleaf、freemarker、jsp、表单校验 等。 - ...
spring boot —— redis 缓存注解使用教程 示例项目地址: 依赖 在pom文件添加如下依赖 <groupId>org.springframework.boot <artifactId>spring-boot-starter-data-redis 配置 在application.yml配置文件添加...
Spring Boot 整合 Spring-cache:让你的网站速度飞起来
主要介绍了spring boot+spring cache实现两级缓存(redis+caffeine),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
spring boot 学习的最佳选择,包含了jpa ,tomcat ,cache, ant ,hibernate4 , jetty,war,web ,xml 等
Spring Boot 学习笔记完整教程
在Spring Boot中,你可以使用Spring框架提供的缓存管理来提高应用程序的性能。Spring Boot支持多种缓存实现,包括内存缓存和分布式缓存。 1.添加缓存依赖: 在项目的 pom.xml 文件中添加所需的缓存依赖。 2.配置缓存...
11. Developing Your First Spring Boot Application 11.1. Creating the POM 11.2. Adding Classpath Dependencies 11.3. Writing the Code 11.3.1. The @RestController and @RequestMapping Annotations 11.3.2. ...
1.6 使用Spring Initializer向导快速创建Spring Boot 16 2 Spring Boot配置 18 2.1 配置文件 18 2.2 YML语法 19 2.3 YML配置文件值获取 21 2.4 properties配置文件乱码问题 24 2.5 @ConfigurationProperties与@Value...
涵盖使用Spring Boot 进行Java EE 开发的绝大数应用场景,包含:Web 开发、数据访问、安全控制、批处理、异步消息、系统集成、开发与部署、应用监控、分布式系统开发等。 第一部分 点睛Spring 4.x 第1 章 Spring ...
spring boot cache 整合 redis demo (内包含 redis windows 安装包,和redis desktop 桌面 管理工具)
Spring Boot 功能特性和组件系列的整合, 详解与使用。下面所有Demo都是基于 Spring Boot 2.0.x, 2.1.x, 2.2.x 版本。 : Blog: Github: Gitee: 数据库 本示例及所有子项目使用的数据库系统是MySQL, 连接的数据库...
JavaEE开发的颠覆者 Spring Boot实战,多个地址免费下载,第一部分 点睛Spring 4.x 第1 章 Spring 基础 ..........................................2 1.1 Spring 概述 ................................................
除了按顺序侦测外,我们也可以通过配置属性spring.cache.type来强制指定。我们也可以通过debug调试查看cacheManager对象的实例来判断当前使用了什么缓存。在上一篇中,我们也展示了如何去查看当前使用情况。