背景
项目开发过程中经常用到mybatis,为了提升查询效率,mybatis支持一级和二级缓存,一级缓存基于SqlSession级别,默认开启,二级缓存基于Mapper级别;一级和二级缓存在单机模式下是没有问题的,但是在集群环境下是无法进行缓存同步的,因此需要借助第三方缓存redis,将查询数据统一缓存到redis,这样在集群环境下也能实现缓存同步;
之前的文章中已经介绍了spring如何集成redis,这里介绍下开启spring cache,通过redis实现查询缓存:
开启缓存
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cache="http://www.springframework.org/schema/cache" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 启用注解缓存 --> <cache:annotation-driven/> <!-- 缓存管理器 --> <bean id="cacheManager" class="org.springframework.data.redis.cache.RedisCacheManager"> <constructor-arg index="0" ref="redisJacksonTemplate"/> <!-- 过期时间 --> <property name="defaultExpiration" value="3600"/> </bean> </beans>
通过 <cache:annotation-driven/>
开启spring cache注解缓存支持;
参数:
cache-manager:缓存管理器,默认引用
cacheManager
key-generator:缓存key生成规则,自定义key生成规则
error-handler:缓存异常处理器
应用
package com.dongzz.cms.modules.home.service.impl; import com.dongzz.cms.common.base.impl.BaseMybatisServiceImpl; import com.dongzz.cms.modules.cms.dao.CmsTagMapper; import com.dongzz.cms.modules.cms.entity.CmsTag; import com.dongzz.cms.modules.home.service.TagService; 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 java.util.List; @Service("WebTagService") @CacheConfig(cacheNames = "tag") // 缓存空间名称 public class TagServiceImpl extends BaseMybatisServiceImpl<CmsTag> implements TagService { @Autowired private CmsTagMapper tagMapper; @Override @Cacheable(key = "'tag::' + #p0") // 查询缓存 key public List<CmsTag> findByTags(String tags) throws Exception { return tagMapper.selectTags(tags); } @Override public List<CmsTag> findAll() throws Exception { return tagMapper.selectAll(); } }
注解:
@CacheConfig 缓存空间名称
@Cacheable 查询缓存
@CachePut 修改缓存
@CacheEvict 清除缓存
总结
通过 spring cache 集成redis,实现查询缓存,有效解决了mybatis一级缓存和二级缓存在集群下无法同步的问题,同时redis作为高性能的nosql数据库,能极大的降低应用程序直接操作msyql带来的性能瓶颈问题;