• 周六. 10 月 5th, 2024

5G编程聚合网

5G时代下一个聚合的编程学习网

热门标签

Spring boot 2. X Basics: using ehcache cache

King Wang

1 月 3, 2022

Last one We learned how to use Spring Boot Using in-process caching to speed up data access . Maybe you will ask , Then we are Spring Boot What kind of cache is used in ?

stay Spring Boot Pass through @EnableCaching Annotation automation configures the appropriate cache manager (CacheManager),Spring Boot Detect 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

Except for sequential detection , We can also configure properties spring.cache.type To force the assignment . We can also pass debug Debug view cacheManager Object to determine what cache is currently in use . stay Last one in , We also showed how to look at current usage .

When we don’t specify specific third-party implementations ,Spring Boot Of Cache The module will use the ConcurrentHashMap To store . And when it’s actually used in production , Because we may need more features , Other caching frameworks are often used , So next, we will introduce the integration and use of several common excellent caches .

Use EhCache

In this article, we will introduce how to use Spring Boot Use in EhCache In process caching . We will continue to use it here Last one The result of the case is to transform , In order to realize the EhCache Use .

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

User Definition of 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;
}
}

User Entity data access implementation ( Includes cache annotations )

@CacheConfig(cacheNames = "users")
public interface UserRepository extends JpaRepository<User, Long> {
@Cacheable
User findByName(String name);
}

Test validation use cases ( covers CacheManager The injection of , 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 {
// establish 1 Bar 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());
}
}

Let’s go through the following steps , You can easily change the above cache application to use ehcache Cache management .

First step : stay pom.xml Introduction in ehcache rely on

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

stay Spring Boot Of parent Under management , There is no need to specify a specific version , Will automatically adopt Spring Boot Version number specified in .

The second step : stay src/main/resources Create under 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 , Re pass debug Mode run unit test , Observe this moment CacheManager It’s already EhCacheManager example , explain EhCache Open successfully . Or add a sentence to the test case CacheManager Output , 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());
}

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

You can see :

  1. The first line outputs CacheManager type by org.springframework.cache.ehcache.EhCacheCacheManager, Not the one in the last one ConcurrentHashMap 了 .
  2. On the second inquiry , No output SQL sentence , So it’s going to take cache access

Successful integration !

Code example

For an example of this article, see the following in the warehouse chapter5-2 Catalog :

  • Github:https://github.com/dyc87112/SpringBoot-Learning/
  • Gitee:https://gitee.com/didispace/SpringBoot-Learning/

If you think this article is good , welcome Star Support , Your concern is the driving force of my persistence !

First article :Spring Boot 2.x Basic course :EhCache The use of caching , Reprint please indicate the source . Welcome to my official account. : Program the ape DD, Get exclusive learning resources and daily dry goods push . This series of tutorials Click to the directory

发表回复