博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springboot+mybatis 用redis作二级缓存
阅读量:4967 次
发布时间:2019-06-12

本文共 9080 字,大约阅读时间需要 30 分钟。

1.加入相关依赖包:

4.0.0
springBootD
demo
0.0.1-SNAPSHOT
jar
demo
Demo project for Spring Boot
org.springframework.boot
spring-boot-starter-parent
2.0.3.RELEASE
UTF-8
UTF-8
1.8
      
org.mybatis.spring.boot
mybatis-spring-boot-starter
1.3.2
      
org.springframework.boot
spring-boot-starter-data-redis
org.springframework.boot
spring-boot-starter-web
mysql
mysql-connector-java
runtime
org.springframework.boot
spring-boot-starter-test
test
    
io.springfox
springfox-swagger2
2.6.1
io.springfox
springfox-swagger-ui
2.6.1
org.springframework.boot
spring-boot-maven-plugin
       
org.mybatis.generator
mybatis-generator-maven-plugin
1.3.2
src/main/resources/generatorConfig.xml
true
true
Generate MyBatis Artifacts
generate
org.mybatis.generator
mybatis-generator-core
1.3.2

 

2.springboot配置文件:

#数据库配置spring.datasource.data-username=com.mysql..jdbc.Driverspring.datasource.url=jdbc:mysql://localhost:3306/springboot?seUnicode=true&characterEncoding=utf8&characterSetResults=utf8spring.datasource.username=rootspring.datasource.password=root#redis配置spring.redis.host=localhostspring.redis.port=6379spring.redis.database=1spring.redis.jedis.pool.max-active=8spring.redis.jedis.pool.max-wait= -1msspring.redis.jedis.pool.max-idle=500#mybatismybatis.mapper-locations=classpath*:mybatis/mapper/**/*.xml#开启MyBatis的二级缓存mybatis.configuration.cache-enabled=true#日志配置logging.level.springbootd.demo=debuglogging.level.org.springframework.web=debuglogging.level.org.springframework.transaction=debuglogging.level.org.mybatis=debug

 

3.建立获取spring容器获取bean工具类,通过Spring Aware(容器感知)来获取到ApplicationContext,然后根据ApplicationContext获取容器中的Bean,因为RedisTemplate的bean不能用@Autowired注解注入

 

package springbootd.demo.util;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;import org.springframework.stereotype.Component;@Componentpublic class ApplicationContextHolder implements ApplicationContextAware{    private static ApplicationContext applicationContext;    /**     * 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.     */    public void setApplicationContext(ApplicationContext applicationContext) {        ApplicationContextHolder.applicationContext = applicationContext; // NOSONAR    }    /**     * 取得存储在静态变量中的ApplicationContext.     */    public static ApplicationContext getApplicationContext() {        checkApplicationContext();        return applicationContext;    }    /**     * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.     */    @SuppressWarnings("unchecked")    public static 
T getBean(String name) { checkApplicationContext(); return (T) applicationContext.getBean(name); } /** * 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. */ @SuppressWarnings("unchecked") public static
T getBean(Class
clazz) { checkApplicationContext(); return (T) applicationContext.getBeansOfType(clazz); } /** * 清除applicationContext静态变量. */ public static void cleanApplicationContext() { applicationContext = null; } private static void checkApplicationContext() { if (applicationContext == null) { throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder"); } }}

 

4.实现mybatis缓存接口:

package springbootd.demo.util;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 MybatisRedisCache implements Cache {    private static final Logger logger = LoggerFactory.getLogger(MybatisRedisCache.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 MybatisRedisCache(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    @SuppressWarnings("unchecked")    public void putObject(Object key, Object value) {        RedisTemplate redisTemplate = getRedisTemplate();        ValueOperations opsForValue = redisTemplate.opsForValue();        opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);        logger.debug("Put query result to redis");    }    /**     * Get cached query result from redis     *     * @param key     * @return     */    @Override    public Object getObject(Object key) {        RedisTemplate redisTemplate = getRedisTemplate();        ValueOperations opsForValue = redisTemplate.opsForValue();        logger.debug("Get cached query result from redis");        return opsForValue.get(key);    }    /**     * Remove cached query result from redis     *     * @param key     * @return     */    @Override    @SuppressWarnings("unchecked")    public Object removeObject(Object key) {        RedisTemplate redisTemplate = getRedisTemplate();        redisTemplate.delete(key);        logger.debug("Remove cached query result from redis");        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");    }    @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.在mapper.xml映射文件中开启缓存:

id, pass_word, user_name

 

细节提示:

1.mapper映射接口类要加上@mapper注解,将其添加入ioc容器:

import org.apache.ibatis.annotations.Mapper;import springbootd.demo.mybatisEntity.User;@Mapperpublic interface UserMapper {
User selectByPrimaryKey(Long id);}

或者在springboot入口类加上@MapperScan(basePackages ="包路径")

@SpringBootApplication@MapperScan(basePackages ="springbootd.demo.mybatisDao")public class DemoApplication {    public static void main(String[] args) {        SpringApplication.run(DemoApplication.class, args);    }}

 

转载于:https://www.cnblogs.com/chenziyu/p/9229748.html

你可能感兴趣的文章
排序之有序数组合并
查看>>
springMVC之mvc:interceptors拦截器的用法
查看>>
Java之美[从菜鸟到高手演变]系列之博文阅读导航
查看>>
C#将科大讯飞语音合成文件转换为MULAW音频格式
查看>>
解决使用Rails中使用中文时出现"Your template was not saved as valid UTF-8"的问题
查看>>
LoadRunner配置方案
查看>>
loadrunner解决“服务器正在运行中”方法
查看>>
界面编程之QT的线程20180731
查看>>
三元环计数问题
查看>>
页面内嵌iframe 防止session过期
查看>>
c#冒泡算法
查看>>
socketv 验证客户端链接的合法性
查看>>
iis 启用父目录路径访问
查看>>
javaweb学习总结(四十三)——Filter高级开发
查看>>
paip.函数方法回调机制跟java php python c++的实现
查看>>
Atitit 自然语言处理原理与实现 attilax总结
查看>>
数据库——JDBC
查看>>
第22章:MongoDB-聚合操作--聚合管道--$out
查看>>
Python 列表
查看>>
SpringMVC转发和重定向区别!
查看>>