SpringBoot2-第五章:整合EhCache

上一章咱們簡單的介紹了Springboot的使用Gson做爲消息解析器,這一章咱們來在springboot中使用一下緩存相關的註解。java

本項目的GitHub:https://github.com/pc859107393/Go2SpringBoot.gitgit

有興趣交流springboot進行快速開發的同窗能夠加一下下面的企鵝羣。github

行走的java全棧

使用SpringBoot的緩存註解

在番外篇中,我已經介紹過springcache的註解,一樣的咱們在源碼中去分析能夠看到SpringBoot已經預先設定了一些經常使用的緩存,咱們能夠看看都有哪些東西:spring

  • org.springframework.cache
    • concurrent
      • ConcurrentMapCache 使用ConcurrentMap做爲緩存技術(默認)
    • support
      • AbstractCacheManager CacheManager的抽象
      • NoOpCache 不會實際存儲的簡單緩存
      • SimpleCacheManager 簡單緩存,經常使用於測試
    • ehcache
      • EhCacheCache
    • CaffeineCache
      • CaffeineCache
    • jcache
      • JCacheCache
    • transaction
      • AbstractTransactionSupportingCacheManager 抽象的支持事務的緩存管理器

固然上面的這些類,只是springboot默認集成的,要想使用緩存,首先咱們須要在SpringBoot的入口類中加入對應的註解來開啓緩存。數據庫

@SpringBootApplication
@EnableWebMvc
@EnableSwagger2
@MapperScan(value = ["cn.acheng1314.base.dao"])
@Configuration
@EnableTransactionManagement
@EnableCaching  //使用這個註解開啓緩存
class BaseApplication : WebMvcConfigurer {
    //···省略代碼
}
複製代碼

固然默認的Spring會使用ConcurrentMapCacheManager,如何使用EhCache呢?咱們須要在配置文件中作出修改。首先加入Ehcache的依賴:compile 'net.sf.ehcache:ehcache:2.10.5' ,再接着咱們在配置文件中約定好Ehcache的配置,以下:緩存

#Ehcache配置
spring.cache.ehcache.config=classpath:/ehcache.xml
spring.cache.type=ehcache
複製代碼

這樣寫玩了就完事了嗎? 然而並無,咱們須要先實現ehcache的配置,再service層實現註解才能使緩存生效,以下:springboot

<!--這裏是咱們的ehcache配置-->
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
    <!--緩存路徑,用戶目錄下的base_ehcache目錄-->
    <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 name="cache_user" maxElementsInMemory="20000" eternal="true" overflowToDisk="true" diskPersistent="false" timeToLiveSeconds="0" diskExpiryThreadIntervalSeconds="120"/>

</ehcache>
複製代碼

接着咱們來看看緩存註解在service層的應用。在個人番外篇中已經介紹過各個註解的使用了,這裏不在闡述,實例以下:mybatis

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") 
//這裏須要和配置文件的cache的name對應,不然產生異常某個名爲XX的緩存找不到
@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() = baseMapper.selectList(null)

}
複製代碼

到這裏咱們運行一下項目,能夠看到第一次訪問的時候速度會比後面的速度慢一點點,一樣的咱們手動在數據庫中添加一個值,再來訪問這個,會發現手動添加的不會被讀出來,因此能夠證實咱們的緩存創建成功了。app

具體的效果能夠看下截圖:dom

圖5-1 緩存成功後,左邊數據庫手動插入後,右邊的緩存數據中並未出現手動插入數據

在上面的圖中,咱們明顯的看到,做圖中我手動插入一段數據後,在右圖中並無顯示出來講明咱們緩存創建成功了。

具體更多細節代碼,請看個人項目源碼,謝謝閱讀。

相關文章
相關標籤/搜索