如何使用Spring启动创建事件源服务器?

时间:2016-09-20 11:23:48

标签: java angularjs spring spring-boot eventsource

如何使用Spring启动应用程序创建事件源服务器? 从下面的链接,我没有看到Java-spring启动示例。 任何参考都会有所帮助。

http://www.html5rocks.com/en/tutorials/eventsource/basics/

2 个答案:

答案 0 :(得分:2)

这是Spring 4.2的一个简单实现。不要考虑线程,它仅用于演示目的:

@RestController
public class AccountsRestController {

    @RequestMapping("/accounts/alerts")
    public SseEmitter getAccountAlertsNoPathVariable(HttpSession session) {

        SseEmitter emitter = new SseEmitter(Long.MAX_VALUE);

        Thread t1 = new Thread(() ->{
            try {
                int i = 0;
                // Send 10000 messages
                while(++i<=10000){
                    Thread.sleep(1000);
                    System.out.println("Sending");
                    try{
                        emitter.send(new Alert((long)i, "Alert message"+i));
                    }catch(ClientAbortException cae){
                        //The client is not there anymore, we get out of the loop
                        i = 10000;
                    }
                }
                emitter.complete();
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
        });
        t1.start();

        return emitter;
    }

答案 1 :(得分:0)

我尝试使用以下代码,从@codependent的解决方案重写,以满足我的需要。它的回应。但是在浏览器选项卡关闭时永远不会终止连接。它继续在服务器端运行。这里有关于HTTP GET的任何事情吗?

@RequestMapping(value = "/getNotificationCount/{userId}",method = RequestMethod.GET)
    public SseEmitter getNotificationCount(@PathVariable("userId") String userId, HttpServletResponse response){
        SseEmitter emitter = null;
        try {
            emitter = new SseEmitter();

            while(true) {
                try{
                    int count= myService.getNotificationCount(Integer.parseInt(userId));
                    emitter.send(count);
                    Thread.sleep(30 *   // minutes to sleep
                                 60 *   // seconds to a minute
                                 1000); // milliseconds to a second

                }catch(ClientAbortException cae){
                    LOGGER.info("ClientAbortException Breaking the notification stream");
                    break;
                }
            }

            //Closes the stream
            emitter.complete();

        } catch (Exception e) {
            //Closes the stream
            emitter.complete();
        }

        return emitter;
    }