Mybatis缓存(一级缓存、二级缓存)

Mybatis缓存(一级缓存、二级缓存)

Mybatis缓存分为一级缓存、二级缓存。Mybatis一级缓存默认是开启的;二级缓存全局开关默认也是开启的,但需要配置CacheNamespace才可生效!
以Mybatis-plus为例

mybatis-plus:
  mapper-locations: classpath*:mapper/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
    default-statement-timeout: 300
    # mybatis二级缓存全局开关
    cache-enabled: true
    # mybatis一级缓存作用域(session、statement)
    local-cache-scope: session

一、Mybatis一级缓存

1.缓存模式为只读模式,返回对象本身而非副本;

2.无法禁用,但可通过local-cache-scope: statement调整作用范围;作用域为statement“等效”于禁用(一个statement可包含多个SQL,此时无法完全禁用)。

二、Mybatis二级缓存

1.缓存模式默认为读写模式,返回对象副本(对象序列化),可设置readWrite属性进行调整。

@CacheNamespace(flushInterval = 600000, size = 4096, readWrite = true)

2.可禁用

mybatis-plus:
  configuration:
    # mybatis二级缓存全局开关
    cache-enabled: false

缓存默认实现类:org.apache.ibatis.cache.impl.PerpetualCache

  • PerpetualCache使用本地内存(集群模式下慎用);
  • 使用装饰者设计模式,为缓存类提供更加丰富的功能org.apache.ibatis.mapping.CacheBuilder#setStandardDecorators。

3.自动刷新缓存

同一namespace下修改、删除数据时,缓存自动刷新。刷新其它namespace下缓存,使用@CacheNamespaceRef注解。

4.手动刷新缓存

package com.example.demo.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.demo.entity.CommParamDefEntity;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Select;

/**
 * @author ouruyi
 */
public interface CommonMapper extends BaseMapper<CommParamDefEntity> {
    /**
     * 刷新Mybatis二级缓存(一级缓存也会刷新)
     * @return 'x'
     */
    @Options(useCache = false, flushCache = Options.FlushCachePolicy.TRUE)
    @Select("SELECT 'x' AS X FROM DUAL")
    String flushCache();
}

三、性能调优

  • 避免动态参数作为查询参数;例如当前系统时间作为查询参数导致mybatis缓存失效;
  • redis null值击穿
  • 冷热数据分离,不建议将冷数据放到缓存,防止缓存被占满。(LRU)
  • 合适的日志实现类
mybatis-plus:
  configuration:
  	# 此处为mybatis-plus通过system.out输出日志到控制台,影响性能(禁用可提升数倍)
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

改为:

mybatis-plus:
  configuration:
    log-impl: org.apache.ibatis.logging.slf4j.Slf4jImpl
  • 连接池配置
druid:
  filters: stat,config
  min-idle: 10
  max-active: 100
  max-pool-prepared-statement-per-connection-size: 20
  min-evictable-idle-time-millis: 300000
  initial-size: 10
  max-wait: 60000
  time-between-eviction-runs-millis: 120000
  pool-prepared-statements: true
  # 高并发性能低
  test-on-borrow: false
  test-on-return: false
  test-while-idle: true
  # 持活,检测间隔默认1分钟(不宜超过3分钟,华为防火墙跨网段切断空闲连接时限3分钟)
  keep-alive: false
  validation-query: SELECT 'x' FROM DUAL
  # 校验超时1秒
  validation-query-timeout: 1
  • 合适的线程池、数据库连接池

版权声明:本文为ory001原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。