Springboot integrates ehcache to implement caching. springbootehcache

Source: Internet
Author: User

Springboot integrates ehcache to implement caching. springbootehcache

EhCache is a pure Java in-process cache framework, which features fast and efficient. It is the default CacheProvider in Hibernate.

Ehcache provides a variety of cache policies, mainly divided into memory and disk levels, so you do not need to worry about capacity issues.

Spring-boot is a rapid integration framework designed to simplify the initial setup and development process of new Spring applications. The framework uses a specific method for configuration, so that developers no longer need to define the configuration of the template.

Because spring-boot does not require any sample configuration files, it is slightly different when spring-boot integrates some other frameworks.

1. spring-boot is a jar package framework managed by 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.springframework</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>  </dependencyManagement>  <build>    <plugins>      <plugin>        <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>  </repositories>  <pluginRepositories>    <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. To use ehcache, we need an ehcache. xml file 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>

Describe the labels in the xml file.

(1). diskStore: the cache path. ehcache is divided into two levels: memory and disk. This attribute defines the disk cache location. The parameters are described as follows:

  1. User. home-user main directory
  2. User. dir-current working directory of the user
  3. Java. io. tmpdir-default temporary file path

(2). defaultCache: the default cache policy. This policy is used when ehcache cannot find the defined cache. Only one can be defined.

(3). cache: a custom cache Policy. The parameters are described as follows:

  1. Attributes of the cache element:
  2. Name: cache name
  3. MaxElementsInMemory: Maximum number of cached objects in memory
  4. MaxElementsOnDisk: Maximum number of cached objects in a hard disk. If it is 0, it indicates infinity.
  5. Eternal: true indicates that the object never expires. The timeToIdleSeconds and timeToLiveSeconds attributes are ignored. The default value is false.
  6. OverflowToDisk: true indicates that when the number of objects in the memory cache reaches the maxElementsInMemory limit, the overflow 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.
  7. DiskSpoolBufferSizeMB: disk cache size. The default value is 30 MB. Each Cache should have its own Cache zone.
  8. DiskPersistent: Indicates whether to cache data during VM restart.
  9. DiskExpiryThreadIntervalSeconds: Specifies the interval for running the disk failure thread. The default value is 120 seconds.
  10. TimeToIdleSeconds: sets the maximum time allowed for idle objects, in seconds. After the last access, if the idle time of the object exceeds the timeToIdleSeconds attribute value, the object will expire and EHCache will clear it from the cache. This attribute is valid only when the eternal attribute is false. If the property value is 0, the object can be idle for an indefinite period of time.
  11. TimeToLiveSeconds: sets the maximum time allowed for an object to exist in the cache, in seconds. After an object is stored in the cache, if the cache time exceeds the timeToLiveSeconds attribute value, the object will expire and EHCache will clear it from the cache. This attribute is valid only when the eternal attribute is false. If the value of this attribute is 0, it indicates that the object can exist in the cache indefinitely. TimeToLiveSeconds must be greater than the timeToIdleSeconds attribute.
  12. MemoryStoreEvictionPolicy: When the maxElementsInMemory limit is reached, Ehcache clears the memory according to the specified policy. Optional policies include LRU (least recently used, default policy), FIFO (first-in-first-out), and LFU (minimum number of visits ).

SpringBoot supports many caching Methods: redis, guava, ehcahe, and jcache.

Differences between redis and ehcache:

Redis: it is an independent running program. It must be installed separately and then operated using Jedis in Java. Because it is independent, if you write a unit test program, put some data in Redis, and then write another program to get the data, you can get the data .,
Ehcache: Unlike Redis, it is bound to a java program. If a java program is alive, it is alive. For example, if you write an independent program to put data, and then write another independent program to get data, you will not be able to get the data. Data can only be obtained in an independent program.

3. Expose the ehcache manager to the context container of spring,

@ Configuration // indicates that the cache @ EnableCachingpublic class CacheConfiguration {/** main ehcache manager */@ Bean (name = "appEhCacheCacheManager") public EhCacheCacheManager (elastic bean) is enabled) {return new EhCacheCacheManager (bean. getObject ();}/** set the shared or not. Spring uses CacheManager. create () or new CacheManager () to create an ehcache base. * // @ Bean public EhCacheManagerFactoryBean ehCacheManagerFactoryBean () {EhCacheManagerFactoryBean cacheManagerFactoryBean = new EhCacheManagerFactoryBean (); cacheManagerFactoryBean. setConfigLocation (new ClassPathResource ("conf/ehcache-app.xml"); cacheManagerFactoryBean. setShared (true); return cacheManagerFactoryBean ;}}

@ Configuration: annotation for spring-boot, which is marked as a Configuration class and scanned first.

@ Bean: Add bean to the spring container.

So far, all the configurations have been completed, and the integration framework through spring-boot is so simple.

4. Use ehcache

The use of ehcache is mainly implemented through the spring cache mechanism. above we implemented the spring Cache Mechanism Using ehcache, so we can simply use the spring cache mechanism in terms of usage.

Several annotations are involved:

@ Cacheable: adds the return value of the method to the cache. Parameter 3
@ CacheEvict: clears the cache. Parameter 4

Parameter description:

  1. Value: the cache location name. It cannot be blank. If EHCache is used, it is the name of the cache declared in ehcache. xml.
  2. Key: the cached key. It is null by default. It indicates that the parameter type and value of the method are used as the key. SpEL is supported.
  3. Condition: the trigger condition. It is added to the cache only when the condition is met. The default value is null, indicating that all the conditions are added to the cache. SpEL is supported.
  4. AllEntries: CacheEvict parameter. true indicates to clear all caches in value. The default value is false.

Not to mention, go directly to the Code:

@ Servicepublic class CacheDemoServiceImpl implements CacheDemoService {/*** cached key */public static final String THING_ALL_KEY = "\" thing_all \""; /*** The value Attribute indicates which cache policy is used. The cache policy is stored 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) {Long id = getNextId (); thing. setId (id); data. put (id, Thing) ;}@ Cacheable (value = DEMO_CACHE_NAME, key = "# thing. getId () + 'thing '") @ Override public thing 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 thing update (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 the method on the service layer through the annotation to use the cache, store the cache on find **, and clear the cache on delete ** and update.

Detailed description of Cache annotations

@ CacheConfig: used to configure some common cache configurations used in this class. @ CacheConfig (cacheNames = "users"): The content returned when this data access object is configured will be stored in the cache object named users. We can also skip this annotation, you can directly configure the cache set name by @ Cacheable.

@ Cacheable: the return value of the findByName function is added to the cache. At the same time, the query will first be obtained from the cache, and if it does not exist, then initiate access to the database. The annotation mainly includes the following parameters:

  1. Value and cacheNames: two equivalent parameters (cacheNames is added to Spring 4 and serves as the alias of value) are used to specify the cache storage set name. Since @ CacheConfig is added to Spring 4, the value Attribute originally required in Spring 3 becomes a non-required item.
  2. Key: the key value of the cached object stored in the Map set. It is not required. By default, all parameters of the function are combined as the key value. If you configure it yourself, use the SpEL expression, for example: @ Cacheable (key = "# p0"): use the first parameter of the function as the cached key value,

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.