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

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"/>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot是一个用于快速构建基于Spring框架的Java应用程序的开发框架。它简化了Spring应用程序的配置和部署过程,提供了一种快速开发的方式。 MyBatis是一个持久层框架,它可以将Java对象与数据库表进行映射,并提供了灵活的SQL查询和更新操作。MyBatis通过XML或注解的方式来配置SQL语句和映射关系。 Redis是一个开源的内存数据库,它支持多种数据结构(如字符串、哈希、列表、集合、有序集合等),并提供了丰富的操作命令。Redis具有高性能、高可用性和可扩展性的特点,常用于缓存、消息队列、计数器等场景。 MySQL是一个开源的关系型数据库管理系统,它支持多用户、多线程和多表操作。MySQL具有良好的性能和稳定性,并且拥有丰富的功能和工具。 将Spring BootMyBatisRedis和MySQL结合使用可以实现一个完整的Java应用程序。Spring Boot提供了便捷的配置和集成方式,可以轻松地将MyBatis和MySQL集成到应用程序中。同时,通过使用Redis作为缓存,可以提高应用程序的性能和响应速度。 具体来说,可以使用Spring Boot的自动配置功能来集成MyBatis和MySQL。通过配置数据源和MyBatis的Mapper接口,可以实现对数据库的访问和操作。同时,可以使用Redis作为缓存,提高数据的读取速度和响应性能。 总结起来,Spring Boot+MyBatis+Redis+MySQL的组合可以实现一个高性能、可扩展的Java应用程序,提供了方便的开发和部署方式,适用于各种类型的应用场景。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值