Java 在文件中每隔1小时存储一分钟的Servlet post请求
我试图找到一些选项,将一分钟的post请求存储到一个文件中,并希望每小时重复一次。我每秒有大约3000个请求,我只想将请求消息存储一分钟,它将给我大约180000个请求进行分析。但我想每小时对请求消息进行相同的分析Java 在文件中每隔1小时存储一分钟的Servlet post请求,java,multithreading,servlets,httprequest,Java,Multithreading,Servlets,Httprequest,我试图找到一些选项,将一分钟的post请求存储到一个文件中,并希望每小时重复一次。我每秒有大约3000个请求,我只想将请求消息存储一分钟,它将给我大约180000个请求进行分析。但我想每小时对请求消息进行相同的分析 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
ServletInputStream inputStream = request.getInputStream();
Reader reader = new InputStreamReader(inputStream);
requestMessage = gson.fromJson(reader, Request.class);
//I am trying to print requestMessage in one file for a minute at interval of 1 hour to do analysis on it
//(I am having around 3000 post requests per seconds)
} catch (Exception e) {
e.printStackTrace();
}
response.setStatus(HttpServletResponse.SC_NO_CONTENT);
}
我曾尝试在Post方法中使用下面的代码,但它无法正常工作,因为每当我有新请求时,它都会启动新的计划,并且我将相同的代码放入init()方法中,但它没有输出
service = Executors.newSingleThreadScheduledExecutor();
service.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
System.out.println("Starting of 1 Hour time: "+new Date());
ScheduledExecutorService exec = Executors.newSingleThreadScheduledExecutor();
exec.schedule(new Runnable(){
@Override
public void run(){
System.out.println("Starting of 1 minute: "+new Date());
while(requestMessage.getID().equals("123"))
{
try {
System.out.println("Printing to File: "+new Date()); Files.write(Paths.get("location/requestMessage.txt"),requestMessage, StandardOpenOption.APPEND);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}, 1, TimeUnit.MINUTES);
}
}, 0, 1, TimeUnit.HOUR);
我在这里迷路了,正在寻找一些选择。
这可以通过使用执行器或线程实现吗?如果没有,我还可以尝试哪些其他选择
谢谢大家! 如果你想在每小时1分钟内执行一个给定的任务,你最好安排一个每小时启动一次的主任务,只要我们不到1分钟,它就会继续执行递归任务
ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
// Schedule the main task to be executed every one our
service.scheduleAtFixedRate(
new Runnable() {
@Override
public void run() {
// Get the initial time
long initial = System.currentTimeMillis();
// Iterate as long as the current time - initial time is less than 60 K ms (1m)
do {
// Here is my recursive task that I want to do during 1 minute
} while ((System.currentTimeMillis() - initial) < 60_000L);
}
}, 0L, 1L, TimeUnit.HOURS
);
ScheduledExecutorService=Executors.newSingleThreadScheduledExecutor();
//安排我们每个人都要执行的主要任务
service.scheduleAtFixedRate(
新的Runnable(){
@凌驾
公开募捐{
//获取初始时间
长初始值=System.currentTimeMillis();
//只要当前时间-初始时间小于60 kms(1m),就进行迭代
做{
//这是我想在1分钟内完成的递归任务
}而((System.currentTimeMillis()-初始值)<60_000L);
}
},0升,1升,时间单位。小时
);
这不清楚“每隔1小时一分钟”,请您澄清一下好吗?理想情况下,您能提供一个例子来澄清吗?谢谢Nicolas的回复。我已经尝试了更多的解释。嘿,再次感谢您的回复。我已经尝试了根据我的用法将您的代码结构用于init()方法,并且成功了。增加线程。睡眠(5);在do…while循环中。