我是REST API的新手,我正在尝试构建本地内存缓存,并使用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方法。任何建议将不胜感激。

最佳答案

满足您的第一个需求构建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();
}

}

关于java - 等待任务完成的HTTP请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52799265/

10-11 19:17