SpringBoot中使用redis做Mybatis的二级缓存

文章目录


在mybatis中有一级缓存、二级缓存
一级缓存:该缓存是基于SqlSession的,mybatis默认开启一级缓存。
二级缓存:该缓存是Mapper级别的,默认没有开启二级缓存,需要在配置文件中开启

<!-- 开启二级缓存,默认是false -->
<setting name="cacheEnabled" value="true"/>
package com.becom.qoe.usermanager.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;

/**
 * redisTemplate 设置
 * 
 * @author wangn 2019年10月8日 下午3:23:03
 */
@Configuration
public class RedisConfiguration {

	@Bean
	public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		// 设置序列化
		GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
		template.setKeySerializer(new JdkSerializationRedisSerializer());
		template.setHashKeySerializer(new JdkSerializationRedisSerializer());
		template.setHashValueSerializer(new JdkSerializationRedisSerializer());
		template.setValueSerializer(serializer);
		template.setConnectionFactory(redisConnectionFactory);
		template.afterPropertiesSet();
		return template;
	}
}

自定义实现mybatis的cache接口

package com.becom.qoe.usermanager.cache;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.apache.ibatis.cache.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import com.becom.qoe.usermanager.util.SpringBeanUtils;

/**
 * mybatis 二级缓存的redis实现
 * 
 * @author wangn 2019年10月24日 下午3:37:39
 */
public class MybatisRedisCache implements Cache {

	private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.class);

	/**
	 * 缓存对象id
	 */
	private final String id;
	/**
	 * 读写锁
	 */
	private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

	private RedisTemplate<?, ?> template;

	/**
	 * 缓存有效期
	 */
	private static final long EXPIRE_TIME = 30;

	public MybatisRedisCache(String id) {
		if (id == null) {
			throw new IllegalArgumentException("the parameter id can not been null.");
		}
		this.id = id;
	}

	@Override
	public String getId() {
		return this.id;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void putObject(Object key, Object value) {
		RedisTemplate rt = getRedisTemplate();
		ValueOperations operat = rt.opsForValue();
		operat.set(key, value, EXPIRE_TIME, TimeUnit.MINUTES);
		logger.debug("save {} success.", key);
	}

	@Override
	@SuppressWarnings("rawtypes")
	public Object getObject(Object key) {
		RedisTemplate rt = getRedisTemplate();
		ValueOperations operat = rt.opsForValue();
		return operat.get(key);
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Object removeObject(Object key) {
		RedisTemplate rt = getRedisTemplate();
		rt.delete(key);
		logger.debug("delete {} success.", key);
		return null;
	}

	@Override
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void clear() {
		RedisTemplate rt = getRedisTemplate();
		rt.execute((RedisCallback) collect -> {
			collect.flushDb();
			return null;
		});
	}

	@Override
	public int getSize() {
		return 0;
	}

	@Override
	public ReadWriteLock getReadWriteLock() {
		return readWriteLock;
	}

	@SuppressWarnings("rawtypes")
	private RedisTemplate getRedisTemplate() {
		if (this.template == null) {
			this.template = (RedisTemplate) SpringBeanUtils.getBean("redisTemplate");
		}
		return this.template;
	}
}

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper	namespace="com.becom.qoe.usermanager.dao.usermanager.UserInformationDao">
	<cache type="com.becom.qoe.usermanager.cache.MybatisRedisCache"/>
	<cache-ref namespace="com.becom.qoe.usermanager.dao.usermanager.SysUserLoginDao"/>
</mapper>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值