每隔1小时间隔在文件中存储一分钟的Servlet发布请求

时间:2016-10-13 17:58:32

标签: java multithreading servlets httprequest

我正在尝试找一些选项来将一分钟的帖子请求存储到文件中,并希望每小时重复一次。我每秒有大约3000个请求,我只想存储请求消息一分钟它会给我180000左右的请求做分析。但我想每小时对请求消息进行相同的分析。

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);

我有点迷失在这里寻找一些选择。 使用Executors还是Thread可以实现这一点吗?如果没有,我可以尝试的其他选择是什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

如果你想在每小时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
);