介绍
使用mybatis时可以使用二级缓存提高查询速度,进而改善用户体验。
使用redis做mybatis的二级缓存可是内存可控<如将单独的服务器部署出来用于二级缓存>,管理方便。
1.在pom.xml文件中引入redis依赖
<dependency> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-starter-data-redis</artifactID></dependency>
2.在application.propertIEs配置文件中进行redis的配置
## Redis spring.redis.database=0spring.redis.host=172.16.3.123spring.redis.port=6379spring.redis.password=spring.redis.pool.max-active=8spring.redis.pool.max-wait=-1spring.redis.pool.max-IDle=8spring.redis.pool.min-IDle=0spring.redis.timeout=0
3.创建cache包,然后创建两个类,一个ApplicationContextHolder实现ApplicationContextAware接口,具体内容如下
package com.ruijIE.SpringBootandRedis.cache;import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class ApplicationContextHolder implements ApplicationContextAware { private static ApplicationContext applicationContext; @OverrIDe public voID setApplicationContext(ApplicationContext ctx) throws BeansException { applicationContext = ctx; } /** * Get application context from everywhere * * @return */ public static ApplicationContext getApplicationContext() { return applicationContext; } /** * Get bean by class * * @param clazz * @param <T> * @return */ public static <T> T getBean(Class<T> clazz) { return applicationContext.getBean(clazz); } /** * Get bean by class name * * @param name * @param <T> * @return */ public static <T> T getBean(String name) { return (T) applicationContext.getBean(name); }}
4.创建RedisCache类实现Cache接口,具体内容如下:
package com.ruijIE.SpringBootandRedis.cache;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 java.util.concurrent.TimeUnit;import java.util.concurrent.locks.ReaDWriteLock;import java.util.concurrent.locks.reentrantreadwritelock;public class RedisCache implements Cache { private static final Logger logger = LoggerFactory.getLogger(RedisCache.class); private final ReaDWriteLock reaDWriteLock = new reentrantreadwritelock(); private final String ID; // cache instance ID private Redistemplate redistemplate; private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis过期时间 public RedisCache(String ID) { if (ID == null) { throw new IllegalArgumentException("Cache instances require an ID"); } this.ID = ID; } @OverrIDe public String getID() { return ID; } /** * Put query result to redis * * @param key * @param value */ @OverrIDe public voID putObject(Object key,Object value) { try { Redistemplate redistemplate = getRedistemplate(); ValueOperations opsForValue = redistemplate.opsForValue(); opsForValue.set(key,value,EXPIRE_TIME_IN_MINUTES,TimeUnit.MINUTES); logger.deBUG("Put query result to redis"); } catch (Throwable t) { logger.error("Redis put Failed",t); } } /** * Get cached query result from redis * * @param key * @return */ @OverrIDe public Object getobject(Object key) { try { Redistemplate redistemplate = getRedistemplate(); ValueOperations opsForValue = redistemplate.opsForValue(); logger.deBUG("Get cached query result from redis"); System.out.println("****"+opsForValue.get(key).toString()); return opsForValue.get(key); } catch (Throwable t) { logger.error("Redis get Failed,fail over to db",t); return null; } } /** * Remove cached query result from redis * * @param key * @return */ @OverrIDe @SuppressWarnings("unchecked") public Object removeObject(Object key) { try { Redistemplate redistemplate = getRedistemplate(); redistemplate.delete(key); logger.deBUG("Remove cached query result from redis"); } catch (Throwable t) { logger.error("Redis remove Failed",t); } return null; } /** * Clears this cache instance */ @OverrIDe public voID clear() { Redistemplate redistemplate = getRedistemplate(); redistemplate.execute((RedisCallback) connection -> { connection.flushDb(); return null; }); logger.deBUG("Clear all the cached query result from redis"); } /** * This method is not used * * @return */ @OverrIDe public int getSize() { return 0; } @OverrIDe public ReaDWriteLock getReaDWriteLock() { return reaDWriteLock; } private Redistemplate getRedistemplate() { if (redistemplate == null) { redistemplate = ApplicationContextHolder.getBean("redistemplate"); } return redistemplate; }}
5.实体类中要实现Serializable接口,并且要声明序列号
private static final long serialVersionUID = -2566441764189220519L;
6.开启Mybatis的二级缓存
在pom.xml配置文件中配置
mybatis.configuration.cache-enabled=true
在mapper接口中加入
@Cachenamespace(implementation=(com.demo.testdemo.cache.RedisCache.class))
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。
总结以上是内存溢出为你收集整理的SpringBoot+Mybatis项目使用Redis做Mybatis的二级缓存的方法全部内容,希望文章能够帮你解决SpringBoot+Mybatis项目使用Redis做Mybatis的二级缓存的方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)