万隆的笔记 万隆的笔记
博文索引
笔试面试
  • 在线学站

    • 菜鸟教程 (opens new window)
    • 入门教程 (opens new window)
    • Coursera (opens new window)
  • 在线文档

    • w3school (opens new window)
    • Bootstrap (opens new window)
    • Vue (opens new window)
    • 阿里开发者藏经阁 (opens new window)
  • 在线工具

    • tool 工具集 (opens new window)
    • bejson 工具集 (opens new window)
    • 文档转换 (opens new window)
  • 更多在线资源
  • Changlog
  • Aboutme
GitHub (opens new window)
博文索引
笔试面试
  • 在线学站

    • 菜鸟教程 (opens new window)
    • 入门教程 (opens new window)
    • Coursera (opens new window)
  • 在线文档

    • w3school (opens new window)
    • Bootstrap (opens new window)
    • Vue (opens new window)
    • 阿里开发者藏经阁 (opens new window)
  • 在线工具

    • tool 工具集 (opens new window)
    • bejson 工具集 (opens new window)
    • 文档转换 (opens new window)
  • 更多在线资源
  • Changlog
  • Aboutme
GitHub (opens new window)
  • Redis

    • Redis简介
    • 缓存的认识
    • Linux安装Redis的正确方式
    • Redis数据类型
    • Redis底层数据结构
    • Redis回收策略与缓存过期
    • Redis持久化
    • Redis发布与订阅
    • Redis事务
    • Redis Lua脚本
    • Redis 慢查询
    • Redis 监视器
    • Redis通讯协议
    • Redis事件处理机制与NIO演进
    • Redis 常用命令
    • Redis与MyBatis整合
      • pom.xml
      • application.yml
      • 缓存实现
      • 开启增加二级缓存
      • Application
    • Spring、SpringBoot整合Redis
  • 集群架构

  • Redis
  • Redis
2022-04-01
目录

Redis与MyBatis整合

# Redis与MyBatis整合

Redis与MyBatis整合指Redis做MyBatis的二级缓存。整合参考如下:

# pom.xml

添加Redis依赖

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

# application.yml

添加Redis配置

spring:
  # 数据源配置
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/demo?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

# mybatis配置
mybatis:
  typeAliasesPackage: com.example.rcache.entity
  mapperLocations: classpath:mapper/*.xml

# redis 配置
spring.redis:
  database: 0 # Redis数据库索引(默认为0)
  timeout: 10000 # 连接超时时间(毫秒)
  pool:
    max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
    max-idle: 8 # 连接池中的最大空闲连接
    max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
    min-idle: 0 # 连接池中的最小空闲连接
  cluster:
    nodes:
      - 192.168.0.104:7001
      - 192.168.0.104:7002
      - 192.168.0.104:7003

# 缓存实现

ApplicationContextHolder 用于注入RedisTemplate

@Component 
public class ApplicationContextHolder implements ApplicationContextAware { 
  private static ApplicationContext ctx; 
  
  /** 
  * 向工具类注入applicationContext 
  */
  @Override 
  public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { 
    // ctx就是注入的applicationContext
    ctx = applicationContext;   
  }
  
  public static ApplicationContext getCtx() { 
    return ctx; 
  }
  
  public static <T> T getBean(Class<T> tClass) { 
    return ctx.getBean(tClass); 
  }
  
  @SuppressWarnings("unchecked") 
  public static <T> T getBean(String name) { 
    return (T) ctx.getBean(name); 
  } 
  
}

使用redis实现mybatis二级缓存的工具类,参考实现

/** 
* 使用redis实现mybatis二级缓存 
*/ 
public class RedisCache implements Cache { 
  
  // 缓存对象唯一标识 orm的框架都是按对象的方式缓存
  private final String id; 
  
