JAVA缓存

JAVA缓存有两种:
一、文件缓存,是指把数据存储在磁盘上,可以XML格式,也可以序列化文件DAT格式还是其它文件格式。
二、内存缓存,也就是实现一个类中静态Map,对这个Map进行常规的增删查。

其代码如下:

JAVA缓存-Cache类

    

public class Cache {
private String key;//缓存ID
private Object value;//缓存数据
private long timeOut;//更新时间
private boolean expired; //是否终止
public Cache() {
super();
}
public Cache(String key, Object value, long timeOut, boolean expired) {
this.key = key;
this.value = value;
this.timeOut = timeOut;
this.expired = expired;
}
public String getKey() {
return key;
}
public long getTimeOut() {
return timeOut;
}
public Object getValue() {
return value;
}
public void setKey(String string) {
key = string;
}
public void setTimeOut(long l) {
timeOut = l;
}
public void setValue(Object object) {
value = object;
}
public boolean isExpired() {
return expired;
}
public void setExpired(boolean b) {
expired = b;
}
}
//测试类,
class Test {
public static void main(String[] args) {
System.out.println(CacheManager.getSimpleFlag("alksd"));
// CacheManager.putCache("abc", new Cache());
// CacheManager.putCache("def", new Cache());
// CacheManager.putCache("ccc", new Cache());
// CacheManager.clearOnly("");
// Cache c = new Cache();
// for (int i = 0; i < 10; i++) {
// CacheManager.putCache("" + i, c);
// }
// CacheManager.putCache("aaaaaaaa", c);
// CacheManager.putCache("abchcy;alskd", c);
// CacheManager.putCache("cccccccc", c);
// CacheManager.putCache("abcoqiwhcy", c);
// System.out.println("删除前的大小:"+CacheManager.getCacheSize());
// CacheManager.getCacheAllkey();
// CacheManager.clearAll("aaaa");
// System.out.println("删除后的大小:"+CacheManager.getCacheSize());
// CacheManager.getCacheAllkey();
}
}

JAVA缓存-CacheManager类

    

