Author: ramostear www.jianshu.com/p/f4126ee58…

This article mainly introduces the data caching function of Spring Boot application based on Ehcache 3.0. In Spring Boot applications, you can use Spring Caching to quickly get around data Caching.

Next we’ll show you how to do Spring Boot caching in three steps.

1. Create a Spring Boot project

The Maven dependency files you create for your Spring Boot application should at least look like this:

<? The 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 > < the parent > < groupId > org. Springframework. Boot < / groupId > The < artifactId > spring - the boot - starter - parent < / artifactId > < version > 2.1.3. RELEASE < / version > < relativePath / > <! -- lookup parent from repository --> </parent> <groupId>com.ramostear</groupId> <artifactId>cache</artifactId> <version>0.0.1-SNAPSHOT</version> <name> Cache </name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-cache</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.ehcache</groupId> <artifactId>ehcache</artifactId> </dependency> <dependency> <groupId>javax.cache</groupId> <artifactId>cache-api</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>Copy the code

Dependency description:

  • Spring-boot-starter-cache provides caching support for Spring Boot applications

  • Ehcache provides a caching implementation of EhCache

  • Cache-api provides a caching specification based on JSR-107

2. Configure Ehcache

Now, you need to tell Spring Boot where to find the cache configuration file, which needs to be set in the Spring Boot configuration file:

spring.cache.jcache.config=classpath:ehcache.xmlCopy the code

Then use the @enablecaching annotation to enable Spring Boot application caching. You can do this in the main application class:

package com.ramostear.cache; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cache.annotation.EnableCaching; @SpringBootApplication @EnableCaching public class CacheApplication { public static void main(String[] args) { SpringApplication.run(CacheApplication.class, args); }}Copy the code

Next, you need to create an Ehcache configuration file in the classpath, such as the Resources directory:

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.ehcache.org/v3" xmlns:jsr107="http://www.ehcache.org/v3/jsr107" xsi:schemaLocation=" http://www.ehcache.org/v3 http://www.ehcache.org/schema/ehcache-core-3.0.xsd http://www.ehcache.org/v3/jsr107 http://www.ehcache.org/schema/ehcache-107-ext-3.0.xsd "> < service > < jsr107: defaults enable - statistics =" true "/ > < / service >  <cache alias="person"> <key-type>java.lang.Long</key-type> <value-type>com.ramostear.cache.entity.Person</value-type> <expiry> <ttl unit="minutes">1</ttl> </expiry> <listeners> <listener> <class>com.ramostear.cache.config.PersonCacheEventLogger</class> <event-firing-mode>ASYNCHRONOUS</event-firing-mode> <event-ordering-mode>UNORDERED</event-ordering-mode> <events-to-fire-on>CREATED</events-to-fire-on> <events-to-fire-on>UPDATED</events-to-fire-on> <events-to-fire-on>EXPIRED</events-to-fire-on> <events-to-fire-on>REMOVED</events-to-fire-on> <events-to-fire-on>EVICTED</events-to-fire-on> </listener> </listeners> <resources> <heap unit="entries">2000</heap> <offheap unit="MB">100</offheap> </resources> </cache> </config>Copy the code

Finally, we need to define a CacheEventListener to record system operations on cached data. The fastest way to do this is to implement the CacheEventListener interface:

package com.ramostear.cache.config; import org.ehcache.event.CacheEvent; import org.ehcache.event.CacheEventListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author ramostear * @create-time 2019/4/7 0007-0:48 * @modify by : * @since: */ public class PersonCacheEventLogger implements CacheEventListener<Object,Object>{ private static final Logger logger = LoggerFactory.getLogger(PersonCacheEventLogger.class); @Override public void onEvent(CacheEvent cacheEvent) { logger.info("person caching event {} {} {} {}", cacheEvent.getType(), cacheEvent.getKey(), cacheEvent.getOldValue(), cacheEvent.getNewValue()); }}Copy the code

3. Use the @cacheable annotation

To enable Spring Boot to cache our data, we also need to annotate the business method with the @cacheable annotation, telling Spring Boot that the data generated in the method needs to be added to the cache:

package com.ramostear.cache.service; import com.ramostear.cache.entity.Person; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; /** * @author ramostear * @create-time 2019/4/7 0007-0:51 * @modify by : * @since: */ @Service(value = "personService") public class PersonService { @Cacheable(cacheNames = "person",key = "#id") public Person getPerson(Long id){ Person person = new Person(id,"ramostear","[email protected]"); return person; }}Copy the code

With the above three steps, we have completed Spring Boot’s caching capability. Next, we’ll test the cache in action.

4. Cache test

To test our application, create a simple Restful endpoint that calls PersonService and returns a Person object:

package com.ramostear.cache.controller; import com.ramostear.cache.entity.Person; import com.ramostear.cache.service.PersonService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @author ramostear * @create-time 2019/4/7 0007-0:54 * @modify by : * @since: */ @RestController @RequestMapping("/persons") public class PersonController { @Autowired private PersonService personService; @GetMapping("/{id}") public ResponseEntity<Person> person(@PathVariable(value = "id") Long id){ return new ResponseEntity<>(personService.getPerson(id), HttpStatus.OK); }}Copy the code

Person is a simple POJO class:

package com.ramostear.cache.entity;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.io.Serializable;

/**
 * @author ramostear
 * @create-time 2019/4/7 0007-0:45
 * @modify by :
 * @since:
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class Person implements Serializable{

    private Long id;

    private String username;

    private String email;
}Copy the code

With all of this done, let’s compile and run the application. Project starts successfully, use the browser open: http://localhost:8080/persons/1, you will find the following information in the browser page:

{"id":1,"username":"ramostear","email":"[email protected]"}Copy the code

At this time, you are observing the log information output by the console:

1. The 2019-04-07 01:08:01. 6704-001 the INFO [nio - 8080 - exec - 1] O.S.W eb. Servlet. DispatcherServlet: INFO 6704 -- [e [_default_]-0] c.r.cache.config.PersonCacheEventLogger : person caching event CREATED 1 null com.ramostear.cache.entity.Person@ba8a729Copy the code

Since we are requesting the API for the first time, there is no cached data. Therefore, Ehcache creates a cache of data, which can be seen by creating.

We set the cache expiration time to 1 minute (1) in the ehcache.xml file, so within a minute we refresh the browser and see no new log output. After a minute the cache expires, we refresh the browser again and see the following log output:

1. The 2019-04-07 01:09:28. 6704-612 the INFO [e] [_default_] - 1 C.R.C ache. Config. PersonCacheEventLogger: Person caching event EXPIRED 1 com. Ramostear. Cache. The entity. 2 person @ a9f3c57 null 01:09:28 2019-04-07. 6704-612 the INFO [e [_default_]-1] c.r.cache.config.PersonCacheEventLogger : person caching event CREATED 1 null com.ramostear.cache.entity.Person@416900ceCopy the code

The first log indicates that the cache has expired. The second log indicates that Ehcache created a new cache.

conclusion

In this case, the implementation of Spring Boot application caching based on Ehcache is explained in three simple steps.

The content of this article focuses on the basic steps and methods of cache implementation, which simplifies the specific business code. Interested friends can expand by themselves, and they can contact me at any time when they encounter problems.

Read more on my blog:

1.Java JVM, Collections, Multithreading, new features series tutorials

2.Spring MVC, Spring Boot, Spring Cloud series tutorials

3.Maven, Git, Eclipse, Intellij IDEA series tools tutorial

4.Java, backend, architecture, Alibaba and other big factory latest interview questions

Life is good. See you tomorrow