SpringBoot2 integrates Ehcache components to realize lightweight cache management

  • 2021-09-20 20:44:56
  • OfStack

Directory 1. Introduction to Ehcache Cache Hibernate Cache
EhCache Cache Features
Compare Redis cache
2. Integrate the SpringBoot framework
1. Core dependency 2. Load configuration
3. Detailed configuration 3. Annotation usage 4. Source code address

1. Introduction to Ehcache Cache

Hibernate cache

Brief introduction of Hibernate level 3 cache mechanism:

Level 1 cache: 1 block of cache space is allocated based on Session level to cache accessed object information. Session automatically clears the cache when it is shut down.

Level 2 cache: It is an SessionFactory object cache, which can be shared by multiple Session objects created. Level 2 cache is turned off by default. If you want to use it, you need to open it manually and rely on EhCache components.

Level 3 cache: Query cache. When the cache is configured to be turned on, it will be cached if one sql is repeatedly used to query data in a certain range.

EhCache Cache Features

Fast, simple, and provide a variety of caching strategies; There are two levels of cached data: memory and disk, so there is no need to worry about capacity; Cached data will be written to disk during the restart of the virtual machine; Distributed caching can be carried out by RMI and insertable API. Listening interface with cache and cache manager; Support multiple cache manager instances and multiple cache areas of one instance; Provide cache implementation of Hibernate;

Compare Redis cache

Ehcache: Caching directly in Jvm virtual machine is fast and efficient, which is not suitable for processing large-scale cached data. In distributed environment, cached data sharing operation is complex;

Redis: As an independent cache middleware, it is very easy to use in distributed cache system, cache data sharing, effectively support a large number of data caches, and support Sentinel mode or highly available mature scheme of cluster mode;

2. Integrating the SpringBoot Framework

1. Core dependencies


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

2. Load the configuration

Basic configuration


spring:
  cache:
    ehcache:
      config: classpath:ehcache.xml

Startup class annotation


@EnableCaching
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class,args) ;
    }
}

3. Detailed explanation of configuration


<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd">

    <!--  Temporary directory for operating system cache , Write to the directory when the memory is full  -->
    <diskStore path="java.io.tmpdir"/>

    <defaultCache
            maxElementsInMemory="1000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            maxElementsOnDisk="10000000"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </defaultCache>

    <cache name="userEntity"
           maxElementsInMemory="1000"
           eternal="false"
           timeToIdleSeconds="120"
           timeToLiveSeconds="120"
           maxElementsOnDisk="10000000"
           diskExpiryThreadIntervalSeconds="120"
           memoryStoreEvictionPolicy="LRU">
        <persistence strategy="localTempSwap"/>
    </cache>
</ehcache>

Configuration parameter description

maxElementsOnDisk: The maximum number of elements that can be stored in the disk cache; eternal: Whether the object in the cache is permanently valid; timeToIdleSeconds: Used when eternal=false, the cache data is valid (in seconds), and the element is not accessed within the time period, and will be cleared; timeToLiveSeconds: Lifetime of cached data; maxElementsInMemory: The maximum number of elements that can be stored in memory. If overflowToDisk=true, the extra elements in Cache will be put into disk files. If overflowToDisk=false, the original elements in Cache will be replaced according to memoryStoreEvictionPolicy strategy; diskExpiryThreadIntervalSeconds: Disk Cache Cleanup Thread Run Interval; memoryStoreEvictionPolicy: Cache release strategy, LRU will give priority to cleaning the least used cache; localTempSwap: Persistence strategy. When the elements in heap memory or non-heap memory are full, the elements are temporarily stored on the disk and will disappear after restarting;

3. Use of annotations


@Service
public class CacheService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CacheService.class);

    @Resource
    private UserMapper userMapper ;

    @Cacheable(value="userEntity")  //  The first query accesses the database during the cache validity period 
    public UserEntity getById (Integer id){
        //  Through the log, identify whether the method is executed 
        LOGGER.info("getById..."+id);
        return userMapper.selectById(id) ;
    }

    @CacheEvict(value="userEntity",key = "#id") // The ID Data update, empty the ID Cache 
    public void updateUser(Integer id) {
        UserEntity user = new UserEntity() ;
        user.setId(id);
        user.setUserName("myCache");
        userMapper.updateById(user);
    }
}

@ Cacheable: Annotations are marked on 1 method, or on 1 class. Marking on 1 method indicates that the method supports caching. After the method is called, its return value is cached. The next time the same request parameter executes the method, the result can be directly obtained from the cache without executing the method again.

@ CacheEvict: An annotation marked on a method or class that needs to clear cached elements. When marked on 1 class, it means that the execution of all methods in it will trigger the cache clearing operation, and it can be cleared according to the specified attributes.

4. Source code address

GitHub · Address
https://github.com/cicadasmile/middle-ware-parent
GitEE · Address
https://gitee.com/cicadasmile/middle-ware-parent

The above is SpringBoot2 integration Ehcache components to achieve lightweight cache management details, more information about SpringBoot2 integration Ehcache components please pay attention to other related articles on this site!


Related articles: