Skip to content Skip to sidebar Skip to footer

How to Read Cache Through Properties File

The Spring Framework provides support for transparently adding caching to an application. At its core, the abstraction applies caching to methods, thus reducing the number of executions based on the information available in the enshroud. The caching logic is applied transparently, without any interference to the invoker. Spring Kick machine-configures the enshroud infrastructure every bit long as caching support is enabled via the @EnableCaching notation.

In a nutshell, adding caching to an functioning of your service is as easy equally adding the relevant notation to its method, as shown in the following case:

This instance demonstrates the use of caching on a potentially costly performance. Before invoking computePiDecimal, the abstraction looks for an entry in the piDecimals cache that matches the i statement. If an entry is found, the content in the enshroud is immediately returned to the caller, and the method is not invoked. Otherwise, the method is invoked, and the cache is updated before returning the value.

If you lot do non add any specific cache library, Bound Kick automobile-configures a simple provider that uses concurrent maps in retentivity. When a cache is required (such as piDecimals in the preceding case), this provider creates it for you. The elementary provider is not really recommended for production usage, but it is great for getting started and making certain that you understand the features. When yous have made up your mind about the cache provider to use, please make sure to read its documentation to effigy out how to configure the caches that your awarding uses. Nearly all providers require you to explicitly configure every cache that you utilise in the awarding. Some offer a fashion to customize the default caches defined by the spring.enshroud.cache-names property.

33.1 Supported Enshroud Providers

The cache abstraction does not provide an bodily store and relies on abstraction materialized by the org.springframework.cache.Cache and org.springframework.cache.CacheManager interfaces.

If y'all have not defined a bean of type CacheManager or a CacheResolver named cacheResolver (run across CachingConfigurer), Spring Kicking tries to detect the following providers (in the indicated lodge):

  1. Generic
  2. JCache (JSR-107) (EhCache iii, Hazelcast, Infinispan, and others)
  3. EhCache 2.10
  4. Hazelcast
  5. Infinispan
  6. Couchbase
  7. Redis
  8. Caffeine
  9. Simple
[Tip] Tip

It is also possible to strength a particular cache provider by setting the spring.enshroud.type belongings. Use this holding if you need to disable caching altogether in certain environs (such equally tests).

[Tip] Tip

Use the spring-boot-starter-cache "Starter" to quickly add basic caching dependencies. The starter brings in spring-context-back up. If yous add dependencies manually, you must include jump-context-support in order to use the JCache, EhCache two.x, or Guava support.

If the CacheManager is motorcar-configured by Leap Kicking, you lot can further melody its configuration before it is fully initialized by exposing a bean that implements the CacheManagerCustomizer interface. The following case sets a flag to say that zero values should be passed down to the underlying map:

                      @Bean                    public          CacheManagerCustomizer<ConcurrentMapCacheManager> cacheManagerCustomizer() {          return          new          CacheManagerCustomizer<ConcurrentMapCacheManager>() {                      @Override                    public          void          customize(ConcurrentMapCacheManager cacheManager) { 			cacheManager.setAllowNullValues(simulated); 		} 	}; }
[Note] Note

In the preceding example, an auto-configured ConcurrentMapCacheManager is expected. If that is non the case (either yous provided your own config or a dissimilar cache provider was auto-configured), the customizer is not invoked at all. Y'all can have as many customizers every bit you want, and y'all can also guild them by using @Club or Ordered.

33.1.1 Generic

Generic caching is used if the context defines at to the lowest degree one org.springframework.cache.Cache bean. A CacheManager wrapping all beans of that type is created.

33.1.ii JCache (JSR-107)

JCache is bootstrapped through the presence of a javax.cache.spi.CachingProvider on the classpath (that is, a JSR-107 compliant caching library exists on the classpath), and the JCacheCacheManager is provided past the leap-boot-starter-enshroud "Starter". Various compliant libraries are bachelor, and Spring Boot provides dependency direction for Ehcache iii, Hazelcast, and Infinispan. Whatever other compliant library tin can exist added as well.

It might happen that more than one provider is present, in which case the provider must exist explicitly specified. Even if the JSR-107 standard does not enforce a standardized way to define the location of the configuration file, Spring Kicking does its best to suit setting a enshroud with implementation details, as shown in the following case:

                        spring.cache.jcache.provider=com.acme.MyCachingProvider            spring.cache.jcache.config=classpath:pinnacle.xml
[Note] Note

When a cache library offers both a native implementation and JSR-107 support, Bound Kicking prefers the JSR-107 support, so that the same features are available if you switch to a different JSR-107 implementation.

[Tip] Tip

Jump Boot has full general support for Hazelcast. If a single HazelcastInstance is available, information technology is automatically reused for the CacheManager likewise, unless the leap.cache.jcache.config property is specified.

At that place are two means to customize the underlying javax.cache.cacheManager:

  • Caches can be created on startup past setting the bound.enshroud.cache-names property. If a custom javax.cache.configuration.Configuration edible bean is defined, it is used to customize them.
  • org.springframework.kicking.autoconfigure.cache.JCacheManagerCustomizer beans are invoked with the reference of the CacheManager for full customization.
[Tip] Tip

If a standard javax.cache.CacheManager edible bean is defined, it is wrapped automatically in an org.springframework.cache.CacheManager implementation that the brainchild expects. No farther customization is applied to it.

33.1.iii EhCache 2.ten

