当前位置: 首页 > news >正文

构建高可用二级缓存系统

二级缓存机制原理详解

1. 整体架构

MyBatis-Plus二级缓存采用装饰器模式实现,核心组件包括:

  • Cache接口‌:定义缓存基本操作
  • PerpetualCache‌:基础缓存实现(HashMap)
  • 装饰器‌:如LruCache、FifoCache等
  • TransactionalCache‌:事务缓存管理器

2. 工作流程

  1. 初始化阶段‌:

    • 解析Mapper XML中的<cache>配置
    • 创建基础缓存实例
    • 根据配置添加装饰器
  2. 查询流程‌:

    sequenceDiagramparticipant Clientparticipant SqlSessionparticipant Executorparticipant Cacheparticipant DBClient->>SqlSession: 执行查询SqlSession->>Executor: query()Executor->>Cache: 检查缓存alt 缓存命中Cache-->>Executor: 返回缓存结果else 缓存未命中Executor->>DB: 执行查询DB-->>Executor: 返回结果Executor->>Cache: 缓存结果endExecutor-->>SqlSession: 返回结果SqlSession-->>Client: 返回结果
    

  3. 更新流程‌:

    sequenceDiagramparticipant Clientparticipant SqlSessionparticipant Executorparticipant Cacheparticipant DBClient->>SqlSession: 执行更新SqlSession->>Executor: update()Executor->>DB: 执行SQLDB-->>Executor: 返回影响行数Executor->>Cache: 清除相关缓存Executor-->>SqlSession: 返回结果SqlSession-->>Client: 返回结果
    

3. 关键实现细节

  • 缓存键生成‌:基于Mapper ID + 方法参数 + SQL + 分页等生成唯一键
  • 事务支持‌:通过TransactionalCacheManager管理事务提交/回滚时的缓存操作
  • 序列化‌:默认使用JVM序列化,可配置为其他序列化方式

生产案例详细实现步骤

案例1:电商商品缓存系统

  1. 基础配置
<!-- mybatis-config.xml -->
<configuration><settings><setting name="cacheEnabled" value="true"/><!-- 配置缓存序列化方式 --><setting name="defaultCacheType" value="com.example.MyCustomCache"/></settings>
</configuration>
  1. 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>
  1. 服务层实现
@Service
public class ProductServiceImpl implements ProductService {@Autowiredprivate ProductMapper productMapper;// 带缓存穿透保护的查询public Product getProductWithCache(Long id) {// 1. 先查缓存Product product = productMapper.selectById(id);if (product != null) {return product;}// 2. 缓存不存在,查数据库product = productMapper.selectFromDb(id);if (product == null) {// 防止缓存穿透:缓存空对象product = new Product();product.setId(id);product.setName("NULL_OBJECT");productMapper.cacheNullObject(product);} else {// 放入缓存productMapper.cacheProduct(product);}return product;}@Transactionalpublic void updateProduct(Product product) {// 1. 更新数据库productMapper.updateById(product);// 2. 清除缓存productMapper.clearCache(product.getId());// 3. 异步重建缓存CompletableFuture.runAsync(() -> {Product freshProduct = productMapper.selectFromDb(product.getId());productMapper.cacheProduct(freshProduct);});}
}
  1. 自定义Redis缓存实现
public class CustomRedisCache implements Cache {private final String id;private final RedisTemplate<String, Object> redisTemplate;public CustomRedisCache(String id) {this.id = id;this.redisTemplate = SpringContextHolder.getBean("redisTemplate");}@Overridepublic String getId() {return this.id;}@Overridepublic void putObject(Object key, Object value) {// 自定义序列化逻辑redisTemplate.opsForValue().set(generateRedisKey(key), serialize(value),30, TimeUnit.MINUTES // 设置TTL);}// 其他方法实现...
}

案例2:多级缓存策略

  1. 配置多级缓存
@Configuration
public class CacheConfig {@Beanpublic Cache productCache() {// 一级缓存:本地缓存(Caffeine)CaffeineCache localCache = new CaffeineCache("localProductCache",Caffeine.newBuilder().maximumSize(1000).expireAfterWrite(5, TimeUnit.MINUTES).build());// 二级缓存:Redis缓存RedisCache redisCache = new RedisCache("redisProductCache");// 构建多级缓存return new MultiLevelCache(localCache, redisCache);}
}
  1. 多级缓存实现
public class MultiLevelCache implements Cache {private final Cache[] caches;public MultiLevelCache(Cache... caches) {this.caches = caches;}@Overridepublic Object getObject(Object key) {// 按顺序查询缓存for (Cache cache : caches) {Object value = cache.getObject(key);if (value != null) {// 填充上级缓存for (Cache upperCache : getUpperCaches(cache)) {upperCache.putObject(key, value);}return value;}}return null;}// 其他方法实现...
}

生产环境注意事项

