20191127 Spring Boot official document learning (4.12)

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 @EnableCachingcaching 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 computePiDecimalbefore, the abstract will be piDecimalslooking 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-namescustomizing 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.CacheManagerthe abstract interface implementation.

If you have not defined the type CacheManageror CacheResolverand 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):

  1. Generic
  2. JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
  3. ehcache 2.x
  4. Hazelcast
  5. Infinispan
  6. Couchbase
  7. Redis
  8. Caffeine
  9. Simple
  10. None

You can be set spring.cache.typeto 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-cachestarter quickly add basic cache dependency. Starter brought in spring-context-support. If you manually add dependencies, you must include spring-context-supportin order to use JCache, EhCache 2.xor Caffeinesupport.

If Spring Boot automatically configured CacheManager, you can achieve through an open CacheManagerCustomizerinterface bean, further adjustments to its configuration before fully initialized. The following example sets a flag indicating that should nullthe 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 @Orderor Orderedsort them.

Generic

If context defines at least a org.springframework.cache.Cachebean, the generic cache. CacheManagerThe 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 JCacheCacheManagerby the spring-boot-starter-cacheprovided "launcher." Compatible with a variety of libraries available, Spring Boot to Ehcache 3, Hazelcastand Infinispanprovides 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 HazelcastInstanceis available, unless specified spring.cache.jcache.configattribute, 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-namesto create a cache properties. If you define a custom javax.cache.configuration.Configurationbean, then it is used to customize them.
  • Using CacheManagerreferences to call org.springframework.boot.autoconfigure.cache.JCacheManagerCustomizerthe bean is fully customizable.

If you define a standard javax.cache.CacheManagerbean, it automatically packaged in org.springframework.cache.CacheManagerabstract desired implementation. No longer its application customization.

ehcache 2.x

If you can find the class named in the root directory path of ehcache.xmlthe file is used EhCache2.x. If found EhCache 2.x, use the spring-boot-starter-cache"starter" provided EhCacheCacheManagerto 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 CacheManagerin.

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-namesto create a cache properties. If you define a custom ConfigurationBuilderbean, 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-cacheimplementation is available, and you have configured Couchbase, it will be automatically configured CouchbaseCacheManager. By setting the spring.cache.cache-namesproperty, 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 @Configurationclass 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-namescreate 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 RedisCacheConfigurationto fully control configuration @Bean. If you want to customize serialization strategy, which would be useful.

Caffeine

Caffeine is a Guavacache of Java 8 rewrite, which replaces the support of Guava. Caffeine, if present, is CaffeineCacheManagerconfigured automatically (by the spring-boot-starter-cacheprovided initiator). Cache at startup can be provided spring.cache.cache-namesto create a property, and can be customized by one of the following (in the order indicated):

  1. Cache specification by the spring.cache.caffeine.specdefinition of
  2. It defines a com.github.benmanes.caffeine.cache.CaffeineSpecbean
  3. It defines a com.github.benmanes.caffeine.cache.Caffeinebean

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.CacheLoaderbean, and it will automatically CaffeineCacheManagerassociate. Because CacheLoaderwill 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 ConcurrentHashMapa 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-namesto 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 nonecache type to achieve a no-op, as shown in the following example:

spring.cache.type=none

Guess you like

Origin www.cnblogs.com/huangwenjie/p/11941753.html