目录
- 1.SseController
- 2. SseService
- SseService
- SseServiceImpl
- 3.SendMessageTask
- 4.将定时任务加入启动类
- 5.参考资料
1.SseController
@Slf4j
@RestController
@RequestMapping("sse")
public class SseController {@Autowiredprivate SseService sseService;@RequestMapping("/")public String index(){return "sse";}/*** 创建SSE连接* @return*/@RequestMapping(path = "/connect",produces = MediaType.TEXT_EVENT_STREAM_VALUE)public SseEmitter sse(){String uuid = UUID.randomUUID().toString();log.info("新用户连接:{}",uuid);return sseService.connect(uuid);}/*** 广播消息* @param message*/@RequestMapping("/sendMessage")@ResponseBodypublic void sendMessage(@RequestBody SseMessage message){sseService.sendMessage(message);}}
2. SseService
SseService
public interface SseService {/*** 创建sse连接* @param uuid* @return*/SseEmitter connect(String uuid);/*** 发送消息* @param message*/void sendMessage(SseMessage message);
}
SseServiceImpl
@Slf4j
@Service
public class SseServiceImpl implements SseService {/*** sseMesageId的SseEmitter对象映射集**/private static Map<String,SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();/*** 创建sse连接** @param uuid* @return*/@Overridepublic SseEmitter connect(String uuid) {SseEmitter sseEmitter = new SseEmitter();//连接成功需要返回数据,否则会出现待处理状态try{sseEmitter.send(SseEmitter.event().comment("connect success"));}catch (IOException e){e.printStackTrace();}//连接断开sseEmitter.onCompletion(()->{sseEmitterMap.remove(uuid);});//连接超时sseEmitter.onTimeout(()->{sseEmitterMap.remove(uuid);});//连接报错sseEmitter.onError((throwable)-> {sseEmitterMap.remove(uuid);});sseEmitterMap.put(uuid,sseEmitter);return sseEmitter;}/*** 发送消息** @param message*/@Overridepublic void sendMessage(SseMessage message) {message.setTotal(sseEmitterMap.size());sseEmitterMap.forEach((uuid,sseEmiter)->{try {sseEmiter.send(message, MediaType.APPLICATION_JSON);} catch (IOException e) {e.printStackTrace();}});}
}
3.SendMessageTask
@Configuration
public class SendMessageTask {@Autowiredprivate SseService sseService;/*** 定时执行 秒 分 时 日 月 周*/@Scheduled(cron = "*/1 * * * * *")//间隔1Spublic void sendMessageTask(){SseMessage message = new SseMessage();DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");message.setData(LocalDateTime.now().format(format));message.setDtuStatus(1);message.setPlcId(01);message.setInletValve(0);message.setSampleValve(1);message.setVentingValve(0);message.setDtuStatus(1);message.setSamplerStatus("01");sseService.sendMessage(message);}}
4.将定时任务加入启动类
5.参考资料
springboot集成sse详细教程: https://bilibili.com/video/BV1pC4y1P7cp