首页 > 解决方案 > 等待任务完成的 HTTP 请求

问题描述

我是 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 方法。任何建议将不胜感激。

标签: javaspringspring-boot

解决方案


对于您的第一个要求构建 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();
}

}

推荐阅读