使用SseEmitter不断向网页输出结果
序
之前写过一篇文章:springmvc不断输出文本到网页,采用的是对response不断进行write和flush实现的。在spring 4.2版本的时候提供了一个SseEmitter可以直接用来实现这个功能。
实例
@Controller
@RequestMapping("/sse")
public class SseEmitterController {
private static final Logger LOGGER = LoggerFactory.getLogger(SseEmitterController.class);
@Autowired
@Qualifier("mvcTaskExecutor")
ThreadPoolTaskExecutor mvcTaskExecutor;
@GetMapping("")
public SseEmitter sseDemo() throws InterruptedException {
final SseEmitter emitter = new SseEmitter(0L); //timeout设置为0表示不超时
mvcTaskExecutor.execute(() -> {
try {
for(int i=0;i<100;i++){
emitter.send("hello"+i);
LOGGER.info("emit:{}","hello"+i);
Thread.sleep(1000*1);
emitter.complete();
} catch (Exception e) {
emitter.completeWithError(e);
return emitter;
}
输出实例
data:"hello0"
data:"hello1"
data:"hello2"
data:"hello3"
data:"hello4"