话不多说,直接上货
import cn.hutool.core.util.IdUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;@RestController
public class SseController {private final ExecutorService nonBlockingService = Executors.newCachedThreadPool();@GetMapping("/sse")public SseEmitter handleSse() {SseEmitter emitter = new SseEmitter();String[] split = ("金融业也被波及。多国石油天然气、电力、股票交易19日、当天难以正常展开。" +"伦敦证券交易所等、重要金融市场的监管新闻服务、交易系统出现问题,信息无法及时流通。" +"在系统故障期间," +"一些银行、金融机构甚至不得不采用手工记账," +"极大地降低了、工作效率。" +"英国、德国、南非和新西兰都有银行、客户在交易中遇到问题。").split("[。、,]");nonBlockingService.execute(() -> {try {for (int i = 0; i < 10; i++) {JSONObject object = new JSONObject();object.put("id", IdUtil.fastUUID());object.put("content", split[i]);SseEmitter.SseEventBuilder event = SseEmitter.event().data(object.toJSONString(), MediaType.TEXT_PLAIN).id(String.valueOf(i)).name(""+i);emitter.send(event);Thread.sleep(1000); // 模拟延迟}emitter.complete();} catch (IOException | InterruptedException e) {emitter.completeWithError(e);}});return emitter;}
}