下边实现了一个持续返回100以内随机数的接口,在接口超时之前会每隔1秒返回一个随机数
java
@GetMapping(value = "/getRandomNum", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public SseEmitter getRandomNum() {
SseEmitter emitter = new SseEmitter();
ThreadLocalRandom random = ThreadLocalRandom.current();
new Thread(() -> {
try {
while (true) {
int price = random.nextInt(100);
emitter.send(SseEmitter.event().data(price));
Thread.sleep(1000);
}
} catch (Exception e) {
emitter.completeWithError(e);
}
}).start();
return emitter;
}
下边是postman调用效果图