Getting Started with Spring Boot (16) - Caching Technology

Reprint: http://blog.sina.com.cn/s/blog_c90ce4e0010329x8.html

In actual development work, if the database is frequently queried, will it bring a lot of pressure to the database server?

Therefore, we need to cache the queried data, so that the client only needs to query the data from the database once, this batch of data will be put into the cache, and it can be read from the cache when querying again later, will it be much faster? Woolen cloth?

SpringBoot supports many caching methods: redis, guava, ehcahe, jcache, etc.

Below we use SpringBoot's simplest caching method to make a brief introduction to SpringBoot's caching technology (SpringBoot's version is 1.4.0.RELEASE).

 

The default caching method of SpringBoot is to cache data in memory through the ConCurrentMap structure.

1. First, create a new SpringBoot project with the following structure

 

2. Edit POM.XML and add related dependencies

 

3. Edit the application.properties file to configure the database connection parameters​

4. Write the entity class Person.java (getter and setter methods are omitted here)​

5. Write the database access interface PersonRepository.java, where the jap framework is used, and the basic database addition, deletion, modification, and query operations can be implemented by inheriting the JpaRepository interface.​

6. Write the business class interface PersonService.java and declare some business methods​

7. Write the business interface implementation class PersonServiceImpl.java​

注:   @CachePut 缓存新增的或者更新的数据到缓存中其中缓存名称为person,数据的keyperson.id

          @CacheEvict:  从缓存person中删除key为id的缓存数据

          @Cacheable: 读取缓存为person中key为id的缓存数据。

@CachePut@CacheEvict@Cacheable若未指定key, 则方法参数作为key保存到缓存中。

 

8.      编写访问控制器类PersonController.java

 

9.      编写程序入口

 注: 此处一定要加上@EnableCaching来开启SpringBoot的缓存支持

 

10.      测试访问:

       A.我们先保存一组数据到缓存中

            此时页面输出如下:​

           控制台输出如下:

        B.此时再次从页面上访问id=21的数据, 控制台不会再打印Hibernate的查询语句以及“为id、key为:21数据做了缓存”。这表明程序未调用该方法,页面数据直接从缓存中取得。

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326458424&siteId=291194637