Spring Boot 2.x basic tutorial: the use of EhCache cache

Previous We learned how to use Spring Boot to use in-process caching to speed up data access. You may ask, what cache do we use in Spring Boot?

In Spring Boot, the appropriate cache manager (CacheManager) is automatically configured through the @EnableCaching annotation. Spring Boot detects the cache provider according to the following order:

  • Generic
  • JCache (JSR-107) (EhCache 3, Hazelcast, Infinispan, and others)
  • EhCache 2.x
  • Hazelcast
  • Infinispan
  • Couchbase
  • Redis
  • Caffeine
  • Simple

In addition to detecting in order, we can also force it by configuring the property spring.cache.type. We can also view the instance of the cacheManager object through debug debugging to determine what cache is currently used. exist Previous , we also show how to check the current usage.

When we do not specify other third-party implementations, Spring Boot's Cache module will use ConcurrentHashMap for storage. In actual production use, because we may need more other features, other caching frameworks are often used, so next we will introduce the integration and use of several commonly used excellent caches in several articles.

Using EhCache

In this article, we will introduce how to use EhCache in-process caching in Spring Boot. Here we will use Previous The results of the case to be retrofitted to achieve the use of EhCache.

Let’s review the three parts of this base case:

Definition of User entity

@Entity
@Data
@NoArgsConstructor
public class User {

    @Id
    @GeneratedValue
    private Long id;

    private String name;
    private Integer age;

    public User(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

Data access implementation for User entity (covers cache annotations)

@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {

    @Cacheable
    User findByName(String name);

}

Test verification case (covers the injection of CacheManager, which can be used to observe the cache management class used)

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter51ApplicationTests {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private CacheManager cacheManager;

    @Test
    public void test() throws Exception {
        // Create 1 record
        userRepository.save(new User("AAA", 10));

        User u1 = userRepository.findByName("AAA");
        System.out.println("First query:" + u1.getAge());

        User u2 = userRepository.findByName("AAA");
        System.out.println("Second query:" + u2.getAge());
    }

}

Next, we can easily change the above cache application to use ehcache cache management through the following steps.

Step 1: Introduce ehcache dependency in pom.xml

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>

Under the parent management of Spring Boot, there is no need to specify a specific version, and the version number specified in Spring Boot will be used automatically.

Step 2: Create in the src/main/resources directory: ehcache.xml

<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="ehcache.xsd">

    <cache name="users"
           maxEntriesLocalHeap="200"
           timeToLiveSeconds="600">
    </cache>

</ehcache>

After completing the above configuration, run the unit test in debug mode and observe that CacheManager is already an instance of EhCacheManager at this time, indicating that EhCache is successfully opened. Or add the output of CacheManager to the test case, for example:

@Autowired
private CacheManager cacheManager;

@Test
public void test() throws Exception {
    System.out.println("CacheManager type : " + cacheManager.getClass());

    userRepository.save(new User("AAA", 10));

    User u1 = userRepository.findByName("AAA");
    System.out.println("First query:" + u1.getAge());

    User u2 = userRepository.findByName("AAA");
    System.out.println("Second query:" + u2.getAge());
}

Execute the test output to get:

CacheManager type : class org.springframework.cache.ehcache.EhCacheCacheManager
Hibernate: select next_val as id_val from hibernate_sequence for update
Hibernate: update hibernate_sequence set next_val= ? where next_val=?
Hibernate: insert into user (age, name, id) values (?, ?, ?)
2020-07-14 18:09:28.465  INFO 58538 --- [           main] o.h.h.i.QueryTranslatorFactoryInitiator  : HHH000397: Using ASTQueryTranslatorFactory
Hibernate: select user0_.id as id1_0_, user0_.age as age2_0_, user0_.name as name3_0_ from user user0_ where user0_.name=?
First query: 10
 Second query: 10

can be seen:

  1. The CacheManager type output in the first line is org.springframework.cache.ehcache.EhCacheCacheManager, not the ConcurrentHashMap in the previous article.
  2. When querying for the second time, there is no SQL statement output, so it is obtained from the cache.

Integration succeeded!

code example

Examples of this article can be found in the chapter5-2 directory in the following repository:

If you think this article is good, you are welcome to support Star, your attention is the driving force for me to persevere!

This article was first published: Spring Boot 2.x basic tutorial: the use of EhCache cache ,Please indicate the source.
Welcome to pay attention to my public number: Programmer DD, get exclusive learning resources and daily dry goods push.
This series of tutorials Click to go to the directory

Tags: Java

Posted by littlehelp on Tue, 31 May 2022 23:00:39 +0530