您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这期内容当中小编将会给大家带来有关怎么在mybatis中利用redis作二级缓存,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。
1. mybatis-plus开启二级缓存
mybatis-plus.configuration.cache-enabled=true
2. 定义RedisTemplate的bean交给spring管理,这里为了能将对象直接存取到redis中,进行了一些序列化的操作
@Bean(value = "redisTemplate") public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(connectionFactory); //Use Jackson 2Json RedisSerializer to serialize and deserialize the value of redis (default JDK serialization) Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //将类名称序列化到json串中 objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); //设置输入时忽略JSON字符串中存在而Java对象实际没有的属性 objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); jackson2JsonRedisSerializer.setObjectMapper(objectMapper); //Use String RedisSerializer to serialize and deserialize the key value of redis RedisSerializer redisSerializer = new StringRedisSerializer(); //key redisTemplate.setKeySerializer(redisSerializer); redisTemplate.setHashKeySerializer(redisSerializer); //value redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer); redisTemplate.afterPropertiesSet(); return redisTemplate; }
3. 自定义自己的缓存管理
package com.qctchina.headsetserver.config; import com.qctchina.headsetserver.util.SpringUtil; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.cache.Cache; import org.springframework.data.redis.connection.RedisServerCommands; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.util.CollectionUtils; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * @author shuangyueliao * @create 2019/9/10 14:02 * @Version 0.1 */ @Slf4j public class MybatisRedisCache implements Cache { // 读写锁 private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(true); //这里使用了redis缓存,使用springboot自动注入 private RedisTemplate<String, Object> redisTemplate; private String id; public MybatisRedisCache(final String id) { if (id == null) { throw new IllegalArgumentException("Cache instances require an ID"); } this.id = id; } @Override public String getId() { return this.id; } @Override public void putObject(Object key, Object value) { if (redisTemplate == null) { //由于启动期间注入失败,只能运行期间注入,这段代码可以删除 redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate"); } if (value != null) { redisTemplate.opsForValue().set(key.toString(), value); } } @Override public Object getObject(Object key) { if (redisTemplate == null) { //由于启动期间注入失败,只能运行期间注入,这段代码可以删除 redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate"); } try { if (key != null) { return redisTemplate.opsForValue().get(key.toString()); } } catch (Exception e) { e.printStackTrace(); log.error("缓存出错 "); } return null; } @Override public Object removeObject(Object key) { if (redisTemplate == null) { //由于启动期间注入失败,只能运行期间注入,这段代码可以删除 redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate"); } if (key != null) { redisTemplate.delete(key.toString()); } return null; } @Override public void clear() { log.debug("清空缓存"); if (redisTemplate == null) { redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate"); } Set<String> keys = redisTemplate.keys("*:" + this.id + "*"); if (!CollectionUtils.isEmpty(keys)) { redisTemplate.delete(keys); } } @Override public int getSize() { if (redisTemplate == null) { //由于启动期间注入失败,只能运行期间注入,这段代码可以删除 redisTemplate = (RedisTemplate<String, Object>) SpringUtil.getBean("redisTemplate"); } Long size = redisTemplate.execute((RedisCallback<Long>) RedisServerCommands::dbSize); return size.intValue(); } @Override public ReadWriteLock getReadWriteLock() { return this.readWriteLock; } }
SpringUtil是手动获取bean的工具类
@Component public class SpringUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { SpringUtil.applicationContext = applicationContext; } public static Object getBean(String name){ return applicationContext.getBean(name); } public static <T> T getBean(String name, Class<T> clazz){ return applicationContext.getBean(name, clazz); } public static <T> T getBean(Class<T> clazz){ return applicationContext.getBean(clazz); } }
4. 在mapper上加上注解@CacheNamespace
@CacheNamespace(implementation= MybatisRedisCache.class,eviction=MybatisRedisCache.class) public interface CommonMapper extends BaseMapper<Common> {
如果调用该mapper下的方法,那么会使用redis缓存
上述就是小编为大家分享的怎么在mybatis中利用redis作二级缓存了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注亿速云行业资讯频道。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。