今天看啥  ›  专栏  ›  pc859107393

SpringBoot2-第五章:整合EhCache

pc859107393  · 掘金  ·  · 2018-06-25 06:40

SpringBoot2-第五章:整合EhCache

上一章我们简单的介绍了Springboot的使用Gson作为消息解析器,这一章我们来在springboot中使用一下缓存相关的注解。

本项目的GitHub:https://github.com/pc859107393/Go2SpringBoot.git

有兴趣交流springboot进行快速开发的同学可以加一下下面的企鹅群。

行走的java全栈

使用SpringBoot的缓存注解

在番外篇中,我已经介绍过springcache的注解,同样的我们在源码中去分析可以看到SpringBoot已经预先设定了一些常用的缓存,我们可以看看都有哪些东西:

  • 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层实现注解才能使缓存生效,如下:

<!--这里是我们的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层的应用。在我的番外篇中已经介绍过各个注解的使用了,这里不在阐述,实例如下:

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)

}

到这里我们运行一下项目,可以看到第一次访问的时候速度会比后面的速度慢一点点,同样的我们手动在数据库中添加一个值,再来访问这个,会发现手动添加的不会被读出来,所以可以证明我们的缓存建立成功了。

具体的效果可以看下截图:

图5-1 缓存成功后,左边数据库手动插入后,右边的缓存数据中并未出现手动插入数据

在上面的图中,我们明显的看到,作图中我手动插入一段数据后,在右图中并没有显示出来说明我们缓存建立成功了。

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




原文地址:访问原文地址
快照地址: 访问文章快照