java利用map写个简单的本地缓存,每天早上定时任务查一张数据进行清楚再存储
时间: 2024-04-12 17:30:48 浏览: 19
下面是一个使用 `Map` 实现简单本地缓存,并且每天早上定时任务清除并重新存储数据的示例代码:
```java
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
public class LocalCacheExample {
private static Map<String, Object> cache = new HashMap<>();
public static void main(String[] args) {
// 模拟每天早上定时任务时间
long interval = 24 * 60 * 60 * 1000; // 24小时
// 执行定时任务
Timer timer = new Timer();
timer.schedule(new CacheRefreshTask(), interval, interval);
// 存储数据到缓存
storeData("key1", "value1");
storeData("key2", "value2");
// 从缓存中获取数据
System.out.println(getData("key1")); // 输出: value1
System.out.println(getData("key2")); // 输出: value2
// 等待定时任务执行完毕
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 重新从缓存中获取数据
System.out.println(getData("key1")); // 输出: null
System.out.println(getData("key2")); // 输出: null
// 停止定时任务
timer.cancel();
}
private static void storeData(String key, Object value) {
cache.put(key, value);
}
private static Object getData(String key) {
return cache.get(key);
}
private static class CacheRefreshTask extends TimerTask {
@Override
public void run() {
// 清除缓存
cache.clear();
// 重新存储数据到缓存
storeData("key1", "new value1");
storeData("key2", "new value2");
System.out.println("缓存已更新");
}
}
}
```
在上面的示例中,使用 `HashMap` 实现了一个简单的本地缓存 `cache`。定时任务 `CacheRefreshTask` 负责在每天早上清除并重新存储数据。首先,通过 `storeData()` 方法将数据存储到缓存中,然后通过 `getData()` 方法从缓存中获取数据。等待定时任务执行完毕后,再次从缓存中获取数据,可以看到数据已被清除并重新存储。
请注意,上面的示例只是一个简单的示例,实际应用中可能需要考虑并发访问、缓存过期策略等问题。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)