iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >SpringBoot+Mybatis项目中如何使用Redis做Mybatis的二级缓存
  • 511
分享到

SpringBoot+Mybatis项目中如何使用Redis做Mybatis的二级缓存

springbootredismybatis 2023-05-30 19:05:20 511人浏览 八月长安
摘要

这篇文章给大家分享的是有关SpringBoot+mybatis项目中如何使用Redis做Mybatis的二级缓存的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。介绍使用mybatis时可以使用二级缓存提高查询速度,

这篇文章给大家分享的是有关SpringBoot+mybatis项目中如何使用Redis做Mybatis的二级缓存的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

介绍

使用mybatis时可以使用二级缓存提高查询速度,进而改善用户体验。

使用Redis做mybatis的二级缓存可是内存可控<如将单独的服务器部署出来用于二级缓存>,管理方便。

在pom.xml文件中引入redis依赖

<dependency>  <groupId>org.springframework.boot</groupId>  <artifactId>spring-boot-starter-data-redis</artifactId></dependency>

在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

创建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;  }    public static ApplicationContext getApplicationContext() {    return applicationContext;  }    public static <T> T getBean(Class<T> clazz) {    return applicationContext.getBean(clazz);  }    public static <T> T getBean(String name) {    return (T) applicationContext.getBean(name);  }}

创建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;  }    @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);    }  }    @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;    }  }    @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;  }    @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;  }}

实体类中要实现Serializable接口,并且要声明序列号

private static final long serialVersionUID = -2566441764189220519L;

开启Mybatis的二级缓存

在pom.xml配置文件中配置

mybatis.configuration.cache-enabled=true

在mapper接口中加入

@CacheNamespace(implementation=(com.demo.testdemo.cache.RedisCache.class))

感谢各位的阅读!关于“SpringBoot+Mybatis项目中如何使用Redis做Mybatis的二级缓存”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

--结束END--

本文标题: SpringBoot+Mybatis项目中如何使用Redis做Mybatis的二级缓存

本文链接: https://www.lsjlt.com/news/220355.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作