[JAVA] Use cache with EhCashe 2.x with Spring Boot

background

I was using Spring Boot and wanted to implement a cache, so I tried it.

Execution environment

Cache in Spring Boot

Several caches are available in Spring Boot. https://docs.spring.io/spring-boot/docs/2.1.6.RELEASE/reference/html/boot-features-caching.html

Looking from above, EhCache 2.x seems to be easy to install. It is said that if there is ehcache.xml in the classpath, it will be used, so it seems easy to introduce, so I will try it.

EhCache 2.x

Implementation

Caller of method that uses cache

This time, let's call it from the class annotated with @ SpringBootApplication. Annotate @EnableCaching

CacheApplication.java


@SpringBootApplication
@EnableCaching
public class CacheApplication implements CommandLineRunner {

	@Autowired
	Cache cache;

	private final static Logger logger = LoggerFactory.getLogger(CacheApplication.class);
	private final static DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss");

	public static void main(String[] args) {
		SpringApplication.run(CacheApplication.class, args);
	}

	public void run(String[] args){

		this.getValue("Be cached");
		this.getValue("Be cached");//Be cached
		this.getValue("Not cached because the arguments are different");//Not cached because the arguments are different
		this.getValue("Be cached");//引数違うのを挟んでBe cached
		try {
			Thread.sleep(3000L);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		this.getValue("Be cached");//The arguments are the same, but they are not cached because they have passed the lifetime.
	}

	public void getValue(String key){
		logger.info(key + " Start at: " + LocalDateTime.now().format(dateTimeFormatter));
		String ret = cache.getFromCache(key); //Cache-enabled methods
		logger.info(ret + " End at: " + LocalDateTime.now().format(dateTimeFormatter));
	}
}

Class that uses cache

Add @Cacheable to the method you want to enable caching

Cache.java


@Component
public class Cache {

