多层缓存设计
是什么多级缓存缓存层级策略面临的问题解决方式多级缓存解决什么问题涉及的技术本地缓存技术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); } }总结多级缓存是用可控的复杂度换取极致的性能和系统高可用
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2408171.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!