In the last article we learned how to use Spring Boot to speed up data access using in-process caching. You might be asking, well, what kind of cache are we using in Spring Boot?

The appropriate CacheManager (CacheManager) is automatically configured in Spring Boot with the @enablecaching annotation. Spring Boot detects cache providers in 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 sequential detection, we can also enforce this by configuring the property spring.cache.type. You can also debug by viewing an instance of the cacheManager object to determine what cache is currently in use. In the previous article, we also showed how to view current usage.

Spring Boot’s Cache module uses ConcurrentHashMap when we do not specify a specific third-party implementation. In actual production use, we often use other caching frameworks because we may need more features, so we will introduce the integration and use of several commonly used excellent caches in the following sections.

Using EhCache

This article will show you how to use EhCache in-process caching in Spring Boot. Here we will use the case results of the previous article to implement the transformation to achieve the use of EhCache.

Let’s review the three parts of the 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; }}Copy the code

Data access implementation for User entities (including caching annotations)

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

    @Cacheable
    User findByName(String name);

}Copy the code

Test validation use cases (covering injection of CacheManager, which can be used to observe cache management classes in use)

@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 ()); }}Copy the code

With the following steps, we can easily change the above cache application to use ehCache cache management.

Step 1: Introduce ehcache dependencies in POM.xml

<dependency>
    <groupId>net.sf.ehcache</groupId>
    <artifactId>ehcache</artifactId>
</dependency>Copy the code

Under the parent management of Spring Boot, the version specified in Spring Boot is automatically adopted without specifying the specific version.

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

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

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

</ehcache>Copy the code

After the configuration is complete, run the unit test in debug mode. If The CacheManager instance is EhCache Emanager, EhCache is successfully enabled. Or add a line of CacheManager output to the test case, such as:

@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 ()); }Copy the code

Executing the test output yields:

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 (? ,? ,?) The 2020-07-14 18:09:28. 58538-465 the INFO [main] O.H.H.I.Q ueryTranslatorFactoryInitiator: HHH000397: Using ASTQueryTranslatorFactory Hibernate: Id as id1_0_, user0_. Age as age2_0_, user0_. Name as name3_0_ from user user0_ where user0_. 10 Second query: 10Copy the code

You can see:

  1. The CacheManager Type displayed in the first line isorg.springframework.cache.ehcache.EhCacheCacheManager“Instead of the last oneConcurrentHashMap.
  2. In the second query, no SQL statement is output, so it is cache fetch

Integration successful!

Code sample

For an example of this article, see the chapter5-2 directory in the repository below:

  • Github:github.com/dyc87112/Sp…
  • Gitee:gitee.com/didispace/S…

If you found this article good, welcomeStarSupport, your attention is my motivation!

Spring Boot 2. X basic tutorial: EhCache Welcome to pay attention to my official account: Program ape DD, for exclusive learning resources and daily dry goods push. For this tutorial, click direct to the catalog