  1. 缓存一致性解决方案‌:

    • 使用消息队列实现缓存更新
    @RabbitListener(queues = "cache.update.queue")
    public void handleCacheUpdate(CacheUpdateMessage message) {if (message.getType().equals("PRODUCT")) {productMapper.clearCache(message.getId());}
    }
    

  2. 监控指标采集‌:

public class MonitoredCache implements Cache {private final Cache delegate;private final CacheMetrics metrics;@Overridepublic Object getObject(Object key) {long start = System.currentTimeMillis();try {Object value = delegate.getObject(key);metrics.recordHit(value != null);metrics.recordLatency(System.currentTimeMillis() - start);return value;} catch (Exception e) {metrics.recordError();throw e;}}// 其他方法...
}
  1. 缓存预热策略‌:
@PostConstruct
public void preloadHotProducts() {List<Long> hotProductIds = productMapper.selectHotProductIds();hotProductIds.parallelStream().forEach(id -> {Product product = productMapper.selectById(id);// 主动放入缓存productMapper.cacheProduct(product);});
}

通过以上详细实现,可以构建一个高性能、高可用的二级缓存系统,适用于各种生产环境场景。

下面是springboot用法:


<?xml version="1.0" encoding="UTF-8"?>
<project><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.4</version></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.5.3.1</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies>
</project>spring:datasource:url: jdbc:mysql://localhost:3306/testusername: rootpassword: 123456driver-class-name: com.mysql.cj.jdbc.Driverredis:host: localhostport: 6379password: database: 0mybatis-plus:configuration:cache-enabled: true@Configuration
public class RedisCacheConfig {@Beanpublic RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(factory);template.setKeySerializer(new StringRedisSerializer());template.setValueSerializer(new GenericJackson2JsonRedisSerializer());return template;}@Beanpublic RedisCacheManager cacheManager(RedisConnectionFactory factory) {RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofMinutes(30)).serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())).serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));return RedisCacheManager.builder(factory).cacheDefaults(config).transactionAware().build();}
}@CacheNamespace(implementation = RedisCache.class, eviction = RedisCache.class)
public interface UserMapper extends BaseMapper<User> {@Options(useCache = true)@Select("SELECT * FROM user WHERE id = #{id}")User selectUserById(Long id);@CacheEvict@Update("UPDATE user SET name=#{name} WHERE id=#{id}")int updateUserName(@Param("id") Long id, @Param("name") String name);
}@Service
public class UserService {@Autowiredprivate UserMapper userMapper;@Cacheable(key = "#id", unless = "#result == null")public User getUserById(Long id) {return userMapper.selectById(id);}@Transactional@CacheEvict(key = "#user.id")public void updateUser(User user) {userMapper.updateById(user);}@CacheEvict(allEntries = true)public void clearAllCache() {// 清空所有缓存}
}@Configuration
@MapperScan("com.example.mapper")
public class MyBatisPlusConfig {@Beanpublic MybatisPlusInterceptor mybatisPlusInterceptor() {MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));return interceptor;}@Beanpublic ConfigurationCustomizer configurationCustomizer() {return configuration -> {configuration.setCacheEnabled(true);configuration.setLocalCacheScope(LocalCacheScope.SESSION);};}
}
  1. @CacheNamespace(MyBatis注解)
  • 作用:在Mapper接口级别声明启用二级缓存
  • 核心属性:
    • implementation:指定自定义缓存实现类(默认PerpetualCache)
    • eviction:指定缓存淘汰策略(LRU/FIFO等)
    • flushInterval:缓存刷新间隔(毫秒)
    • size:缓存最大容量
  • 示例:

javaCopy Code

@CacheNamespace(implementation = RedisCache.class, eviction = FifoCache.class, flushInterval = 60000) public interface UserMapper {...}

  1. @Options(MyBatis注解)
  • 作用:为单个SQL语句提供额外配置选项
  • 常用属性:
    • useCache:是否使用二级缓存(默认true)
    • flushCache:执行后是否清空缓存(默认false)
    • timeout:查询超时时间(秒)
  • 示例:

javaCopy Code