EhCache two.x is used if a file named ehcache.xml can be found at the root of the classpath. If EhCache ii.x is plant, the EhCacheCacheManager provided by the spring-kick-starter-enshroud "Starter" is used to bootstrap the cache manager. An alternate configuration file tin be provided too, as shown in the following example:

            spring.cache.ehcache.config=classpath:config/another-config.xml

33.1.4 Hazelcast

Jump Kick has general support for Hazelcast. If a HazelcastInstance has been auto-configured, it is automatically wrapped in a CacheManager.

33.1.5 Infinispan

Infinispan has no default configuration file location, so it must be specified explicitly. Otherwise, the default bootstrap is used.

            spring.cache.infinispan.config=infinispan.xml

Caches can be created on startup by setting the spring.enshroud.cache-names holding. If a custom ConfigurationBuilder bean is defined, it is used to customize the caches.

[Note] Note

The support of Infinispan in Leap Boot is restricted to the embedded style and is quite basic. If you want more than options, you lot should use the official Infinispan Spring Kick starter instead. See Infinispan'south documentation for more details.

33.1.half-dozen Couchbase

If the Couchbase Coffee client and the couchbase-spring-cache implementation are available and Couchbase is configured, a CouchbaseCacheManager is automobile-configured. It is also possible to create boosted caches on startup past setting the jump.cache.cache-names property. These caches operate on the Saucepan that was auto-configured. You can also create additional caches on another Bucket by using the customizer. Assume you need two caches (cache1 and cache2) on the "principal" Bucket and 1 (cache3) cache with a custom time to live of 2 seconds on the "some other" Bucket. Y'all tin create the first two caches through configuration, every bit follows:

            spring.enshroud.cache-names=cache1,cache2

And so yous can define a @Configuration class to configure the extra Bucket and the cache3 cache, equally follows:

                          @Configuration                        public            form            CouchbaseCacheConfiguration {            private            final            Cluster cluster;            public            CouchbaseCacheConfiguration(Cluster cluster) {            this.cluster = cluster; 	}                          @Bean                        public            Bucket anotherBucket() {            render            this.cluster.openBucket("another",            "secret"); 	}                          @Bean                        public            CacheManagerCustomizer<CouchbaseCacheManager> cacheManagerCustomizer() {            return            c -> { 			c.prepareCache("cache3", CacheBuilder.newInstance(anotherBucket()) 					.withExpiration(2)); 		}; 	}  }

This sample configuration reuses the Cluster that was created through auto-configuration.

33.1.vii Redis

If Redis is available and configured, a RedisCacheManager is auto-configured. Information technology is possible to create additional caches on startup by setting the spring.cache.cache-names property and cache defaults tin can exist configured by using spring.enshroud.redis.* backdrop. For instance, the post-obit configuration creates cache1 and cache2 caches with a time to alive of 10 minutes:

            bound.cache.cache-names=cache1,cache2            spring.enshroud.redis.fourth dimension-to-alive=600000
[Note] Note

Past default, a key prefix is added and so that, if 2 divide caches use the same cardinal, Redis does not have overlapping keys and cannot render invalid values. We strongly recommend keeping this setting enabled if you create your own RedisCacheManager.

[Tip] Tip

You can accept full control of the configuration by adding a RedisCacheConfiguration @Bean of your own. This tin can be useful if you're looking for customizing the serialization strategy.

33.i.viii Caffeine

Caffeine is a Java viii rewrite of Guava'due south enshroud that supersedes support for Guava. If Caffeine is present, a CaffeineCacheManager (provided past the spring-boot-starter-enshroud "Starter") is machine-configured. Caches tin can be created on startup past setting the spring.cache.cache-names holding and can exist customized by ane of the post-obit (in the indicated gild):

  1. A cache spec defined by spring.cache.caffeine.spec
  2. A com.github.benmanes.caffeine.enshroud.CaffeineSpec bean is defined
  3. A com.github.benmanes.caffeine.enshroud.Caffeine bean is defined

For instance, the post-obit configuration creates cache1 and cache2 caches with a maximum size of 500 and a fourth dimension to live of 10 minutes

            spring.cache.cache-names=cache1,cache2            spring.cache.caffeine.spec=maximumSize=500,expireAfterAccess=600s

If a com.github.benmanes.caffeine.cache.CacheLoader edible bean is defined, it is automatically associated to the CaffeineCacheManager. Since the CacheLoader is going to be associated with all caches managed by the cache manager, it must be defined as CacheLoader<Object, Object>. The auto-configuration ignores any other generic type.

33.1.nine Elementary

If none of the other providers tin can be found, a simple implementation using a ConcurrentHashMap as the enshroud shop is configured. This is the default if no caching library is present in your application. By default, caches are created as needed, but you tin restrict the listing of available caches by setting the cache-names holding. For instance, if you want but cache1 and cache2 caches, set the cache-names property as follows:

            bound.enshroud.cache-names=cache1,cache2

If y'all practice so and your application uses a cache not listed, and then it fails at runtime when the cache is needed, but non on startup. This is similar to the mode the "real" cache providers behave if yous use an undeclared cache.

33.1.x None

When @EnableCaching is present in your configuration, a suitable enshroud configuration is expected as well. If you need to disable caching altogether in certain environments, force the cache type to none to utilize a no-op implementation, equally shown in the following example:

            bound.cache.blazon=none

hayeseimstand53.blogspot.com

Source: https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-caching.html

Post a Comment for "How to Read Cache Through Properties File"