关于JAVA中业务场景需自定义缓存工具类

创建一个自定义的缓存类,包含一个ConcurrentHashMap来存储缓存数据,以及一个ScheduledExecutorService来执行定时清理任务,它接受一个cleanupInterval参数,表示清理间隔。:

import java.util.concurrent.*;

public class CustomCache {
    private final ConcurrentHashMap<String, Object> cache = new ConcurrentHashMap<>();
    private final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
    private final long cleanupInterval; // 清理间隔,单位:毫秒

    public CustomCache(long cleanupInterval) {
        this.cleanupInterval = cleanupInterval;
        startCleanupTask();
    }

    public Object get(String key) {
        return cache.get(key);
    }

    public void put(String key, Object value) {
        cache.put(key, value);
    }

    public void remove(String key) {
        cache.remove(key);
    }

    private void startCleanupTask() {
        executorService.scheduleAtFixedRate(() -> {
            System.out.println("Performing cache cleanup...");
            // 在这里实现清理缓存的逻辑,例如根据过期时间移除缓存项
            // cache.entrySet().removeIf(entry -> entry.getValue() instanceof ExpiringValue && ((ExpiringValue) entry.getValue()).isExpired());
            // 示例:移除所有缓存项(仅用于演示)
            cache.clear();
        }, cleanupInterval, cleanupInterval, TimeUnit.MILLISECONDS);   //  }, 60000, 60000);
    }

    public void shutdown() {
        executorService.shutdown();
    }
}


方法2import java.util.concurrent.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

public class LRUCacheWithCleanup<K, V> {
    private final int capacity;
    private final ConcurrentHashMap<K, CacheEntry<V>> cacheMap;
    private final Queue<K> accessQueue;
    private final long cleanupInterval; // 清理间隔时间,单位为毫秒
    private final ScheduledExecutorService cleanupService;

    private static class CacheEntry<V> {
        V value;
        long accessTime;

        CacheEntry(V value, long accessTime) {
            this.value = value;
            this.accessTime = accessTime;
        }
    }

    public LRUCacheWithCleanup(int capacity, long cleanupInterval) {
        this.capacity = capacity;
        this.cacheMap = new ConcurrentHashMap<>();
        this.accessQueue = new ConcurrentLinkedQueue<>();
        this.cleanupInterval = cleanupInterval;
        this.cleanupService = Executors.newSingleThreadScheduledExecutor();
        scheduleCleanupTask(); // 安排定时清理任务
    }

    private void scheduleCleanupTask() {
        // 安排定时任务,周期性地清理过期的缓存项
        cleanupService.scheduleAtFixedRate(this::cleanupCache, cleanupInterval, cleanupInterval, TimeUnit.MILLISECONDS);
    }

    private void cleanupCache() {
        // 清理过期的缓存项
        long currentTime = System.currentTimeMillis();
        Iterator<K> iterator = accessQueue.iterator();
        while (iterator.hasNext()) {
            K key = iterator.next();
            CacheEntry<V> entry = cacheMap.get(key);
            // 如果缓存项不存在或已过期,则从缓存和访问队列中移除
            if (entry == null || currentTime - entry.accessTime > cleanupInterval) {
                iterator.remove();
                if (entry != null) {
                    cacheMap.remove(key);
                }
            }
        }
    }

    public V get(K key) {
        // 根据键获取缓存项
        CacheEntry<V> entry = cacheMap.get(key);
        if (entry == null) {
            return null;
        }
        // 更新访问时间并将该项移动到访问队列的末尾
        entry.accessTime = System.currentTimeMillis();
        accessQueue.remove(key);
        accessQueue.add(key);
        return entry.value;
    }

    public void put(K key, V value) {
        // 将键值对放入缓存
        CacheEntry<V> newEntry = new CacheEntry<>(value, System.currentTimeMillis());
        CacheEntry<V> oldEntry = cacheMap.put(key, newEntry);
        if (oldEntry != null) {
            // 键已存在,更新访问时间并重新排序
            accessQueue.remove(key);
        } else {
            // 键不存在,检查是否需要从缓存中移除最老的项
            if (cacheMap.size() > capacity) {
                K oldestKey = accessQueue.poll();
                if (oldestKey != null) {
                    cacheMap.remove(oldestKey);
                }
            }
        }
        // 将新项添加到访问队列的末尾
        accessQueue.add(key);
    }

    public V remove(K key) {
        // 从缓存中移除指定的键
        CacheEntry<V> entry = cacheMap.remove(key);
        if (entry != null) {
            accessQueue.remove(key);
        }
        return entry == null ? null : entry.value;
    }

    public void shutdown() {
        // 关闭清理服务
        cleanupService.shutdown();
        try {
            if (!cleanupService.awaitTermination(60, TimeUnit.SECONDS)) {
                cleanupService.shutdownNow();
            }
        } catch (InterruptedException e) {
            cleanupService.shutdownNow();
        }
    }
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java自定义注解是一种在代码声明的特殊标记,用于在运行时对代码进行处理。通过定义注解,我们可以在代码添加一些额外的元数据或标记信息,以实现对代码的自定义处理。使用自定义注解可以简化代码的编写和维护,提高代码的可读性和可维护性。 自定义注解的使用场景有很多,以下是一些常见的使用场景: 1. 代码检查和规范:通过定义注解并在代码添加注解,可以对代码进行静态检查,以确保代码符合规范和标准。例如,可以定义一个@NonNull注解用于标记不允许为null的参数或返回值,通过编译器插件或静态检查工具进行检查,从而避免了空指针异常。 2. 代码生成:通过定义注解和处理器,可以自动生成一些重复性的代码,提高开发效率。例如,可以定义一个@Entity注解用于标记实体类,通过注解处理器自动生成数据库表的建表语句或实体类的序列化/反序列化方法。 3. 运行时的动态处理:通过定义注解,并在运行时使用反射机制获取注解信息,可以实现一些动态处理的功能。例如,可以定义一个@Cacheable注解用于标记缓存的方法,然后使用反射在方法执行前判断是否有缓存数据,如果有则直接返回缓存结果,提高系统性能。 4. 测试框架:通过定义注解和处理器,可以实现自定义的测试框架。例如,可以定义一个@Test注解用于标记测试方法,然后使用注解处理器在测试运行时自动执行标记的测试方法。 总之,自定义注解是Java语言一种强大的元数据扩展机制,可以在代码实现各种功能的自定义处理。通过合理设计和使用自定义注解,可以提高代码的可读性、可维护性和可扩展性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值