二级缓存机制原理详解
1. 整体架构
MyBatis-Plus二级缓存采用装饰器模式实现,核心组件包括:
- Cache接口:定义缓存基本操作
- PerpetualCache:基础缓存实现(HashMap)
- 装饰器:如LruCache、FifoCache等
- TransactionalCache:事务缓存管理器
2. 工作流程
-
初始化阶段:
- 解析Mapper XML中的<cache>配置
- 创建基础缓存实例
- 根据配置添加装饰器
-
查询流程:
sequenceDiagram participant Client participant SqlSession participant Executor participant Cache participant DB Client->>SqlSession: 执行查询 SqlSession->>Executor: query() Executor->>Cache: 检查缓存 alt 缓存命中 Cache-->>Executor: 返回缓存结果 else 缓存未命中 Executor->>DB: 执行查询 DB-->>Executor: 返回结果 Executor->>Cache: 缓存结果 end Executor-->>SqlSession: 返回结果 SqlSession-->>Client: 返回结果 -
更新流程:
sequenceDiagram participant Client participant SqlSession participant Executor participant Cache participant DB Client->>SqlSession: 执行更新 SqlSession->>Executor: update() Executor->>DB: 执行SQL DB-->>Executor: 返回影响行数 Executor->>Cache: 清除相关缓存 Executor-->>SqlSession: 返回结果 SqlSession-->>Client: 返回结果
3. 关键实现细节
- 缓存键生成:基于Mapper ID + 方法参数 + SQL + 分页等生成唯一键
- 事务支持:通过TransactionalCacheManager管理事务提交/回滚时的缓存操作
- 序列化:默认使用JVM序列化,可配置为其他序列化方式
生产案例详细实现步骤
案例1:电商商品缓存系统
- 基础配置
<!-- mybatis-config.xml -->
<configuration>
<settings>
<setting name="cacheEnabled" value="true"/>
<!-- 配置缓存序列化方式 -->
<setting name="defaultCacheType" value="com.example.MyCustomCache"/>
</settings>
</configuration>
- Mapper配置
<!-- ProductMapper.xml -->
<mapper namespace="com.example.mapper.ProductMapper">
<cache
type="org.mybatis.caches.redis.RedisCache"
eviction="LRU"
flushInterval="300000"
size="1024"
readOnly="false"/>
<select id="selectById" resultType="Product" useCache="true">
SELECT * FROM product WHERE id = #{id}
</select>
</mapper>
- 服务层实现

最低0.47元/天 解锁文章
176万+

被折叠的 条评论
为什么被折叠?



