在内存对象缓存中开发

在内存对象缓存中开发

本文介绍了在内存对象缓存中开发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究基于Web的医疗应用程序,需要创建一个小的内存中对象缓存。这是我的用例。

I am working on a web-based medical application and need to create a small in-memory object cache. Here is my use-case.

我们需要显示需要某些东西(血,肾等)的人提交的请求列表,它不会是一个巨大的清单,如在某一天要求血液或其他任何东西将是有限的。请考虑到我们不想使用任何缓存API,因为它会过度杀伤。我们的想法是创建一个Map并将其放在ApplicationContext中。

We need to show list of requests submitted by people who need certain things (Blood, Kidney, etc.) and it's not going to be a huge list as in a given day request for blood or anything else will be a limited one. Please take into account that we do not want to use any caching API as it would be an overkill. The idea is to create a Map and place it in the ApplicationContext.

当任何人发出新请求的那一刻,我们将在Application上下文中更新Map请求到期的那一刻,我们将从地图中删除它们。我们还需要另外考虑以下几点。

The moment a new request is being placed by any person, we will update that Map in the Application context and the moment the request expires, we will remove them from the Map. We need to look into the following points additionally.


  1. 需要设置最大元素限制。

  2. 如果达到最大限额,我们应该删除首先添加的条目。

  3. 处理任何同步问题。

请建议应该使用什么数据结构以及在实现时要注意什么。

Please suggest what Data-structure should be used and what things to take care of while implementing this.

推荐答案

我相信正是您所需要的。你只需要覆盖方法,如果达到最大容量,它将自动删除旧条目。类似于:

I believe LinkedHashMap is exactly what you need. You just need to override removeEldestEntry(...) method, and it will automatically remove old entries for you if the maximum capacity is reached. Something like:

import java.util.*;

class CacheMap<K,V> extends LinkedHashMap<K,V> {
    protected final int maxCapacity;
    public CacheMap(int maxCapacity) {
        this.maxCapacity = maxCapacity;
    }

    @Override
    protected boolean removeEldestEntry(Map.Entry eldest) {
        return size() > maxCapacity;
    }
}

您可以实现更复杂的逻辑,例如删除很老的条目,即使最大。没有达到容量。

You could implement a more sophisticated logic, for example remove very old entries even if the max. capacity is not reached.

如果同步原子地图操作就足够了,你可以将地图包装成:

If synchronizing atomic map operations is enough for you, you can just wrap the map into Collections.synchronizedMap(...):

Map<K,V> map = Collections.synchronizedMap(new CacheMap<K,V>(capacity));

如果您需要更准确的同步,例如读取地图并在一个同步块中更新它,需要 (全部)自己使用地图的代码块。

If you need more accurate synchronization, for example read the map and update it in one synchronized block, you need to synchronize (all) code blocks that work with the map yourself.

这篇关于在内存对象缓存中开发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 01:32