@Options(useCache = true, flushCache = false, timeout = 10) @Select("SELECT * FROM users WHERE id = #{id}") User findById(Long id);

  1. @CacheEvict(Spring缓存注解)
  • 作用:方法执行后清除指定缓存
  • 关键属性:
    • value/cacheNames:目标缓存名称
    • key:要清除的缓存键(支持SpEL)
    • allEntries:是否清空整个缓存区域
    • beforeInvocation:是否在方法执行前清除
  • 典型使用场景:

javaCopy Code

@CacheEvict(value = "userCache", key = "#user.id") public void updateUser(User user) { // 更新操作后会清除userCache中该用户的缓存 }

三者关系示意图:

  1. @CacheNamespace定义Mapper的缓存策略
  2. @Options控制单个SQL语句的缓存行为
  3. @CacheEvict在Service层维护缓存一致性

生产建议:

  1. 对于读写频繁的数据,建议组合使用@CacheEvict@Cacheable
  2. 分布式环境建议使用Redis等集中式缓存实现
  3. 注意设置合理的缓存过期时间防止脏数据

文章转载自:

http://mP8eHHN1.gtxrw.cn
http://VFIg2w5k.gtxrw.cn
http://wgpmT0qQ.gtxrw.cn
http://XnBHNB0z.gtxrw.cn
http://arYaH5lf.gtxrw.cn
http://31DjhQAv.gtxrw.cn
http://uKwJ2iwc.gtxrw.cn
http://pJVftFAK.gtxrw.cn
http://9Zs35jJV.gtxrw.cn
http://DsPfFY5o.gtxrw.cn
http://puVhp3pF.gtxrw.cn
http://xdO3cU2k.gtxrw.cn
http://uMVxTRmK.gtxrw.cn
http://AZbUQ62U.gtxrw.cn
http://byYWnysg.gtxrw.cn
http://7iSrcOUx.gtxrw.cn
http://KaoJZtgL.gtxrw.cn
http://IYnlDQnN.gtxrw.cn
http://EKIXHcQO.gtxrw.cn
http://e0ayXYm3.gtxrw.cn
http://lnH5bI8p.gtxrw.cn
http://3TIBtecp.gtxrw.cn
http://xc5HAvRV.gtxrw.cn
http://7T4WvRyH.gtxrw.cn
http://0cJyKVVH.gtxrw.cn
http://k1seiLVf.gtxrw.cn
http://3DHXgyhm.gtxrw.cn
http://mgnriXGp.gtxrw.cn
http://AiDtWcVv.gtxrw.cn
http://dP51aFCg.gtxrw.cn
http://www.dtcms.com/a/371639.html

相关文章:

  • hardhat3 框架源码修改后如何使用
  • Photoshop - Photoshop 创建文档
  • 论文阅读:SaTML 2023 A Light Recipe to Train Robust Vision Transformers
  • RocketMQ为什么自研Nameserver而不用zookeeper?
  • 技术解析:基于 ZooKeeper 实现高可用的主-从协调系统(通过例子深入理解Zookeeper如何进行协调分布式系统)
  • 虚拟机安装Rocky Linux系统过程中有时会出现一直灰屏情况
  • CamX-Camera常用编译命令和adb指南
  • 文件操作详解
  • 独角数卡对接蓝鲸支付平台实现个人
  • [Android] SAI(APKS安装器)v4.5
  • MySQL 主从读写分离架构
  • 软件可靠性基本概念
  • 无人机自组网系统的抗干扰技术分析
  • 对比Java学习Go——基础理论篇
  • centos9安装sentinel
  • 小迪安全v2023学习笔记(七十九讲)—— 中间件安全IISApacheTomcatNginxCVE
  • 关键字 const
  • 性能优化——首屏优化
  • Linux网络设备驱动程序深度理解
  • Unity AssetBundle详解
  • 小白AIGC短视频生成的第一课之混元AI视频
  • 通义万相wan2.2视频模型的基础模型与安装应用详解
  • JavaEE 进阶第三期:开启前端入门之旅(三)
  • Linux:NTP服务
  • 【多模态学习】QA3:FFN的作用?Embedding生成方法的BERT和Word2Vec?非线性引入的作用?
  • Tomcat 日志文件名的命名规范
  • 基于单片机的可燃性气体泄漏智能报警系统
  • Ubuntu系统下Python连接国产KingbaseES数据库实现增删改查
  • 【linux kernel 常用数据结构和设计模式】【数据结构 2】【通过一个案例属性list、hlist、rbtree、xarray数据结构使用】
  • 论文阅读:DMD | Improved Distribution Matching Distillation for Fast Image Synthesis