在Ubuntu上使用Java缓存技术可结合本地缓存库或分布式缓存系统,以下是具体方法及示例:
-
本地缓存(轻量级场景)
-
Guava Cache:适合简单键值缓存,支持过期策略(如基于时间或容量)。
// 添加依赖:Maven中引入 guava --> // 代码示例 Cachecom.google.guava guava31.1-jre cache = CacheBuilder.newBuilder() .maximumSize(1000) .expireAfterWrite(10, TimeUnit.MINUTES) .build(); cache.put("key1", "value1"); String value = cache.getIfPresent("key1"); -
Caffeine:高性能本地缓存,支持异步加载和多种淘汰策略(如LRU)。
// 添加依赖:Maven中引入 caffeine --> // 代码示例 Cachecom.github.ben-manes.caffeine caffeine3.1.8 cache = Caffeine.newBuilder() .maximumSize(1000) .expireAfterWrite(5, TimeUnit.MINUTES) .build();
-
-
分布式缓存(高并发/分布式场景)
- Redis:支持多种数据结构(字符串、哈希等)和持久化,适合跨服务共享数据。
// 添加依赖:Maven中引入 jedis --> // 代码示例 Jedis jedis = new Jedis("localhost", 6379); jedis.set("key1", "value1"); jedis.expire("key1", 3600); // 设置过期时间(秒) String value = jedis.get("key1");redis.clients jedis4.3.1
- Redis:支持多种数据结构(字符串、哈希等)和持久化,适合跨服务共享数据。
-
缓存策略与工具集成
- Spring Cache:通过注解(@Cacheable、@CacheEvict)简化缓存操作,支持Ehcache、Redis等实现。
// 添加依赖:Spring Boot Starter Cache --> // 配置缓存管理器(以Redis为例) @Bean public CacheManager cacheManager(RedisConnectionFactory factory) { return RedisCacheManager.create(factory); } // 使用注解缓存方法结果 @Cacheable(value = "myCache", key = "#id") public String getDataById(String id) { // 数据库查询逻辑 }org.springframework.boot spring-boot-starter-cache
- Spring Cache:通过注解(@Cacheable、@CacheEvict)简化缓存操作,支持Ehcache、Redis等实现。
-
注意事项
- 本地缓存适用于单机环境,分布式缓存需确保服务间数据一致性。
- 合理设置缓存过期时间,避免数据过期或内存溢出。
- 生产环境中建议结合监控工具(如RedisInsight、Prometheus)跟踪缓存命中率和性能。