4.12. Cache (Caching)
The Spring Framework provides support for application transparent add cache. Essentially, the abstract method is applied to the cache, thereby reducing the execution times based on the information available in the cache. Caching logic is transparent to the application, it does not cause any disturbance to the caller. As long as through @EnableCaching
caching is enabled support for annotations, Spring Boot will automatically configure the cache infrastructure.
Briefly, the buffer is added to the service-related operations like adding annotations to as its easy method, as shown in the following example:
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class MathService {
@Cacheable("piDecimals")
public int computePiDecimal(int i) {
// ...
}
}
This example illustrates a method used in the cache potentially expensive operations. In the call computePiDecimal
before, the abstract will be piDecimals
looking for and i parameter matching entry in the cache. If the entry is found, the contents of the cache will be returned immediately to the caller, and do not call this method. Otherwise, it calls the method, and update the cache before returning the value.
You can also use transparent criteria JSR-107
( JCache
) annotation (for example @CacheResult
). However, we strongly recommend that you do not mix Spring Cache and JCache comment.
If you do not add any particular cache library, Spring Boot automatically configure the program to provide a simple memory map in concurrent use. When you need to cache (for example, the previous example piDecimals), this program will offer you to create it. In fact, it is not recommended to provide a simple procedure for production use, but it is useful to get up and make sure you understand. After determining the cache to be used to provide the program, be sure to read the documentation to learn how to configure the cache used by the application. Almost all providers require you to explicitly configure each cache used in the application. Some offers by spring.cache.cache-names
customizing the default cache properties.
Also transparently update or delete data from the cache.
For more information see the Spring Framework Document
4.12.1. Supported cache provider
Cache abstract does not provide actual storage, but is dependent on org.springframework.cache.Cache和org.springframework.cache.CacheManager
the abstract interface implementation.
If you have not defined the type CacheManager
or CacheResolver
and name cacheResolver
(please refer to the bean CachingConfigurer
), Spring Boot tries provider (in the order indicated, the following reference detection org.springframework.boot.autoconfigure.cache.CacheType
):
- Generic
- JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
- ehcache 2.x
- Hazelcast
- Infinispan
- Couchbase
- Redis
- Caffeine
- Simple
- None
You can be set spring.cache.type
to force use of specific properties of the cache provider. If you need to completely disable the cache in some environments (such as test), use this property.
Use spring-boot-starter-cache
starter quickly add basic cache dependency. Starter brought in spring-context-support
. If you manually add dependencies, you must include spring-context-support
in order to use JCache
, EhCache 2.x
or Caffeine
support.
If Spring Boot automatically configured CacheManager
, you can achieve through an open CacheManagerCustomizer
interface bean, further adjustments to its configuration before fully initialized. The following example sets a flag indicating that should null
the value passed down to the bottom of the Map:
@Bean
public CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {
return new CacheManagerCustomizer<ConcurrentMapCacheManager>() {
@Override
public void customize(ConcurrentMapCacheManager cacheManager) {
cacheManager.setAllowNullValues(false);
}
};
}
In the previous example, the need for automatic configuration ConcurrentMapCacheManager
. If this is not the case (you provide your own configuration, automatic configuration or other cache provider), it will not call a custom program. You may need to have any number of custom programs can also be used @Order
or Ordered
sort them.
Generic
If context defines at least a org.springframework.cache.Cache
bean, the generic cache. CacheManager
The packaging of this particular type of bean.
JCache (JSR-107)
JCache path through the upper class javax.cache.spi.CachingProvider
(i.e., present on the classpath meet JSR-107 cache library), and guided JCacheCacheManager
by the spring-boot-starter-cache
provided "launcher." Compatible with a variety of libraries available, Spring Boot to Ehcache 3
, Hazelcast
and Infinispan
provides dependency management. You can also add any other compatible libraries.
May appear multiple providers, in this case, you must explicitly specify the provider. JSR-107 standard does not even mandatory standardized way to define the location profile, Spring Boot will do its best to accommodate the implementation details of the cache, as shown in the following example has:
# Only necessary if more than one provider is present
spring.cache.jcache.provider=com.acme.MyCachingProvider
spring.cache.jcache.config=classpath:acme.xml
When the cache library provides native support for JSR-107 implementation and at the same time, Spring Boot will be the preferred JSR-107 support, so if you switch to another JSR-107 implementation, you can use the same function.
Spring Boot has the general support for Hazelcast. If the individual HazelcastInstance
is available, unless specified spring.cache.jcache.config
attribute, otherwise it will automatically re-used CacheManager
.
There are two ways to customize the bottom javax.cache.cacheManager
:
- You can set when you start
spring.cache.cache-names
to create a cache properties. If you define a customjavax.cache.configuration.Configuration
bean, then it is used to customize them. - Using
CacheManager
references to callorg.springframework.boot.autoconfigure.cache.JCacheManagerCustomizer
the bean is fully customizable.
If you define a standard javax.cache.CacheManager
bean, it automatically packaged in org.springframework.cache.CacheManager
abstract desired implementation. No longer its application customization.
ehcache 2.x
If you can find the class named in the root directory path of ehcache.xml
the file is used EhCache2.x
. If found EhCache 2.x, use the spring-boot-starter-cache
"starter" provided EhCacheCacheManager
to guide the cache manager. Backup configuration file, as in this example may also be provided:
spring.cache.ehcache.config=classpath:config/another-config.xml
Hazelcast
Spring Boot has the general support for Hazelcast. If you have automatically configured HazelcastInstance
, it is automatically packaged CacheManager
in.
Infinispan
Infinispan no default profile location, so you must explicitly specify. Otherwise, the default boot loader.
spring.cache.infinispan.config=infinispan.xml
You can set when you start spring.cache.cache-names
to create a cache properties. If you define a custom ConfigurationBuilder
bean, then it will be used to customize the cache.
Spring Boot support for Infinispan limited to embedded mode, and very basic. If you need more options, you should use the official Infinispan Spring Boot starter. For more detailed information, see the documentation Infinispan.
Couchbase
If Couchbase Java client and couchbase-spring-cache
implementation is available, and you have configured Couchbase, it will be automatically configured CouchbaseCacheManager
. By setting the spring.cache.cache-names
property, you can also create other cache at startup. These caches running on Bucket configured automatically. By using customization, you can also create other caches in the Bucket in another. Let's say you need two caches (cache1 and cache2) on the "main" Bucket, need custom cache survival time of two seconds (cache3) on "another" Bucket. You can create a buffer by the first two configurations, as follows:
spring.cache.cache-names=cache1,cache2
Then, you can define a @Configuration
class to configure additional Bucket and cache3 cache, as follows:
@Configuration(proxyBeanMethods = false)
public class CouchbaseCacheConfiguration {
private final Cluster cluster;
public CouchbaseCacheConfiguration(Cluster cluster) {
this.cluster = cluster;
}
@Bean
public Bucket anotherBucket() {
return this.cluster.openBucket("another", "secret");
}
@Bean
public CacheManagerCustomizer<CouchbaseCacheManager> cacheManagerCustomizer() {
return c -> {
c.prepareCache("cache3", CacheBuilder.newInstance(anotherBucket())
.withExpiration(2));
};
}
}
This sample configuration reused by automatically configuring created Cluster.
Redis
If Redis is available and configured automatically configures RedisCacheManager
. You can set spring.cache.cache-names
create additional cache at startup property, and you can use spring.cache.redis.*
the properties to configure caching default values. For example, the following configuration and create cache1 cache2 cache life time of 10 minutes:
spring.cache.cache-names=cache1,cache2
spring.cache.redis.time-to-live=600000
By default, it adds a prefix key, so that, if two separate cache using the same key, the key Redis not overlap, does not return an invalid value. If you create your own RedisCacheManager
, we strongly recommend keeping this setting enabled.
You can add your own RedisCacheConfiguration
to fully control configuration @Bean. If you want to customize serialization strategy, which would be useful.
Caffeine
Caffeine is a Guava
cache of Java 8 rewrite, which replaces the support of Guava. Caffeine, if present, is CaffeineCacheManager
configured automatically (by the spring-boot-starter-cache
provided initiator). Cache at startup can be provided spring.cache.cache-names
to create a property, and can be customized by one of the following (in the order indicated):
- Cache specification by the
spring.cache.caffeine.spec
definition of - It defines a
com.github.benmanes.caffeine.cache.CaffeineSpec
bean - It defines a
com.github.benmanes.caffeine.cache.Caffeine
bean
For example, the following configuration and create cache1 cache2 maximum cache size of 500, survival time of 10 minutes
spring.cache.cache-names=cache1,cache2
spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s
If you define a com.github.benmanes.caffeine.cache.CacheLoader
bean, and it will automatically CaffeineCacheManager
associate. Because CacheLoader
will be associated with all Cache Cache Manager, it must be defined as CacheLoader<Object, Object>
. Automatic configuration ignores any other common type.
Simple
If you can not find other providers, the configuration uses ConcurrentHashMap
a simple implementation of memory as a cache. If there is no cache library in your application, then this is the default setting. By default, the cache will be created as needed, but you can set cache-names
to limit the list of available cache properties. For example, if only cache1 and cache2 cache, cache-names press set the properties shown below:
spring.cache.cache-names=cache1,cache2
If you do, and your application uses a cache that is not listed, then it will fail at runtime when needed the cache, but does not fail at startup. This is similar to when using the cache undeclared "real" Cache provider behavior.
None
When the configuration is present @EnableCaching
, it will be desirable to use a suitable cache configuration. If required in certain circumstances disable the cache altogether specify the none
cache type to achieve a no-op, as shown in the following example:
spring.cache.type=none