欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-22 12:59:40
介绍 使用mybatis时可以使用二级缓存提高查询速度,进而改善用户体验。 使用redis做mybatis的二级缓存可是内存可控<如将单独的服务器部署出来用于二级...

介绍

使用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))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。