  // 用于事务性缓存操作的读写锁 
  private static ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); 
  
  // Redis的模板负责将缓存对象写到redis服务器
  private RedisTemplate redisTemplate; 
  
  // 缓存对象的是失效时间,30分钟 
  private static final long EXPRIRE_TIME_IN_MINUT = 30; 
  
  // 构造方法,把对象唯一标识传进来 
  public RedisCache(String id) { 
    if (id == null) { 
      throw new IllegalArgumentException("缓存对象id是不能为空"); 
    }
    this.id = id; 
  }
  
  @Override 
  public String getId() { 
    return this.id; 
  }
  
  /** 
   * 给模板对象RedisTemplate赋值,并传出去 
   */
  private RedisTemplate getRedisTemplate() { 
    if (redisTemplate == null) { 
      // 每个连接池的连接都要获得
      RedisTemplate redisTemplate = ApplicationContextHolder.getBean("redisTemplate"); 
    }
    return redisTemplate; 
  }
  
  /** 
  * 保存缓存对象的方法
  */
  @Override 
  public void putObject(Object key, Object value) { 
    try {
      RedisTemplate redisTemplate = getRedisTemplate(); 
      // 使用redisTemplate得到值操作对象 
      ValueOperations operation = redisTemplate.opsForValue(); 
      // 使用值操作对象operation设置缓存对象 
      operation.set(key, value, EXPRIRE_TIME_IN_MINUT, TimeUnit.MINUTES); 
      // TimeUnit.MINUTES系统当前时间的分钟数 
      System.out.println("缓存对象保存成功"); 
    } catch (Throwable t) { 
      System.out.println("缓存对象保存失败" + t); 
    } 
  }
  
  /** 
   * 获取缓存对象的方法
   */
  @Override 
  public Object getObject(Object key) { 
    try {
      RedisTemplate redisTemplate = getRedisTemplate(); 
      ValueOperations operations = redisTemplate.opsForValue(); 
      Object result = operations.get(key); 
      System.out.println("获取缓存对象"); 
      return result;
    } catch (Throwable t) { 
      System.out.println("缓存对象获取失败" + t); 
      return null; 
    } 
  }
  
  /** 
   * 删除缓存对象
   */
  @Override 
  public Object (Object key) { 
    try {
      RedisTemplate redisTemplate = getRedisTemplate(); 
      redisTemplate.delete(key); 
      System.out.println("删除缓存对象成功!"); 
    } catch (Throwable t) { 
      System.out.println("删除缓存对象失败!" + t); 
    }
    return null; 
  }
  
  /** 
   * 清空缓存对象 当缓存的对象更新了,就执行此方法
   */
  @Override 
  public void clear() { 
    RedisTemplate redisTemplate = getRedisTemplate(); 
    // 回调函数 
    redisTemplate.execute((RedisCallback) collection -> { 
      collection.flushDb(); 
      return null; 
    }); 
    System.out.println("清空缓存对象成功!"); 
  }
  
  /**
   * 可选实现的方法 
   */
  @Override 
  public int getSize() { 
    return 0; 
  }
  
  @Override public ReadWriteLock getReadWriteLock() { 
    return readWriteLock; 
  } 
  
}

# 开启增加二级缓存

可以在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.example.rcache.dao.UserDao" > 
  ......
  
  <cache type="com.example.rcache.utils.RedisCache" />
  
  ......
</mapper>

# Application

在启动类中增加开启缓存注解@EnableCaching

@SpringBootApplication 
@MapperScan("com.example.rache.dao") 
@EnableCaching 
public class Application { 
  public static void main(String[] args) { 
    SpringApplication.run(RcacheApplication.class, args);
  } 
}
上次更新: 5/30/2023, 11:42:20 PM
Spring、SpringBoot整合Redis

Spring、SpringBoot整合Redis→

最近更新
01
2025
01-15
02
Elasticsearch面试题
07-17
03
Elasticsearch进阶
07-16
更多文章>
Theme by Vdoing
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式