public class CacheManager {
private static HashMap cacheMap = new HashMap();
//单实例构造方法
private CacheManager() {
super();
}
//获取布尔值的缓存
public static boolean getSimpleFlag(String key){
try{
return (Boolean) cacheMap.get(key);
}catch(NullPointerException e){
return false;
}
}
public static long getServerStartdt(String key){
try {
return (Long)cacheMap.get(key);
} catch (Exception ex) {
return 0;
}
}
//设置布尔值的缓存
public synchronized static boolean setSimpleFlag(String key,boolean flag){
if (flag && getSimpleFlag(key)) {//假如为真不允许被覆盖
return false;
}else{
cacheMap.put(key, flag);
return true;
}
}
public synchronized static boolean setSimpleFlag(String key,long serverbegrundt){
if (cacheMap.get(key) == null) {
cacheMap.put(key,serverbegrundt);
return true;
}else{
return false;
}
}
//得到缓存。同步静态方法
private synchronized static Cache getCache(String key) {
return (Cache) cacheMap.get(key);
}
//判断是否存在一个缓存
private synchronized static boolean hasCache(String key) {
return cacheMap.containsKey(key);
}
//清除所有缓存
public synchronized static void clearAll() {
cacheMap.clear();
}
//清除某一类特定缓存,通过遍历HASHMAP下的所有对象,来判断它的KEY与传入的TYPE是否匹配
public synchronized static void clearAll(String type) {
Iterator i = cacheMap.entrySet().iterator();
String key;
ArrayList arr = new ArrayList();
try {
while (i.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
key = (String) entry.getKey();
if (key.startsWith(type)) { //如果匹配则删除掉
arr.add(key);
}
}
for (int k = 0; k < arr.size(); k++) {
clearOnly(arr.get(k));
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
//清除指定的缓存
public synchronized static void clearOnly(String key) {
cacheMap.remove(key);
}
//载入缓存
public synchronized static void putCache(String key, Cache obj) {
cacheMap.put(key, obj);
}
//获取缓存信息
public static Cache getCacheInfo(String key) {
if (hasCache(key)) {
Cache cache = getCache(key);
if (cacheExpired(cache)) { //调用判断是否终止方法
cache.setExpired(true);
}
return cache;
}else
return null;
}
//载入缓存信息
public static void putCacheInfo(String key, Cache obj, long dt,boolean expired) {
Cache cache = new Cache();
cache.setKey(key);
cache.setTimeOut(dt + System.currentTimeMillis()); //设置多久后更新缓存
cache.setValue(obj);
cache.setExpired(expired); //缓存默认载入时,终止状态为FALSE
cacheMap.put(key, cache);
}
//重写载入缓存信息方法
public static void putCacheInfo(String key,Cache obj,long dt){
Cache cache = new Cache();
cache.setKey(key);
cache.setTimeOut(dt+System.currentTimeMillis());
cache.setValue(obj);
cache.setExpired(false);
cacheMap.put(key,cache);
}
//判断缓存是否终止
public static boolean cacheExpired(Cache cache) {
if (null == cache) { //传入的缓存不存在
return false;
}
long nowDt = System.currentTimeMillis(); //系统当前的毫秒数
long cacheDt = cache.getTimeOut(); //缓存内的过期毫秒数
if (cacheDt <= 0||cacheDt>nowDt) { //过期时间小于等于零时,或者过期时间大于当前时间时,则为FALSE
return false;
} else { //大于过期时间 即过期
return true;
}
}
//获取缓存中的大小
public static int getCacheSize() {
return cacheMap.size();
}
//获取指定的类型的大小
public static int getCacheSize(String type) {
int k = 0;
Iterator i = cacheMap.entrySet().iterator();
String key;
try {
while (i.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
key = (String) entry.getKey();
if (key.indexOf(type) != -1) { //如果匹配则删除掉
k++;
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
return k;
}
//获取缓存对象中的所有键值名称
public static ArrayList getCacheAllkey() {
ArrayList a = new ArrayList();
try {
Iterator i = cacheMap.entrySet().iterator();
while (i.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
a.add((String) entry.getKey());
}
} catch (Exception ex) {} finally {
return a;
}
}
//获取缓存对象中指定类型 的键值名称
public static ArrayList getCacheListkey(String type) {
ArrayList a = new ArrayList();
String key;
try {
Iterator i = cacheMap.entrySet().iterator();
while (i.hasNext()) {
java.util.Map.Entry entry = (java.util.Map.Entry) i.next();
key = (String) entry.getKey();
if (key.indexOf(type) != -1) {
a.add(key);
}
}
} catch (Exception ex) {} finally {
return a;
}
}
}

### Java 缓存实现机制及相关库 #### 1. 缓存的作用与意义 缓存技术的主要目的是通过存储计算结果或数据副本,减少对数据库或其他外部资源的频繁访问,从而显著提升应用性能和响应速度[^1]。 #### 2. 常见的缓存分类 在 Java 开发中,常见的缓存分为两类: - **分布式缓存**:适用于多节点环境下的共享缓存需求,典型代表有 Redis 和 Memcached。这些工具通常部署在独立服务器上,支持高并发读写操作。 - **本地缓存**:运行于单机内存中的缓存解决方案,适合低延迟场景。常用的工具有 ConcurrentHashMap、Guava Cache 和 Caffeine 等[^3]。 --- #### 3. 使用 Ehcache 实现本地缓存 Ehcache 是一种广泛使用的开源缓存框架,能够轻松集成到 Java 应用程序中。以下是基于 Ehcache 的简单示例: ```java import net.sf.ehcache.Cache; import net.sf.ehcache.CacheManager; import net.sf.ehcache.Element; public class EhcacheExample { public static void main(String[] args) { // 创建缓存管理器实例 CacheManager cacheManager = CacheManager.create(); // 定义并初始化缓存对象 Cache myCache = new Cache("myCache", 100, false, true, 60, 120); cacheManager.addCache(myCache); // 添加键值对到缓存 Element element = new Element("key1", "value1"); myCache.put(element); // 获取缓存中的值 String value = (String) myCache.get("key1").getObjectValue(); System.out.println(value); // 输出: value1 // 关闭缓存管理器 cacheManager.shutdown(); } } ``` 上述代码展示了如何使用 Ehcache 进行简单的缓存操作。 --- #### 4. 使用 Guava Cache 实现 LRU 缓存 Google 提供的 Guava 工具包内置了强大的缓存功能,尤其擅长实现 LRU(Least Recently Used)淘汰策略。以下是一个典型的 Guava Cache 示例: ```java import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; public class GuavaLRUCacheExample { private LoadingCache<String, String> cache = CacheBuilder.newBuilder() .maximumSize(100) // 设置最大缓存条目数 .expireAfterWrite(10, TimeUnit.MINUTES) // 设置过期时间 .build(new CacheLoader<>() { @Override public String load(String key) throws Exception { return fetchFromDatabase(key); // 模拟从数据库加载数据 } }); private String fetchFromDatabase(String key) { return "Data-" + key; // 返回模拟的数据 } public String getData(String key) throws ExecutionException { return cache.get(key); } public static void main(String[] args) throws ExecutionException { GuavaLRUCacheExample example = new GuavaLRUCacheExample(); // 访问缓存中的数据 System.out.println(example.getData("testKey")); // 输出: Data-testKey } } ``` 此代码片段演示了如何利用 Guava Cache 构建带有自动清理功能的缓存系统[^4]。 --- #### 5. 集成 Redis 实现分布式缓存 Redis 是目前最受欢迎的分布式缓存解决方案之一,其高性能和丰富的特性使其成为许多大型项目的首选。下面展示了一个 Spring Boot 中集成了 Redis 的配置案例: ```yaml spring: redis: host: localhost port: 6379 timeout: 5000ms ``` 对应的 Java 配置类如下所示: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.StringRedisTemplate; @Configuration public class RedisConfig { @Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) { return new StringRedisTemplate(connectionFactory); } } // 测试 Redis 功能 @Service public class RedisService { @Autowired private StringRedisTemplate template; public void setValue(String key, String value) { template.opsForValue().set(key, value); } public String getValue(String key) { return template.opsForValue().get(key); } } ``` 以上代码说明了如何快速搭建一个基于 Redis 的分布式缓存服务[^2]。 --- #### 6. 总结 Java 缓存机制的选择取决于具体业务需求和技术栈特点。对于小型项目或者单一 JVM 场景下推荐采用本地缓存;而对于跨多个服务间共享状态的需求,则更适合选用像 Redis 或 Memcached 这样的分布式缓存方案。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值