This is the fifth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

Author: Tom brother wechat public account: Micro technology

Spring Boot is a major microservices framework with a mature community ecology. Market widely used, in order to facilitate everyone, organizing a spring-based boot used middleware introduction to quickly integrate series manual, involving the RPC, caching, message queues, depots table, registry, common open source components, such as distributed configuration about dozens of article, will open up in succession, the students are interested in, please attention & collection in advance

Ehcache is introduced

EhCache, developed from Hibernate, is a pure Java in-process caching framework with fast and lean features. Ehcache is a widely used open source Java distributed cache. Targeted at generic caches, Java EE, and lightweight containers. It features memory and disk storage, cache loaders, cache extensions, cache exception handlers, a GZIP cache servlet filter, support for REST and SOAP apis, and more.

Main features:

  • Fast and simple

  • Multiple caching strategies

  • There are two levels of cached data: memory and disk, so there is no need to worry about capacity

  • The cached data will be written into the disk during the VM restart

  • Distributed caching can be done through RMI, pluggable apis, etc

  • A listening interface with a cache and cache manager

  • Support for multiple cache manager instances, as well as multiple cache regions for one instance

  • Provides Hibernate caching implementation

Show me the code


Add an Ehcache dependency to the pom.xml file

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

Copy the code

There is no need to configure version. The SpringBoot root POM already specifies the version number.

Configuration file:

Configure the ehcache parameters in the application. Yaml configuration file as follows:

spring:
  application:
    name: spring-boot-bulking-ehcache

  cache:
    type: ehcache
    ehcache:
      config: classpath:/ehcache.xml

Copy the code

Spring.cache. type specifies which type of cache the Spring framework uses, because the Spring framework provides a variety of caches to choose from.

Add Ehcache configuration:

In the SRC /main/resources directory, create the ehcache. XML configuration file as follows:

<ehcache name="test">
    <diskStore path="java.io.tmpdir"/>
    <defaultCache
            maxEntriesLocalHeap="1000"
            eternal="false"
            timeToIdleSeconds="300"
            timeToLiveSeconds="600"
            overflowToDisk="true"
            memoryStoreEvictionPolicy="LRU">
    </defaultCache>
    <cache name="userCache"
           maxEntriesLocalHeap="200"
           eternal="false"
           timeToIdleSeconds="300"
           timeToLiveSeconds="600"
           overflowToDisk="true">
    </cache>
</ehcache>

Copy the code

Parameter Meaning:

  • DiskStore: Indicates the disk cache location

  • Name: Indicates the cache name

  • MaxElementsInMemory: Maximum number of cache objects in memory

  • MaxElementsOnDisk: Indicates the maximum number of cache objects on the disk. Zero indicates infinity

  • Eternal: true means that the object never expires, and the timeToIdleSeconds and timeToLiveSeconds are ignored. The default is false

  • TimeToIdleSeconds: Sets the maximum amount of time, in seconds, an object is allowed to be idle. If the object has been idle for more than the timeToIdleSeconds value since it was last accessed, the object will expire and EHCache will clear it from the cache. This attribute is valid only if the eternal attribute is false. A value of 0 indicates that the object can remain idle indefinitely

  • TimeToLiveSeconds: Sets the maximum amount of time, in seconds, an object is allowed to exist in the cache. If an object has been in the cache for more than the timeToLiveSeconds value since it was placed in the cache, the object will expire and EHCache will clear it from the cache. This attribute is valid only if the eternal attribute is false. A value of 0 indicates that the object can remain in the cache indefinitely. TimeToLiveSeconds must be greater than the timeToIdleSeconds attribute to be meaningful

  • OverflowToDisk: When the number of objects in memory reaches maxElementsInMemory, Ehcache writes the objects to disk.

  • DiskSpoolBufferSizeMB: specifies the size of the disk cache. The default value is 30MB. Each Cache should have its own Cache area.

  • DiskPersistent: specifies whether to cache vm restart data.

  • DiskExpiryThreadIntervalSeconds: disk failure thread running time interval, the default is 120 seconds.

  • MemoryStoreEvictionPolicy: when maxElementsInMemory limit is reached, Ehcache will be based on the specified strategies to clear the memory. The default policy is LRU (least recently used). You can set it to FIFO (first in, first out) or LFU (less used).

  • ClearOnFlush: specifies whether to flush the memory when the memory quantity reaches the maximum.

