In the previous chapter we briefly introduced Springboot’s use of Gson as a message parser. In this chapter we will use caching annotations in Springboot.

The objective of the GitHub:https://github.com/pc859107393/Go2SpringBoot.git

Those interested in springboot for rapid development can add the penguin colony below.

Use SpringBoot cache annotations

In the introduction, I have introduced the annotation of SpringCache, also we can see in the source code to analyze SpringBoot has preset some common cache, we can see what they are:

  • org.springframework.cache
    • concurrent
      • ConcurrentMapCacheUse ConcurrentMap as caching technology (default)
    • support
      • AbstractCacheManagerThe CacheManager abstract
      • NoOpCacheA simple cache that doesn’t actually store
      • SimpleCacheManagerSimple cache, often used for testing
    • ehcache
      • EhCacheCache
    • CaffeineCache
      • CaffeineCache
    • jcache
      • JCacheCache
    • transaction
      • AbstractTransactionSupportingCacheManagerAbstract transaction-enabled cache manager

Of course, these classes are only integrated with SpringBoot by default. In order to use caching, we need to add corresponding annotations to the SpringBoot entry class to enable caching.

@SpringBootApplication
@EnableWebMvc
@EnableSwagger2
@MapperScan(value = ["cn.acheng1314.base.dao"])
@Configuration
@EnableTransactionManagement
@EnableCaching  // Use this annotation to enable caching
class BaseApplication : WebMvcConfigurer {
    //... omit code
}
Copy the code

The default Spring will use ConcurrentMapCacheManager, of course, how to use EhCache? We need to make changes in the configuration file. First join Ehcache dependencies: compile ‘net. Sf. The Ehcache: Ehcache: 2.10.5’, then we good Ehcache configuration specified in the configuration file, as follows:

# Ehcache configuration
spring.cache.ehcache.config=classpath:/ehcache.xml
spring.cache.type=ehcache
Copy the code

Is that the end of the story? However, we need to implement ehCache configuration first, and then service layer annotation to make cache effective, as follows:

<! Here is our ehCache configuration -->
<ehcache
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false">
    <! -- Cache path, base_ehcache directory in user directory -->
    <diskStore path="user.home/base_ehcache"/>  

    <defaultCache
            maxElementsInMemory="20000"
            eternal="false"
            timeToIdleSeconds="120"
            timeToLiveSeconds="120"
            overflowToDisk="true"
            maxElementsOnDisk="10000000"
            diskPersistent="false"
            diskExpiryThreadIntervalSeconds="120"
            memoryStoreEvictionPolicy="LRU"/>
    <! Cache_user: cache_user;
    <cache name="cache_user"
           maxElementsInMemory="20000"
           eternal="true"
           overflowToDisk="true"
           diskPersistent="false"
           timeToLiveSeconds="0"
           diskExpiryThreadIntervalSeconds="120"/>

</ehcache>
Copy the code

Next, let’s look at caching annotations at the Service layer. I have already introduced the use of each annotation in my paper. I will not elaborate on it here. Examples are as follows:

import cn.acheng1314.base.dao.UserDao
import cn.acheng1314.base.domain.User
import com.baomidou.mybatisplus.plugins.pagination.Pagination
import com.baomidou.mybatisplus.service.impl.ServiceImpl
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.cache.annotation.CacheConfig
import org.springframework.cache.annotation.Cacheable
import org.springframework.stereotype.Service
import kotlin.collections.ArrayList

@Service(value = "userService") 
// The value must correspond to the cache name of the configuration file; otherwise, an exception will occur
@CacheConfig(cacheNames = ["cache_user"])  
class UserServiceImpl : ServiceImpl<UserDao, User>() {

    @Autowired
    lateinit var userDao: UserDao

    fun findUserByPage(pageNum: Int, pageSize: Int): ArrayList<User> {
        return try {
            val pagination = Pagination(pageNum, pageSize)
            setTotalPage(pagination.pages)
            userDao.findAllByPage(pagination)
        } catch (e: Exception) {
            arrayListOf()
        }
    }

    var totalPage: Long? = null
    fun setTotalPage(pages: Long) {
        this.totalPage = pages
    }

    @Cacheable(sync = true)
    fun findAll(a) = baseMapper.selectList(null)}Copy the code

So if we run the project over here, we can see that the first access is a little bit slower than the next one, and again if we manually add a value to the database, and then access this one again, we’ll see that the value that was manually added won’t be read, so we can prove that our cache is set up successfully.

The specific effect can be seen in the screenshot:

In the figure above, we can obviously see that after I manually inserted a piece of data in the figure on the right, it does not show that we have successfully established the cache.

For more detailed code, please see my project source code, thank you for reading.