Java中本地缓存的4种实现方式总结
Java中本地缓存的4种实现方式总结
更新时间:2025年04月11日 10:04:52 作者:呱牛 do IT
这篇文章主要介绍了Java中本地缓存的4种实现方式,分别是基础缓存实现、、整合和,通过实例代码,详细讲解了每种缓存技术的特点和使用方法,需要的朋友可以参考下
前言
在Java开发中java缓存技术有哪些,缓存技术是提高应用性能的关键手段之一。
今天,我们来聊聊Java中的四种主流本地缓存技术Java中本地缓存的4种实现方式总结,并通过实例代码帮助大家更好地理解和应用这些技术。
一、基础缓存实现
首先,我们从最基础的缓存实现讲起。
一个简单的缓存系统通常包括缓存实体类、添加、删除、查询和清除缓存的功能。
1. 缓存实体类
缓存实体类用于存储缓存的键值对以及过期时间。
代码如下:。
public class CacheEntity {
private String cacheKey;
private Object cacheValue;
private long expireTime; // 过期时间戳
// 构造方法、getter和setter省略
}
2. 缓存工具类
接下来,我们实现一个缓存工具类,使用作为存储结构,并通过定时任务清除过期数据。
import java.util.concurrent.*;
import java.util.Map;
publicclassCacheUtil {
privatefinalstatic Map CACHE_MAP = newConcurrentHashMap();
privatestaticScheduledExecutorServiceexecutorService= Executors.newSingleThreadScheduledExecutor();
static {
executorService.scheduleAtFixedRate(() -> {
longcurrentTime= System.currentTimeMillis();
CACHE_MAP.values().removeIf(entity -> entity.getExpireTime() < currentTime);
}, 0, 500, TimeUnit.MILLISECONDS);
}
publicstaticvoidput(String key, Object value, long expireTimeInSeconds) {
longexpireTime= System.currentTimeMillis() + expireTimeInSeconds * 1000;
CACHE_MAP.put(key, newCacheEntity(key, value, expireTime));
}
publicstatic Object get(String key) {
CacheEntityentity= CACHE_MAP.get(key);
if (entity == null || entity.getExpireTime() < System.currentTimeMillis()) {
CACHE_MAP.remove(key);
returnnull;
}
return entity.getCacheValue();
}
publicstaticvoiddelete(String key) {
CACHE_MAP.remove(key);
}
publicstaticvoidclear() {
CACHE_MAP.clear();
}
}
测试代码:
public class Test {
public static void main(String[] args) throws InterruptedException {
CacheUtil.put("name", "zzc", 10L);
System.out.println("第一次查询结果:" + CacheUtil.get("name"));
Thread.sleep(2000L);
System.out.println("第二次查询结果:" + CacheUtil.get("name"));
}
}
二、Guava

Guava是提供的一个Java基础库,其中的是一个强大的缓存工具。
1. 使用示例
import com.google.common.cache.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
publicclassTest {
publicstaticvoidmain(String[] args)throws ExecutionException {
LoadingCache cache = CacheBuilder.newBuilder()
.concurrencyLevel(8)
.expireAfterWrite(10, TimeUnit.SECONDS)
.build(newCacheLoader() {
@Override
public String load(String key)throws Exception {
return"default_value";
}
});
cache.put("name", "zzc");
StringnameValue= cache.get("name");
StringageValue= cache.get("age", () -> "default_age");
StringsexValue= cache.get("sex", () -> "key 不存在");
System.out.println("nameValue: " + nameValue);
System.out.println("ageValue: " + ageValue);
System.out.println("sexValue: " + sexValue);
}
}
在上面的代码中,当调用cache.get(key)方法时,如果缓存中不存在对应的keyJava中本地缓存的4种实现方式总结,则会通过的load方法加载默认值。
三、整合
是一个高性能的Java缓存库java缓存技术有哪些,提供了与的无缝整合。
1. 开启缓存功能
在启动类上添加@注解。
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;
@EnableCaching
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
2. 配置缓存管理器
import com.github.benmanes.caffeine.cache.Caffeine;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.caffeine.CaffeineCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableCaching
publicclassCacheConfig {
@Bean("caffeineCacheManager")
public CacheManager cacheManager() {
CaffeineCacheManagercacheManager=newCaffeineCacheManager("userCache");
cacheManager.getCache("userCache").getConfig().setCaffeine(caffeineCacheBuilder());
return cacheManager;
}
Caffeine caffeineCacheBuilder() {
return Caffeine.newBuilder()
.expireAfterWrite(10, TimeUnit.SECONDS)
.maximumSize(100);
}
}
3. 使用缓存注解
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
@Service
publicclassUserService {
// 模拟数据库操作
private Map userMap = newHashMap();
@Cacheable(value = "userCache", key = "#id")
public User getUserById(Integer id) {
// 假设从数据库获取用户数据
Useruser=newUser();
user.setId(id);
user.setName("User" + id);
userMap.put(id, user);
return user;
}
@CacheEvict(value = "userCache", key = "#id")
publicvoiddeleteUserById(Integer id) {
userMap.remove(id);
}
}
四、——阿里巴巴的分布式缓存框架

是阿里巴巴开源的一款基于和Redis的分布式缓存框架,提供了强大的缓存抽象和注解支持。
1. 引入依赖
在pom.xml中添加依赖。
com.alicp.jetcache
jetcache-starter-redis
最新版本号
2. 配置
在.yml中配置。
jetcache:
stat:enable# 开启统计
remote:
default:
type:redis
keyConvertor:fastjson# 序列化方式
valueEncoder:java
valueDecoder:java
poolConfig:
minIdle:5
maxIdle:20
maxTotal:50
host:localhost
port: 6379
3. 使用注解
import com.alicp.jetcache.anno.CacheType;
import com.alicp.jetcache.anno.Cached;
import com.alicp.jetcache.anno.CacheUpdate;
import com.alicp.jetcache.anno.CacheInvalidate;
import org.springframework.stereotype.Service;
@Service
publicclassUserService {
@Cached(name = "userCache", key = "#id", cacheType = CacheType.BOTH)
public String getUser(int id) {
return"用户:" + id;
}
@CacheUpdate(name = "userCache", key = "#id", value = "#user")
publicvoidupdateUser(int id, String user) {
System.out.println("更新用户:" + user);
}
@CacheInvalidate(name = "userCache", key = "#id")
publicvoiddeleteUser(int id) {
System.out.println("删除用户:" + id);
}
}
支持本地缓存和远程缓存的组合java缓存技术有哪些,非常适合分布式系统。
总结
今天我们一起探索了Java本地缓存的多种实现方式,从手写缓存到Guava Cache、、和。每种方式都有自己的特点和适用场景。
到此这篇关于Java中本地缓存的4种实现方式的文章就介绍到这了,更多相关Java本地缓存实现内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
1. 本站所有资源来源于用户上传和网络,如有侵权请联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系站长处理!
6. 本站不售卖代码,资源标价只是站长收集整理的辛苦费!如果您喜欢该程序,请支持正版软件,购买注册,得到更好的正版服务。
7. 站长QQ号码 2205675299
资源库 - 资源分享下载网 » Java中本地缓存的4种实现方式总结
常见问题FAQ
- 关于资源售价和售后服务的说明?
- 代码有没有售后服务和技术支持?
- 有没有搭建服务?
- 链接地址失效了怎么办?
- 关于解压密码

