如何使用 Spring Boot 应用程序创建事件源服务器?从下面的链接中,我没有看到 Java-spring boot 示例。任何参考都会有所帮助。
问问题
2557 次
2 回答
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;
}
于 2016-09-20T11:32:06.010 回答
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;
}
于 2016-09-20T14:06:27.097 回答