EhCache is a pure Java in-process caching framework, with fast and lean features, and is the default CacheProvider in Hibernate.
ehcache provides a variety of caching strategies, mainly divided into memory and disk levels, so there is no need to worry about capacity issues.
spring-boot is a fast integration framework designed to simplify the initial construction and development process of new Spring applications. The framework uses a specific way to configure it, so that developers no longer need to define boilerplate configurations.
Since spring-boot does not require any boilerplate configuration files, spring-boot will be slightly different when integrating some other frameworks.
1.spring-boot is a framework for jar packages managed through maven. The dependencies required for integrating ehcache are as follows
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId></dependency><dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version></dependency>
The specific pom.xml file is as follows
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.lclc.boot</groupId> <artifactId>boot-cache</artifactId> <version>0.0.1-SNAPSHOT</version> <!-- Inherit defaults from Spring Boot --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.1.3.RELEASE</version> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>17.0</version> </dependency> <dependency> <groupId>org.sspringframework</groupId> <artifactId>spring-context-support</artifactId> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache</artifactId> <version>2.8.3</version> </dependency> </dependencies> <dependencyManagement> <dependencies> </dependencies> </dependencies> </dependencies> </dependencies> </dependencies> </dependencies> </dependencies> <build> <plugins> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> <snapshots> <enabled>true</enabled> </snapshots> </repository> <repository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </repository> </repository> </repository> <pluginRepository> <pluginRepository> <id>spring-snapshots</id> <url>http://repo.spring.io/snapshot</url> </pluginRepository> <pluginRepository> <id>spring-milestones</id> <url>http://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories></project>
2. Using ehcache, we need an ehcache.xml to define some cache attributes.
<?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 eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" /> <cache name="demo" eternal="false" maxElementsInMemory="100" overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0" timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU" /></ehcache>
Explain the tags in this xml file.
(1).diskStore: is the cache path, ehcache is divided into two levels: memory and disk. This property defines the cache location of the disk. The parameters are explained as follows:
user.home user home directory user.dir user current working directory java.io.tmpdir default temporary file path
(2).defaultCache: The default cache policy. When ehcache cannot find the defined cache, this cache policy will be used. Only one can be defined.
(3).cache: Custom cache policy, a custom cache policy. The parameters are explained as follows:
Properties of cache element:
name: cache name
maxElementsInMemory: Maximum number of cached objects in memory
maxElementsOnDisk: The maximum number of cached objects in the hard disk. If it is 0, it means infinity
eternal: true means that the object never expires. At this time, the timeToIdleSeconds and timeToLiveSeconds properties will be ignored, and the default is false
overflowToDisk: true means that when the number of objects cached in the memory reaches the maxElementsInMemory limit, the overflowed objects will be written to the hard disk cache. Note: If the cached object is to be written to the hard disk, the object must implement the Serializable interface.
diskSpoolBufferSizeMB: disk cache size, default is 30MB. Each cache should have its own cache area.
diskPersistent: Whether to cache virtual machine restart data during the data
diskExpiryThreadIntervalSeconds: Disk failure thread running time interval, default is 120 seconds
timeToIdleSeconds: Sets the maximum time to allow the object to be idle, in seconds. When the object has been accessed for the last time, if the timeToIdleSeconds property value exceeds the timeToIdleSeconds property value, the object will expire and EHCache will clear it from the cache. This property is only valid if the eternal property is false. If the property value is 0, it means that the object can be idle indefinitely
timeToLiveSeconds: Sets the maximum time the object allows to exist in the cache, in seconds. When the object has been stored in the cache, if the time in the cache exceeds the timeToLiveSeconds property value, the object will expire and EHCache will clear it from the cache. This property is only valid if the eternal property is false. If the property value is 0, it means that the object can exist in the cache indefinitely. timeToLiveSeconds must be greater than the timeToIdleSeconds property to make sense
memoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache will clean up memory according to the specified policy. Optional policies are: LRU (latest recently used, default policy), FIFO (first in, first out), and LFU (minimum number of visits).
3. Expose the ehcache manager to the spring context container.
@Configuration// The annotation starts the cache @EnableCachingpublic class CacheConfiguration { /* * ehcache Main manager*/ @Bean(name = "appEhCacheCacheManager") public EhCacheCacheManager ehCacheCacheManager(EhCacheManagerFactoryBean bean){ return new EhCacheCacheManager (bean.getObject ()); } /* * According to the settings of shared or not, Spring creates an ehcache base through CacheManager.create() or new CacheManager() respectively. */ @Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean(){ EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); cacheManagerFactoryBean.setConfigLocation (new ClassPathResource ("conf/ehcache-app.xml")); cacheManagerFactoryBean.setShared (true); return cacheManagerFactoryBean; }}@Configuration: Annotated for spring-boot, mainly annotated as a configuration class, and priority is given to scanning.
@Bean: Add bean to the spring container.
All configurations are done so far, and integrating the framework through spring-boot is that simple.
4. Use ehcache
Using ehcache is mainly through the spring cache mechanism. We have implemented the spring cache mechanism using ehcache, so we can use the spring cache mechanism completely in terms of use.
A few notes are involved:
@Cacheable: Responsible for adding the return value of the method to the cache, parameter 3
@CacheEvict: Responsible for clearing cache, parameter 4
Parameter explanation:
value: The cache location name cannot be empty. If EHCache is used, it is the name of the cache declared in ehcache.xml
key: The cached key, default is empty, which means the parameter type and parameter value of the method used as the key, and supports SpEL
condition: Trigger condition, only if the condition is met will be added to the cache. The default is empty, which means that all of them are added to the cache and supports SpEL
allEntries: CacheEvict parameter, true means clearing all caches in the value, default is false
Without further ado, just upload the code:
@Servicepublic class CacheDemoServiceImpl implements CacheDemoService { /** * Cache key */ public static final String THING_ALL_KEY = "/"thing_all/""; /** * The value attribute indicates which cache policy to use. The cache policy is in ehcache.xml */ public static final String DEMO_CACHE_NAME = "demo"; @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY) @Override public void create(Thing thing){ Long id = getNextId (); thing.setId (id); data.put (id, thing); } @Cacheable(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'") @Override public Things findById(Long id){ System.err.println ("No cache!" + id); return data.get (id); } @Cacheable(value = DEMO_CACHE_NAME,key = THING_ALL_KEY) @Override public List<Thing> findAll(){ return Lists.newArrayList (data.values ()); } @Override @CachePut(value = DEMO_CACHE_NAME,key = "#thing.getId()+'thing'") @CacheEvict(value = DEMO_CACHE_NAME,key = THING_ALL_KEY) public What update(Thing thing){ System.out.println (thing); data.put (thing.getId (), thing); return thing; } @CacheEvict(value = DEMO_CACHE_NAME) @Override public void delete(Long id){ data.remove (id); }}5. You only need to annotate on the service layer method through annotations and you can use the cache, store the cache on find**, and clear the cache on delete** and update**.
Summarize
The above is the method of spring-boot integrating ehcache to implement the caching mechanism introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!