java - 等待任务完成的 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 方法。任何建议将不胜感激。
解决方案
对于您的第一个要求构建 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();
}
}
推荐阅读
- php - 来自 Google NLP 的演示应用程序不工作 - “代码”:403
- react-native - 如何在 Expo React Native 中使用 twilio 发送短信?
- angular - 是否有任何默认的角度属性可以在角度 5 中滚动到屏幕顶部
- elasticsearch - CURL 命令未将大数据索引到弹性搜索中
- python - python中的其他语句
- php - pi的不同值?
- python - 将 HTML 标记删除应用于 Pandas 列
- wordpress - 如何在 Wordpress 中设置自己的分类顺序?
- angular - 如何在angular2 +中的选择属性中显示多个iframe作为值
- python - Odoo 创建自动报告并使用电子邮件模板将其发送给特定用户