    @Cacheable("getCache") //Enable caching for this method
    public String getFromCache(String key){
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "End getFromCache:" + key;
    }
}

pom.xml Add two systems, spring-boot-starter-cache and ʻehcache`, to pom.xml.

pom.xml


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

ehcache.xml Create ehcache.xml under src / main / resources /. Set timeToLiveSeconds to 5 and set the cache lifetime to 5 seconds.

ehcache.xml


<?xml version="1.0" encoding="UTF-8"?>
<ehcache>
    <diskStore path="java.io.tmpdir"/>
    <cache
            name="getCache"
            timeToLiveSeconds="5"
            maxEntriesLocalHeap="0">
    </cache>
</ehcache>

application.properties Add the following settings to application.properties to use ehcache. This is not necessary if the only cache available is ehcache.

spring.cache.type=ehcache

Run

I will do it. The execution result is like this.

2020-02-29 21:29:48 -Cached Start at: 21:29:48
2020-02-29 21:29:51 - End getFromCache:Cached End at: 21:29:51
2020-02-29 21:29:51 -Cached Start at: 21:29:51
2020-02-29 21:29:51 - End getFromCache:Cached End at: 21:29:51
2020-02-29 21:29:51 -Not cached because the arguments are different Start at: 21:29:51
2020-02-29 21:29:54 - End getFromCache:Not cached because the arguments are different End at: 21:29:54
2020-02-29 21:29:54 -Cached Start at: 21:29:54
2020-02-29 21:29:54 - End getFromCache:Cached End at: 21:29:54
2020-02-29 21:29:57 -Cached Start at: 21:29:57
2020-02-29 21:30:00 - End getFromCache:Cached End at: 21:30:00

We will see the results below. The first time it takes 3 seconds, but the second time is a moment, so the cache seems to be working.

2020-02-29 21:29:48 -Cached Start at: 21:29:48
2020-02-29 21:29:51 - End getFromCache:Cached End at: 21:29:51
2020-02-29 21:29:51 -Cached Start at: 21:29:51
2020-02-29 21:29:51 - End getFromCache:Cached End at: 21:29:51

If you pass a different argument, it will not be cached, so it will take another 3 seconds.

2020-02-29 21:29:51 -Not cached because the arguments are different Start at: 21:29:51
2020-02-29 21:29:54 - End getFromCache:Not cached because the arguments are different End at: 21:29:54

The following is over 5 seconds of survival time, so it is not cached and takes 3 seconds.

2020-02-29 21:29:57 -Cached Start at: 21:29:57
2020-02-29 21:30:00 - End getFromCache:Cached End at: 21:30:00

The cache behaves as intended.

Impressions

I thought that SpringBoot and EhCache2.X are quick because the cache can be implemented only with annotations and configuration files. However, after learning that the EhCache3 series is already available, you may not dare to use the EhCache2 series.

When I tried caffeine, I was able to implement the cache in the same way, so it seems that I can use that as well. The following article was helpful. https://qiita.com/yut_arrows/items/4b664acdfa852c0bd6cd

Recommended Posts

Use cache with EhCashe 2.x with Spring Boot
Beginning with Spring Boot 0. Use Spring CLI
Download with Spring Boot
How to use MyBatis2 (iBatis) with Spring Boot 1.4 (Spring 4)
How to use built-in h2db with spring boot
Use Servlet filter in Spring Boot [Spring Boot 1.x, 2.x compatible]
Generate barcode with Spring Boot
Hello World with Spring Boot
Implement GraphQL with Spring Boot
Get started with Spring boot
Run LIFF with Spring Boot
SNS login with Spring Boot
File upload with Spring Boot
Spring Boot starting with copy
Spring Boot + Springfox springfox-boot-starter 3.0.0 Use
Hello World with Spring Boot
Getting Started with Spring Boot
Create microservices with Spring Boot
Send email with spring boot
File upload with Spring Boot (do not use Multipart File)
Use thymeleaf3 with parent without specifying spring-boot-starter-parent in Spring Boot
Spring Boot 2.x context path settings
Create an app with Spring Boot 2
Database linkage with doma2 (Spring boot)
Cassandra x Spring Boot struggle record
Spring Boot programming with VS Code
Until "Hello World" with Spring Boot
Get validation results with Spring Boot
(Intellij) Hello World with Spring Boot
Create an app with Spring Boot
Google Cloud Platform with Spring Boot 2.0.0
Use DBUnit for Spring Boot test
Check date correlation with Spring Boot
How to use ModelMapper (Spring boot)
I tried GraphQL with Spring Boot
[Java] LINE integration with Spring Boot
I tried Flyway with Spring Boot
Message cooperation started with Spring Boot
Spring Boot gradle build with Docker
Introduction to Spring Boot x OpenAPI ~ OpenAPI made with Generation gap pattern ~
Processing at application startup with Spring Boot
Hello World with Eclipse + Spring Boot + Maven
Send regular notifications with LineNotify + Spring Boot
Perform transaction confirmation test with Spring Boot
Try using Spring Boot with VS Code
Start web application development with Spring Boot
Launch Nginx + Spring Boot application with docker-compose
Use DynamoDB query method in Spring Boot
Implement CRUD with Spring Boot + Thymeleaf + MySQL
Asynchronous processing with Spring Boot using @Async
Use Spring Security JSP tags with FreeMarker
Implement paging function with Spring Boot + Thymeleaf
(IntelliJ + gradle) Hello World with Spring Boot
Form class validation test with Spring Boot
Run WEB application with Spring Boot + Thymeleaf
Achieve BASIC authentication with Spring Boot + Spring Security
Spring Boot environment construction with Docker (January 2021 version)
Create a website with Spring Boot + Gradle (jdk1.8.x)
Configure Spring Boot application with maven multi module
Test controller with Mock MVC in Spring Boot
Asynchronous processing with regular execution in Spring Boot