欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

SpringBoot+Mybatis项目使用Redis做Mybatis的二级缓存的方法

时间:2020-12-21 18:53:47|栏目:JAVA代码|点击:

介绍

使用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=0
spring.redis.host=172.16.3.123
spring.redis.port=6379
spring.redis.password=
spring.redis.pool.max-active=8
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.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;

@Component
public 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))

上一篇:IDEA 2019.2.3破解激活教程(亲测有效)

栏    目:JAVA代码

下一篇:老生常谈 Java中的继承(必看)

本文标题:SpringBoot+Mybatis项目使用Redis做Mybatis的二级缓存的方法

本文地址:http://www.codeinn.net/misctech/35131.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有