Springboot+Mybatis,使用redis作为二级缓存

文章展示了如何在SpringBoot应用中集成Redis,使用RedisTemplate作为数据访问对象,并创建一个名为MybatisCache的类来实现MyBatis的二级缓存功能。配置包括了POM依赖、Redis连接配置以及Mapper中的缓存配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. redis的pom依赖

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

2. 配置类

注入RedisTemplate的类MyBatisRedisSpringContext代码:

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @author: y
 * @date: 2023-01-31 18:22
 * @description:
 */
@Component
public class MyBatisRedisSpringContext implements ApplicationContextAware {

     private static ApplicationContext myApplicationContext = null;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        myApplicationContext = applicationContext;
    }

    /**
     * 外部调用ApplicationContext
     */
    public static ApplicationContext getApplication() {
        return myApplicationContext;
    }

    public static <T> T getBean(Class<T> tClass) {
        return myApplicationContext.getBean(tClass);
    }

    @SuppressWarnings("unchecked")
    public static <T> T getBean(String name) {
        return (T) myApplicationContext.getBean(name);
    }
}

使用redis实现二级缓存

import org.apache.ibatis.cache.Cache;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Set;

/**
 * @author: 
 * @date: 2023-01-31 18:34
 * @description: mybaits缓存的
 */
public class MybatisCache implements Cache {

   private final Logger logger = LoggerFactory.getLogger(MybatisCache.class);

    /**
     * 设置key的有效时间,默认给30m
     */
    private final static Integer EXPIRATION_TIME = 30;

    private String id;

    /**
     * redisTemplate
     */
    private RedisTemplate<String, Object> redisTemplate;

    public MybatisCache(String id) {
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    /**
     * 给模板对象RedisTemplate赋值
     */
    private RedisTemplate getRedisTemplate() {
        if (redisTemplate == null) {
            redisTemplate = MyBatisRedisSpringContext.getBean("redisTemplate");;
        }
        return redisTemplate;
    }

    @Override
    public void putObject(Object key, Object value) {
        if(null == redisTemplate){
            redisTemplate = getRedisTemplate();
        }
        redisTemplate.opsForValue().set(key.toString(), value, EXPIRATION_TIME, TimeUnit.SECONDS);
        logger.info("设置缓存成功,key:{}", key);
    }

    @Override
    public Object getObject(Object key) {
        if(null == redisTemplate){
            redisTemplate = getRedisTemplate();
        }
        logger.info("查询缓存key:{}", key);
        Object o = redisTemplate.opsForValue().get(key.toString());
        return o;
    }

    @Override
    public Object removeObject(Object key) {
        if(null == redisTemplate){
            redisTemplate = getRedisTemplate();
        }
        Boolean status = redisTemplate.delete(key.toString());
        logger.info("删除缓存:{},状态:{}", key, status);
        return status;
    }

    @Override
    public void clear() {
        if(null == redisTemplate){
            redisTemplate = getRedisTemplate();
        }
        Set<String> keys = redisTemplate.keys("*" + this.id + "*");
        logger.info("清除缓存:{}", JSONUtil.toJsonStr(keys));
        redisTemplate.delete(keys);
    }

    @Override
    public int getSize() {
        if(null==redisTemplate){
            redisTemplate = getRedisTemplate();
        }
        Integer execute = redisTemplate.execute(new RedisCallback<Integer>() {
            @Override
            public Integer doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize().intValue();
            }
        });
        return execute;
    }
}

3. application.yml

spring:
  redis:
    host: localhost
    port: 6379
## 开启二级缓存    
mybatis-plus:
  configuration:
    cache-enabled: true

4. mapper中的配置

<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.xxx.mapper.common.XXX">
 
    <!--二级缓存的相关信息-->
    <cache type="com.xxx.MybatisCache" eviction="FIFO" flushInterval="3600000" readOnly="true" size="1024"/>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值