我是REST APIS的新手,我正在尝试构建本地内存缓存,并使用java和spring框架编写REST APIS以获取和检索数据,以下是我要实现的详细描述:
- Building the REST API to store key-value in local memory cache
- API must have 2 endpoints following specification below
• /cache/add (This must store unique key only (existing key must be ignored), This will return true if the element was successfully added )
•/cache/take (This method retrieves and removes the most recently added element from the cache and waits if necessary until an element becomes available)
我不知道如何实现/ cache / take方法。任何建议将不胜感激。
答案 0 :(得分:5)
您的第一个要求构建REST API以将键值存储在本地内存缓存中我使用了linkedHashMap,因为它将存储您的键值对,并且由于它是静态的,因此您可以用作本地缓存
对于第二个需求,创建了两个端点,一个是在linkedHashMap中存储值,另一个是删除您在linkedHashMap中输入的最后一个条目。获取LinkedHashMap的最后一个条目的一种方法是使用Set接口的“ toArray”方法。那就是我所做的,您可能会有更好的方法,这个答案可能会得到改善
@RestController
public class CacheController {
private static LinkedHashMap<String, String> localCache = new LinkedHashMap<String, String>();
@RequestMapping(value = { "/cache/add" }, method = RequestMethod.GET)
public Boolean cacheAdd(@RequestParam(value = "key", required = true) String key, @RequestParam(value = "value", required = true) String value) {
if (localCache.containsKey(key)) {
return false;
}
localCache.put(key, value);
return true;
}
@RequestMapping(value = { "/cache/take" }, method = RequestMethod.GET)
public String cacheTake() {
Set<Entry<String, String>> mapValues = localCache.entrySet();
int maplength = mapValues.size();
Entry<String, String>[] cacheArray = new Entry[maplength];
mapValues.toArray(cacheArray);
System.out.print("Last Key:" + cacheArray[maplength - 1].getKey());
System.out.println(" Last Value:" + cacheArray[maplength - 1].getValue());
localCache.remove(cacheArray[maplength - 1].getKey());
return cacheArray[maplength - 1].getValue();
}
}