Enable cache:

The entry startup class is added with the annotation @enablecaching

@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration. Class}) @ EnableCaching / / open the cache, Public class StartApplication {public static void main(String[] args) { SpringApplication.run(StartApplication.class, args); }}Copy the code

Cache service usage:

@Component @CacheConfig(cacheNames = "userCache") public class UserService { @Cacheable(key = "#id") public User GetUserById (Long ID) {system.out.println (" no value in cache "); User User = User. The builder (). The id (id). The userName (" ice cream (" + id + ") "). The age (18), address (" hangzhou "). The build (); return user; } @cacheput (key = "#user.id") public user updateUser(user user) {user.setUsername (" ice (new name) "); return user; } @cacheevict (key =" #id") public void deleteById(Long id) {system.out.println ("db delete data, id=" + id); }}Copy the code
  • CacheConfig applies to a class and describes the cache name used by all methods in that class. It is also possible to configure the name directly in the cached annotation on the specific method without using the annotation

  • @cacheable is used on query methods to cache the return value of a method. By default, the cached key is the method argument, and the cached value is the method return value

  • The @cachePUT update operation. When data in the database is updated, data in the cache is also updated. Using this annotation, the return value of a method is automatically updated to an existing key

  • The @cacheEVict delete operation. When data in the database is deleted, the associated cache data is automatically cleared.

In addition to annotating the decoupended operational cache with @cacheable, @cachePUT, etc., you can also manually operate the cache using CacheManager display.

CacheManager

Spring defines the CacheManager and Cache interfaces to unify different caching technologies. The CacheManager is an abstract interface for various caching technologies provided by Spring. The Cache interface includes Cache read, write, and delete operations.

For different caching technologies, different CacheManager implementations are required. Spring predefines the cacheManger implementation class of the mainstream caching framework

CacheManager describe
SimpleCacheManager Use a simple Collection to store the cache, primarily for testing purposes
ConcurrentMapCacheManager Use ConcurrentMap as the caching technique (default)
NoOpCacheManager The test
EhCacheCacheManager EhCache is used as a caching technology, which is often used in Hibernate
GuavaCacheManager Use GuavaCache from Google Guava as the caching technology
HazelcastCacheManager Use Hazelcast as a caching technique
JCacheCacheManager Use implementations of the JCache standard as caching techniques, such as Apache Commons JCS
RedisCacheManager Use Redis as caching technology
CaffeineCacheManager Use Caffeine as a caching technique

Spring the Boot interface reserved for us extension, convenient we automatically configure EhCache, Redis, Guava, ConcurrentMap cache, such as using ConcurrentMapCacheManager by default. The application. Yaml configuration file of Spring Boot is configured using the Spring. Cache prefix attribute.

For this article, we use EhCache, as shown in the following code example:

@Component public class UserCacheManager { @Resource private CacheManager cacheManager; public User getUserById(Long id) { Cache cache = cacheManager.getCache("userCache"); User user = cache.get(id, User.class); If (user == null) {system.out.println (" no value in cache "); User = user. The builder (). The id (id). The userName (" ice cream (" + id + ") "). The age (18), address (" hangzhou "). The build (); cache.put(id, user); } return user; } public User updateUser(User User) {user.setUsername (" ice cream (new name) "); Cache cache = cacheManager.getCache("userCache"); cache.put(user.getId(), user); return user; } public void deleteById(Long id) { Cache cache = cacheManager.getCache("userCache"); cache.evict(id); Println ("db delete data, id=" + id); }}Copy the code

Demo code address

https://github.com/aalansehaiyang/spring-boot-bulking modules: spring - the boot - bulking - ehcacheCopy the code

Author introduction: Tom brother, computer graduate student, recruited into Ali, P7 technology expert, patent, CSDN blog expert. In charge of e-commerce transactions, community fresh, traffic marketing, Internet finance and other businesses, many years of first-line team management experience