Learn Spring Boot: (21) Use EhCache to implement data caching

foreword

When querying the database multiple times affects system performance, you can consider using cache to solve the problem of new data access.
SpringBoot has provided us with automatic configuration of multiple CacheManager implementations, as long as we implement and use it.

The general system is to use EhCache first. It works in the JAVA process. It is more convenient to use it when traditional applications do not have much requirements. In distributed systems, Shiro is used to centrally manage the cache.

text

add dependencies

Add dependencies to 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>

Add cache related configuration

New ehcache.xml, add cache related parameters, I add a new cache setting named users:

<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
         updateCheck="false">
    <diskStore path="java.io.tmpdir/Tmp_EhCache"/>
    <defaultCache
            maxElementsInMemory="1000"
            maxEntriesLocalHeap="400"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="false"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"/>

    <cache
            name="users"
            maxEntriesLocalHeap="200"
            timeToLiveSeconds="600"
    />

</ehcache>

Parameter details:

  • name : The cache name.
  • maxElementsInMemory : The maximum number of caches.
  • eternal : Whether the object is permanently valid, once it is set, the timeout will not work.
  • timeToIdleSeconds : Sets the allowable idle time (unit: seconds) for an object before it expires. Only used when the internal=false object is not permanently valid, optional attribute, the default value is 0, that is, the idle time is infinite.
  • timeToLiveSeconds : Set the time the object is allowed to live before it expires (unit: seconds). The maximum time is between the creation time and the expiration time. It is only used when the internal=false object is not permanently valid. The default is 0. That is, the object's lifetime is infinite.
  • overflowToDisk : When the number of objects in memory reaches maxElementsInMemory, Ehcache will write objects to disk.
  • diskSpoolBufferSizeMB : This parameter sets the buffer size of the DiskStore (disk cache). The default is 30MB. Each Cache should have its own buffer.
  • maxElementsOnDisk : The maximum number of caches on the hard disk.
  • diskPersistent : Whether to cache virtual machine restart data, the default is false.
  • diskExpiryThreadIntervalSeconds : The running interval of the disk expiry thread, the default is 120 seconds.
  • memoryStoreEvictionPolicy : When the maxElementsInMemory limit is reached, Ehcache will clean up memory according to the specified policy. The default policy is LRU (Least Recently Used). You can set it to FIFO (first in, first out) or LFU (less used).
  • clearOnFlush : Whether to clear when the amount of memory is the largest.
  • memoryStoreEvictionPolicy : When the maxElementsInMemory limit is reached, Ehcache will clean up memory according to the specified policy. The default policy is LRU (Least Recently Used). You can set it to FIFO (first in, first out) or LFU (less used).

enable cache

  1. Specify
    in Add to the configuration file ehcache.xmlthe configuration file we set as EhCache:
spring:
  cache:
    ehcache:
      config: config/ehcache.xml # 指定 ehcache.xml 创建EhCache的缓存管理器
    type: ehcache # 指定缓存管理器
  1. Annotate the startup class to @EnableCachingenable caching.

use

When using it, it should be noted that we have configured the relevant cache configuration in the shiro cache before, and now we need to delete all the content of the shiro-related cache, otherwise the caches of the two will conflict.
Let's take shiro's service for obtaining the permission list as an example. After not using shiro-cache, you can directly add the cache here in the query.

@CacheConfig(cacheNames = "users")
public interface ShiroService {
    /**
     * 获取用户权限
     *
     * @param userId 用户ID
     * @return 权限
     */
    @Cacheable
    Set<String> getUserPermissions(long userId);

debug debug,

@Autowired
private CacheManager cacheManager;

It is found that the relevant content usersis .

Use of annotations

  • @CacheConfig: Mainly used to configure some common cache configurations that will be used in this class. Here @CacheConfig(cacheNames = "users"): the content returned in the configured data access object will be stored in the cache object named users. We can also define it directly by configuring the name of the cache set by @Cacheable without using this annotation.
  • @Cacheable: getUserPermissions(long userId)The return value of the configured function will be added to the cache. At the same time, when querying, it will be obtained from the cache first, and if it does not exist, the access to the database will be initiated. The annotation mainly has the following parameters:
    1. value, cacheNames: Two equivalent parameters (cacheNames is new in Spring 4, as an alias for value), which are used to specify the collection name of the cache storage. Due to the addition of @CacheConfig in Spring 4, the value attribute that was originally required in Spring 3 has also become a non-essential item.
    2. key: The value of the cache object stored in the Mapcollection key, not required. By default, all parameter combinations of the function are used as the key value. If you configure it yourself, you need to use SpELan expression, such as: @Cacheable(key = "#p0"): Use the first parameter of the function as the cache key value, more For details about SpEL expressions, please refer to the official documentation
    3. condition: The condition of the cached object. It is not necessary. SpEL expressions are also required. Only the content that meets the conditions of the expression @Cacheable(key = "#p0", condition = "#p0.length() < 3")will be cached.
    4. unless: Another cache condition parameter, optional, it needs to use SpEL expression. The difference conditionbetween it and the parameter is its judgment timing. The condition is judged after the function is called, so it can resultbe judged by pair.
    5. keyGenerator: Used to specify keya generator, not required. If you need to specify a custom key generator, we need to implement org.springframework.cache.interceptor.KeyGeneratorthe interface and use this parameter to specify. It should be noted that this parameter and key are mutually exclusive .
    6. cacheManager: Used to specify which cache manager to use, not required. Only need to use if there are more than one.
    7. cacheResolver: Used to specify which cache resolver to use, not required. You need org.springframework.cache.interceptor.CacheResolverto implement your own cache resolver through the interface and specify it with this parameter.

In addition to the two annotations used here, there are also the following core annotations:
* @CachePut: Configured on the function, it can be cached according to the parameter definition conditions. @CacheableThe difference is that it will actually call the function every time, so Mainly used for data addition and modification operations. Its parameters are @Cacheablesimilar. For specific functions, please refer to the analysis of @Cacheable parameters above
* @CacheEvict: Configured on functions, usually used in delete methods to remove corresponding data from the cache. In addition to the @Cacheablesame parameters, it has the following two parameters:
1. allEntries: not required, default is false. trueWhen is, all data will be removed
2. beforeInvocation: not required, default is false, data will be removed after calling the method. trueWhen is , the data is removed before the method is called.

cache configuration

In Spring Boot, the appropriate cache manager (CacheManager) is automatically configured through the @EnableCaching annotation. Spring Boot detects the cache provider according to the following order:
1. Generic
2. JCache (JSR-107)
3. EhCache 2.x
4 . Hazelcast
5. Infinispan
6. Redis
7. Guava
8. Simple

It is usually recommended to specify a cache type, which is configured in the system configuration file:

spring:
  cache:
    type: ehcache

Reference article

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325724126&siteId=291194637
Recommended