gpt4 book ai didi

java - 有时在计划任务中没有任何内容打印到 servlet 的输出流

转载 作者:行者123 更新时间:2023-11-30 11:40:21 25 4
gpt4 key购买 nike

我需要限制某些外部服务的连接速率(在我的 servlet 中),因此我决定尝试使用 ScheduledExecutorService。调度本身似乎运行良好,但输出只是偶尔打印——在大多数情况下什么都没有输出。为什么会出现这种情况?我使用 Tomcat 7 作为测试服务器。

int waitingtimeinmilliseconds = 5000;

ScheduledExecutorService scheduledExecutorService = Executors.newSingleThreadScheduledExecutor();

ScheduledFuture scheduledFuture = scheduledExecutorService.schedule() {

public void run() {

Fetcher fetcher = new Fetcher(loginname, password);
List<Item> items = fetcher.fetchItems();
// do something with the results

//ServletOutputStream
out.print("teststring" + items.size());

}

}, waitingtimeinmilliseconds, TimeUnit.MILLISECONDS);
scheduledExecutorService.shutdown();

最佳答案

您会在以下位置找到关于问题原因的详尽描述:HttpServletResponse seems to periodically send prematurely (同时检查:starting a new thread in servlet)。

基本上您不能使用外部线程写入 servlet 输出。一旦您离开 doGet()/doPost(),servlet 容器会假定您已完成并在将其刷新到客户端后丢弃输出。但由于您是异步写入流,有时输出会通过,而其他时候会被丢弃。

如果您希望您的速率限制非常可扩展,请考虑 async servlet(自 3.0 起)。如果您只想限制某些客户端,RateLimiter来自 将为您工作1

1 - 参见 RateLimiter - discovering Google Guava在我的博客上。

关于java - 有时在计划任务中没有任何内容打印到 servlet 的输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12789835/

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