Ehcache
1. Basic Introduction
EhCache is a pure Java in-process cache framework. It is fast and easy to get started, and it is the default cache provider in Hibernate.
Hibernate caching
Hibernate level 3 Caching
Level 1 cache: Allocates a cache space based on the Session level to cache information about accessed objects. The cache is automatically cleared after the Session is closed.
Level 2 cache: the SessionFactory object cache, which can be shared by multiple Session objects. Level 2 cache is disabled by default. If you want to use it, you need to manually enable it and rely on the EhCache component.
Level-3 cache: Query cache. If this cache is enabled, data in a certain range is repeatedly queried using an SQL query and cached.
EhCache features
- Fast, easy, and offers multiple caching strategies;
- There are two levels of cached data: memory and disk, without worrying about capacity;
- Cached data is written to disks during VM restart.
- Distributed caching can be implemented through RMI, pluggable API, etc.
- Listener interfaces with caches and cache managers;
- Support for multiple cache manager instances, as well as multiple cache areas for one instance;
- Provide Hibernate cache implementation;
4. Compare Redis cache
Ehcache: Cache directly in THE Jvm, which is fast and efficient. It is not suitable for processing large-scale cached data. In a distributed environment, the operation of sharing cached data is complicated.
Redis: As an independent cache middleware, it is very useful in distributed cache systems, cache data sharing, effectively support a large amount of data cache, support sentry mode, or cluster mode of highly available mature solutions;
Second, integrate 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>
Copy the code
2. Load the configuration
Basic configuration
spring:
cache:
ehcache:
config: classpath:ehcache.xml
Copy the code
Start class annotations
@EnableCaching
@SpringBootApplication
public class Application {
public static void main(String[] args) { SpringApplication.run(Application.class,args) ; }}Copy the code
3. Configuration details
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation=".. /config/ehcache.xsd">
<! A temporary directory cached by the operating system. Write to this directory when 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>
Copy the code
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 (unit: second). If the element is not accessed during the period, it will be cleared.
TimeToLiveSeconds: Indicates the survival time of cached data.
MaxElementsInMemory: The maximum number of elements that can be stored in the memory. If overflowToDisk=true, the extra elements in the Cache are added to the disk file. If overflowToDisk=false, memoryStoreEvictio is used NPolicy replaces existing Cache elements.
DiskExpiryThreadIntervalSeconds: disk cache cleaning thread running interval;
MemoryStoreEvictionPolicy: cache release strategy, LRU will clean up first at least use cache;
LocalTempSwap: A persistent policy that temporarily stores elements in the heap or non-heap memory to disk when they are full and then disappears after a restart.
Note usage
@Service
public class CacheService {
private static final Logger LOGGER = LoggerFactory.getLogger(CacheService.class);
@Resource
private UserMapper userMapper ;
@Cacheable(value="userEntity") // The database is accessed for the first time during the cache life
public UserEntity getById (Integer id){
// Log to indicate whether the method is executed
LOGGER.info("getById..."+id);
return userMapper.selectById(id) ;
}
@CacheEvict(value="userEntity",key = "#id") // Update the ID data, clear the ID cache
public void updateUser(Integer id) {
UserEntity user = new UserEntity() ;
user.setId(id);
user.setUserName("myCache"); userMapper.updateById(user); }}Copy the code
@cacheable: Annotation mark on a method, or on a class. A mark on a method indicates that the method is Cacheable, that the method is called and its return value is cached so that the next time the method is executed with the same request parameter, the result can be fetched directly from the cache without having to execute the method again.
CacheEvict: Annotation mark on a method or class that requires the cache element to be cleared. When the mark is on a class, it means that all methods in the class trigger the cache to be cleared, and can be cleared by specified attributes.
Source code address
Making address GitEE, https://github.com/cicadasmile/middle-ware-parent, https://gitee.com/cicadasmile/middle-ware-parentCopy the code