gpt4 book ai didi

Java Servlet 多线程解析请求体

转载 作者:太空宇宙 更新时间:2023-11-04 13:13:46 25 4
gpt4 key购买 nike

我实现了一个异步Servlet,它需要解析请求正文并将解析结果存储在缓存中。我应该在 Servlet 中实现 parseBody() 函数还是实现一个新类来进行解析?最佳实践是什么?

这是我当前的代码片段:

public class DocFeedServlet extends FeedServlet {

private static final Logger LOGGER = LoggerFactory.getLogger(DocFeedServlet.class);
private static final ObjectMapper OBJECTMAPPER = new ObjectMapper();


public void init(ServletConfig config) throws ServletException {
super.init(config);
}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {

final AsyncContext asyncContext = req.startAsync();
asyncContext.start(new Runnable() {
@Override
public void run() {
String bodyStr = getBody(req);
if (bodyStr.isEmpty()) {
resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
asyncContext.complete();
return;
}

int ignoreTime = Integer.parseInt(req.getParameter(Constant.PARAM_IGNORE_TIME));

List<MockDocCacheKeyVal> mockDocCacheKeyVals = new ArrayList<>();
List<String> docUpdateFields = new ArrayList<>();
List<List<String>> docKeepFields = new ArrayList<List<String>>();
List<String> uuidsToRemove = new ArrayList<>();

int parseRet = parseBody(bodyStr, mockDocCacheKeyVals, docUpdateFields, docKeepFields, uuidsToRemove, ignoreTime);

if (parseRet != 0) {
resp.setStatus(HttpServletResponse.SC_OK);
} else {
resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
asyncContext.complete();
}
});
}

protected int parseBody(String body, List<MockDocCacheKeyVal> mockDocCacheKeyVals, List<String> docUpdateFields, List<List<String>> docKeepFields, List<String> uuidsToRemove, int ignoreTime) {
try {
ObjectReader reader = OBJECTMAPPER.reader(new TypeReference<List<Document>>() { });
List<Document> documents = reader.readValue(body);
for (Document doc : documents) {
if (doc.getAction() != null && doc.getAction().equalsIgnoreCase(Constant.DOC_FEED_ACTION_DELETE)) {
if (doc.getUuid() != null) {
uuidsToRemove.add(doc.getUuid());
}
continue;
}
if (doc.getA() != null) {

} else if (doc.getB() != null) {

} else {
DocumentUtils.pruneWeightSet(doc.getC(), cPruneSize);
DocumentUtils.pruneWeightSet(doc.getD(), dPruneSize);
DocumentUtils.pruneWeightSet(doc.getE(), ePruneSize);
}
}
return documents.size();
} catch (Exception e) {
LOGGER.error(e.getMessage());
}
return 0;
}
}

谢谢。

最佳答案

异步请求正文读取是通过 HttpServletRequest.getInputStream().setReadListener(ReadListener) 完成的Servlet 3.1 中引入的概念

您只会根据来自 ReadListener 的事件进行读取,并且您只会读取足够的内容而不会阻塞。 (因此无法读取数兆字节缓冲区!)。

这个 API 正是您正在寻找的,但是 there be land mines here ,所以在完成之前请确保您完全理解该 API。

关于Java Servlet 多线程解析请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33714904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com