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 缓存成功后,左边数据库手动插入后,右边的缓存数据中并未出现手动插入数据

在上面的图中,咱们明显的看到,做图中我手动插入一段数据后,在右图中并无显示出来讲明咱们缓存创建成功了。

具体更多细节代码,请看个人项目源码,谢谢阅读。

相关文章
相关标签/搜索