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

多层缓存设计

是什么多级缓存缓存层级策略面临的问题解决方式多级缓存解决什么问题涉及的技术本地缓存技术Caffeine demoGuavaCache demoEhcache demo分布式缓存技术Redis demoMemcached demo总结是什么在数据从源头到用户的访问路径上设置多个不同速度、不同层次的存储介质缓存层来暂存数据多级缓存缓存层级策略本地缓存热点数据、配置信息、用户会话等分布式缓存共享数据、大容量数据、需要持久化的数据数据库完整的业务数据、需要事务保证的数据面临的问题时间差更新分布式缓存后本地缓存还是旧数据网络延迟通知消息可能延迟或丢失节点故障某些节点可能收不到更新通知并发更新多个节点同时更新可能导致数据不一致解决方式主动失效策略主动更新通知删除缓存TTL过期策略配置缓存失效时间版本号机制每次更新递增版本号多级缓存解决什么问题追求极致速度通过将数据放在离用户最近、速度最快的地方内存/本地大幅提升访问速度。保护后端系统层层拦截请求有效减少对数据库和后端服务的压力避免系统被高流量冲垮。平衡成本与性能用少量昂贵的快设备内存配合大量便宜的慢设备磁盘在有限成本下实现高性能和高吞吐。涉及的技术本地缓存技术Caffeine demo?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdcom.jysemel/groupId artifactIdcache/artifactId version1.0-SNAPSHOT/version /parent artifactIdcache-caffeine/artifactId dependencies dependency groupIdcom.github.ben-manes.caffeine/groupId artifactIdcaffeine/artifactId version3.1.8/version /dependency /dependencies /projectpackage com.jysemel.cache; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import java.util.concurrent.TimeUnit; public class CaffeineDemo { public static void main(String[] args) { // 1. 创建缓存配置最大条目数100写入后10分钟过期 CacheString, String cache Caffeine.newBuilder() .maximumSize(100) // 最多缓存100个条目 .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期 .recordStats() // 开启统计信息可选 .build(); // 2. 存入数据 cache.put(key1, value1); cache.put(key2, value2); // 3. 查询数据 String value1 cache.getIfPresent(key1); System.out.println(key1 - value1); // 输出key1 - value1 // 4. 使用get方法如果key不存在则通过函数加载自动存入缓存 String value3 cache.get(key3, CaffeineDemo::computeValue); System.out.println(key3 - value3); // 输出key3 - computed:key3 // 5. 再次获取key3直接从缓存返回不会调用computeValue String value3Again cache.getIfPresent(key3); System.out.println(key3 again - value3Again); // 6. 查看统计信息 System.out.println(缓存统计 cache.stats()); } // 模拟一个较慢的数据加载方法 private static String computeValue(String key) { System.out.println(计算 key 的值...); return computed: key; } }GuavaCache demo?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdcom.jysemel/groupId artifactIdcache/artifactId version1.0-SNAPSHOT/version /parent artifactIdcache-guava-cache/artifactId dependencies dependency groupIdcom.google.guava/groupId artifactIdguava/artifactId version33.2.0-jre/version !-- 使用最新稳定版 -- /dependency /dependencies /projectpackage com.jysemel.cache; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import java.util.concurrent.TimeUnit; public class GuavaCacheDemo { public static void main(String[] args) throws Exception { // 1. 创建缓存最大容量100写入后10分钟过期开启统计信息 CacheString, String cache CacheBuilder.newBuilder() .maximumSize(100) // 最多缓存100个条目 .expireAfterWrite(10, TimeUnit.MINUTES) // 写入后10分钟过期 .recordStats() // 开启命中率统计 .build(); // 2. 存入数据 cache.put(key1, value1); cache.put(key2, value2); // 3. 查询数据 String value1 cache.getIfPresent(key1); System.out.println(key1 - value1); // 输出key1 - value1 // 4. 使用Callable方式如果key不存在则通过给定的Callable加载并自动存入缓存 String value3 cache.get(key3, () - { System.out.println(执行加载逻辑...); return computed: key3; }); System.out.println(key3 - value3); // 输出key3 - computed:key3 // 5. 再次获取key3直接从缓存返回不会再次执行Callable String value3Again cache.getIfPresent(key3); System.out.println(key3 again - value3Again); // 6. 查看统计信息 System.out.println(缓存统计 cache.stats()); } }Ehcache demo?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdcom.jysemel/groupId artifactIdcache/artifactId version1.0-SNAPSHOT/version /parent artifactIdcache-ehcache/artifactId dependencies dependency groupIdorg.ehcache/groupId artifactIdehcache/artifactId version3.10.8/version !-- 使用最新稳定版 -- /dependency /dependencies /projectpackage com.jysemel.cache; import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; public class EhcacheDemo { public static void main(String[] args) { // 1. 创建 CacheManager并预定义名为 demoCache 的缓存配置 // 使用堆内存最多存储 100 个条目并设置存活时间TTL为 10 秒 CacheManager cacheManager CacheManagerBuilder.newCacheManagerBuilder() .withCache(demoCache, CacheConfigurationBuilder.newCacheConfigurationBuilder( Long.class, // Key 类型 String.class, // Value 类型 ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(100, EntryUnit.ENTRIES) // 堆内存中最多 100 个条目 .offheap(10, MemoryUnit.MB) // 可选的堆外内存 ) .withSizeOfMaxObjectSize(1, MemoryUnit.MB) // 对象大小限制 // .withExpiry(ExpiryPolicyBuilder.timeToLiveExpiration(Duration.ofSeconds(10))) // 设置过期策略 ) .build(true); // true 表示初始化 CacheManager // 2. 获取缓存实例 CacheLong, String demoCache cacheManager.getCache(demoCache, Long.class, String.class); // 3. 存入数据 System.out.println(存入数据: key1L, valueHello Ehcache); demoCache.put(1L, Hello Ehcache); // 4. 查询数据 String value demoCache.get(1L); System.out.println(查询 key1L - value); // 5. 查询不存在的数据 String nonExist demoCache.get(99L); System.out.println(查询 key99L - nonExist); // 输出 null // 6. 移除数据 demoCache.remove(1L); System.out.println(移除后查询 key1L - demoCache.get(1L)); // 7. 关闭 CacheManager通常在应用关闭时执行 cacheManager.close(); } }分布式缓存技术Redis demoMemcached demo?xml version1.0 encodingUTF-8? project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instance xsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd modelVersion4.0.0/modelVersion parent groupIdcom.jysemel/groupId artifactIdcache/artifactId version1.0-SNAPSHOT/version /parent artifactIdcache-memcached/artifactId dependencies dependency groupIdnet.spy/groupId artifactIdspymemcached/artifactId version2.12.0/version !-- 使用最新稳定版 -- /dependency /dependencies /projectpackage com.jysemel.cache; import lombok.SneakyThrows; import net.spy.memcached.AddrUtil; import net.spy.memcached.MemcachedClient; import net.spy.memcached.internal.OperationFuture; public class MemcachedDemo { SneakyThrows public static void main(String[] args) { // 1. 创建 Memcached 客户端连接到本地服务器默认端口 11211 // 支持连接多个服务器new MemcachedClient(AddrUtil.getAddresses(server1:11211 server2:11211)); MemcachedClient client new MemcachedClient(AddrUtil.getAddresses(localhost:11211)); System.out.println(✅ 成功连接到 Memcached); // 2. 缓存数据 - set 操作无论是否存在都会写入 String key user:1001; String value Alice; int expiry 3600; // 过期时间秒0 表示永不过期 OperationFutureBoolean setFuture client.set(key, expiry, value); System.out.println(set 结果: (setFuture.get() ? 成功 : 失败)); // 3. 获取数据 - get 操作 Object cachedValue client.get(key); System.out.println(get 结果: cachedValue); // 4. add 操作仅在 key 不存在时添加相当于 INSERT OperationFutureBoolean addFuture client.add(new:key, expiry, new value); System.out.println(add 结果首次: (addFuture.get() ? 成功 : 失败)); // 再次 add 同一个 key 会失败 OperationFutureBoolean addAgainFuture client.add(new:key, expiry, another); System.out.println(add 结果再次: (addAgainFuture.get() ? 成功 : 失败)); // 5. replace 操作仅在 key 存在时替换相当于 UPDATE OperationFutureBoolean replaceFuture client.replace(new:key, expiry, updated value); System.out.println(replace 结果: (replaceFuture.get() ? 成功 : 失败)); System.out.println(replace 后 get: client.get(new:key)); // 6. delete 操作删除 key OperationFutureBoolean deleteFuture client.delete(new:key); System.out.println(delete 结果: (deleteFuture.get() ? 成功 : 失败)); // 7. 批量获取 - getBulk client.set(key1, expiry, value1); client.set(key2, expiry, value2); java.util.MapString, Object bulkResult client.getBulk(key1, key2); System.out.println(批量获取: bulkResult); // 8. 数值操作incr/decr- 需要存储数字类型 client.set(counter, expiry, 10); long newValue client.incr(counter, 5); // 增加 5 System.out.println(incr 后: newValue); newValue client.decr(counter, 3); // 减少 3 System.out.println(decr 后: newValue); } }总结多级缓存是用可控的复杂度换取极致的性能和系统高可用

相关文章:

多层缓存设计

是什么?多级缓存 缓存层级策略面临的问题解决方式 多级缓存解决什么问题涉及的技术 本地缓存技术 Caffeine demoGuavaCache demoEhcache demo 分布式缓存技术 Redis demoMemcached demo 总结 是什么? 在数据从源头到用户的访问路径上,设置多…...

Neeshck-Z-lmage_LYX_v2效果对比:不同推理步数(10/20/30/50)质量分析

Neeshck-Z-lmage_LYX_v2效果对比:不同推理步数(10/20/30/50)质量分析 想用AI画画,但总感觉生成的图片要么细节不够,要么等得花儿都谢了?这背后,一个叫“推理步数”的参数,可能就是关…...

Jimeng LoRA参数详解:LoRA权重精度(fp16/bf16)对dreamlike风格影响

Jimeng LoRA参数详解:LoRA权重精度(fp16/bf16)对dreamlike风格影响 1. 项目背景与测试环境 Jimeng(即梦)LoRA是一个专注于生成梦幻风格图像的轻量级模型,基于Z-Image-Turbo文生图底座构建。这个测试系统专…...

EasyAnimateV5图生视频入门:service.pid进程文件作用与异常清理方法

EasyAnimateV5图生视频入门:service.pid进程文件作用与异常清理方法 1. 理解EasyAnimateV5的核心能力 EasyAnimateV5-7b-zh-InP是一个专门用于图生视频任务的AI模型,它能够将输入的静态图片转换成动态视频。这个模型拥有70亿参数,占用22GB存…...

granite-4.0-h-350m开源镜像教程:支持中文的轻量级AI服务搭建实录

granite-4.0-h-350m开源镜像教程:支持中文的轻量级AI服务搭建实录 1. 快速了解granite-4.0-h-350m模型 granite-4.0-h-350m是一个轻量级的指令跟随模型,专门为资源受限的环境设计。这个模型只有3.5亿参数,但却具备了强大的多语言理解和生成…...

GPEN模型快速上手:GPU算力优化下的高效人脸修复

GPEN模型快速上手:GPU算力优化下的高效人脸修复 1. 项目简介 GPEN(Generative Prior for Face Enhancement)是一个专门针对人脸修复和增强的智能系统。这个模型采用了先进的生成对抗网络技术,能够智能识别并重构图像中的人脸细节…...

为什么选择Cell框架?6大优势让前端开发更简单高效

为什么选择Cell框架?6大优势让前端开发更简单高效 【免费下载链接】cell A self-driving web app framework 项目地址: https://gitcode.com/gh_mirrors/ce/cell Cell是一个由自驱动DOM提供支持的自构建Web应用框架,它以“简单”为核心设计目标&a…...

icomet配置全攻略:max_channels、buffer_size等关键参数调优指南

icomet配置全攻略:max_channels、buffer_size等关键参数调优指南 【免费下载链接】icomet A C1000K comet/push server built with C, for web and mobile app 项目地址: https://gitcode.com/gh_mirrors/ic/icomet icomet是一款基于C构建的高性能comet/push…...

为什么选择GPTeacher?GPT-4生成数据集的7大优势解析

为什么选择GPTeacher?GPT-4生成数据集的7大优势解析 【免费下载链接】GPTeacher A collection of modular datasets generated by GPT-4, General-Instruct - Roleplay-Instruct - Code-Instruct - and Toolformer 项目地址: https://gitcode.com/gh_mirrors/gp/G…...

2000-2024年地级市规模以上工业企业相关数据

数据简介 规模以上工业企业,是指年主营业务收入达到一定规模的工业法人单位。这一标准由国家统计局制定,旨在通过统一口径筛选出对工业经济具有显著贡献的“核心企业”,为政策制定、经济监测和学术研究提供精准数据支撑。 数据名称&#xf…...

2011-2024年各省互联网普及率/互联网宽带接入用户数、城市/农村宽带接入用户

2024-2011年各省互联网普及率/互联网宽带接入用户数、城市/农村宽带接入用户 面板数据无缺失 【计算方法】 互联网普及率每百人中互联网宽带接入用户数 数据范围:全国31个省 数据时间:2011-2024年 数据格式:excel,dta面板数…...

IPED云存储API密钥轮换:定期更新访问凭证的安全策略

IPED云存储API密钥轮换:定期更新访问凭证的安全策略 【免费下载链接】IPED IPED Digital Forensic Tool. It is an open source software that can be used to process and analyze digital evidence, often seized at crime scenes by law enforcement or in a cor…...

IPED内存取证流程:从内存镜像到证据报告的完整指南

IPED内存取证流程:从内存镜像到证据报告的完整指南 【免费下载链接】IPED IPED Digital Forensic Tool. It is an open source software that can be used to process and analyze digital evidence, often seized at crime scenes by law enforcement or in a corp…...

IPED日志分析告警配置:设置邮件与短信通知的方法

IPED日志分析告警配置:设置邮件与短信通知的方法 【免费下载链接】IPED IPED Digital Forensic Tool. It is an open source software that can be used to process and analyze digital evidence, often seized at crime scenes by law enforcement or in a corpor…...

IPED敏感信息脱敏工具:自动替换报告中的敏感数据

IPED敏感信息脱敏工具:自动替换报告中的敏感数据 【免费下载链接】IPED IPED Digital Forensic Tool. It is an open source software that can be used to process and analyze digital evidence, often seized at crime scenes by law enforcement or in a corpor…...

Minimongo远程同步实战:构建实时协作应用的完整流程

Minimongo远程同步实战:构建实时协作应用的完整流程 【免费下载链接】minimongo Client-side in-memory mongodb backed by localstorage with server sync over http 项目地址: https://gitcode.com/gh_mirrors/mi/minimongo Minimongo是一款轻量级客户端数…...

Qwik框架表单开发教程:使用modular-forms打造响应式用户界面

Qwik框架表单开发教程:使用modular-forms打造响应式用户界面 【免费下载链接】modular-forms The modular and type-safe form library for SolidJS, Qwik, Preact and React 项目地址: https://gitcode.com/gh_mirrors/mo/modular-forms modular-forms是一个…...

Monkey365最佳实践:提升微软云安全评估效率的10个技巧

Monkey365最佳实践:提升微软云安全评估效率的10个技巧 【免费下载链接】monkey365 Monkey365 provides a tool for security consultants to easily conduct not only Microsoft 365, but also Azure subscriptions and Azure Active Directory security configurat…...

TIS与数据脱敏工具集成:实现敏感数据的自动化处理

TIS与数据脱敏工具集成:实现敏感数据的自动化处理 【免费下载链接】tis Support agile DataOps Based on Flink, DataX and Flink-CDC, Chunjun with Web-UI 项目地址: https://gitcode.com/GitHub_Trending/ti/tis 在当今数据驱动的时代,敏感数据…...

为什么选择Tai-e-assignments?静态程序分析工具对比与优势

为什么选择Tai-e-assignments?静态程序分析工具对比与优势 【免费下载链接】Tai-e-assignments Tai-e assignments for static program analysis 项目地址: https://gitcode.com/gh_mirrors/ta/Tai-e-assignments Tai-e-assignments是一款专为静态程序分析设…...

Cuik中间表示(IR)探秘:编译器优化的核心引擎原理

Cuik中间表示(IR)探秘:编译器优化的核心引擎原理 【免费下载链接】Cuik A Modern C11 compiler (STILL EARLY) 项目地址: https://gitcode.com/gh_mirrors/cu/Cuik Cuik是一款现代C11编译器,其中间表示(IR)作为编译器优化的…...

从0到1开发图片预览插件:qlImageSize核心功能实现原理探秘

从0到1开发图片预览插件:qlImageSize核心功能实现原理探秘 【免费下载链接】qlImageSize QuickLook and Spotlight plugins to display the dimensions, size and DPI of an image in the title bar instead of the filename. Also preview some unsupported format…...

解密Authority核心组件:Authorizer类如何掌控Rails应用权限

解密Authority核心组件:Authorizer类如何掌控Rails应用权限 【免费下载链接】authority *CURRENTLY UNMAINTAINED*. Authority helps you authorize actions in your Rails app. Its ORM-neutral and has very little fancy syntax; just group your models under o…...

Strapi Documentation完全指南:构建强大API的开源Headless CMS入门

Strapi Documentation完全指南:构建强大API的开源Headless CMS入门 【免费下载链接】documentation Strapi Documentation 项目地址: https://gitcode.com/gh_mirrors/document/documentation Strapi是一款开源的Headless CMS(内容管理系统&#…...

sqlite-gui完全指南:轻量级Windows SQLite编辑器的终极入门教程

sqlite-gui完全指南:轻量级Windows SQLite编辑器的终极入门教程 【免费下载链接】sqlite-gui Lightweight SQLite editor for Windows 项目地址: https://gitcode.com/gh_mirrors/sq/sqlite-gui sqlite-gui是一款专为Windows系统设计的轻量级SQLite编辑器&am…...

favicons-webpack-plugin完全指南:自动生成44种图标格式的终极解决方案

favicons-webpack-plugin完全指南:自动生成44种图标格式的终极解决方案 【免费下载链接】favicons-webpack-plugin Let webpack generate all your favicons and icons for you 项目地址: https://gitcode.com/gh_mirrors/fa/favicons-webpack-plugin favico…...

React-Bulma-Components高级用法:组件组合与自定义

React-Bulma-Components高级用法:组件组合与自定义 【免费下载链接】react-bulma-components React components for Bulma framework 项目地址: https://gitcode.com/gh_mirrors/re/react-bulma-components React-Bulma-Components是基于Bulma框架的React组件…...

为什么选择matrixmultiplication.xyz?5大优势让线性代数学习事半功倍

为什么选择matrixmultiplication.xyz?5大优势让线性代数学习事半功倍 【免费下载链接】matrixmultiplication.xyz 项目地址: https://gitcode.com/gh_mirrors/ma/matrixmultiplication.xyz matrixmultiplication.xyz是一款专为教育设计的交互式矩阵乘法计算…...

SSDTTime跨平台使用指南:在Windows、macOS和Linux上轻松运行

SSDTTime跨平台使用指南:在Windows、macOS和Linux上轻松运行 【免费下载链接】SSDTTime SSDT/DSDT hotpatch attempts. 项目地址: https://gitcode.com/gh_mirrors/ss/SSDTTime SSDTTime是一款强大的SSDT/DSDT热补丁工具,支持在Windows、macOS和L…...

Compose Stability Analyzer Gradle插件使用指南:自动化稳定性验证

Compose Stability Analyzer Gradle插件使用指南:自动化稳定性验证 【免费下载链接】compose-stability-analyzer 🦄 Real-time analysis of Jetpack Compose composable functions stability directly within Android Studio or IntelliJ. 项目地址: …...