项目开发过程中经常用到mybatis,为了提升查询效率,mybatis支持一级和二级缓存,一级缓存基于SqlSession级别,默认开启,二级缓存基于Mapper级别;一级和二级缓存在单机模式下是没有问题的,但是在集群环境下是无法进行缓存同步的,因此需要借助第三方缓存redis,将查询数据统一缓存到redis,这样在集群环境下也能实现缓存同步;
之前的文章中已经介绍了spring如何集成redis,这里介绍下开启spring cache,通过redis实现查询缓存:
通过 <cache:annotation-driven></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 implements TagService {
@Autowired
private CmsTagMapper tagMapper;
@Override
@Cacheable(key = "'tag::' + #p0") // 查询缓存 key
public List findByTags(String tags) throws Exception {
return tagMapper.selectTags(tags);
}
@Override
public List findAll() throws Exception {
return tagMapper.selectAll();
}
}
注解:
- @CacheConfig 缓存空间名称
- @Cacheable 查询缓存
- @CachePut 修改缓存
- @CacheEvict 清除缓存
通过 spring cache 集成redis,实现查询缓存,有效解决了mybatis一级缓存和二级缓存在集群下无法同步的问题,同时redis作为高性能的nosql数据库,能极大的降低应用程序直接操作msyql带来的性能瓶颈问题;
Original: https://www.cnblogs.com/herokevin/p/15824386.html
Author: 暴走编程
Title: Spring 4 集成 redis 实现缓存 二
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/609994/
转载文章受原作者版权保护。转载请注明原作者出处!