samedi 23 octobre 2021

How to implement sse in spring mvc?

How to implement sse in spring mvc?

I have the following data:

Map<String, Object> pushMap = new HashMap<String, Object>();
pushMap.put("poiNo", poi.getPoiNo());
pushMap.put("poiNm", poi.getPoiNm());
pushMap.put("poiStatus", poi.getPoiStatus());

And I want to send pushMap to client in sse method.

I am wondering how to implement this.

Sources found on the google

    @RequestMapping("/subscribe")
// public SseEmitter subscribe(String id) {
    public SseEmitter subscribe() {
        String id = String.valueOf(UUID.randomUUID());
        SseEmitter emitter = new SseEmitter();
        CLIENTS.put(id, emitter);

        emitter.onTimeout(() -> CLIENTS.remove(id));
        emitter.onCompletion(() -> CLIENTS.remove(id));
        return emitter;
    }
    @RequestMapping("/publish")
// public void publish(String message) {
    public void publish() {
        Set<String> deadIds = new HashSet<>();

        CLIENTS.forEach((id, emitter) -> {
            try {
                emitter.send(pushMap, MediaType.APPLICATION_JSON);
                log.info("pushMap: [{}]", pushMap);
            } catch (Exception e) {
                deadIds.add(id);
                log.warn("disconnected id : {}", id);
            }
        });

        deadIds.forEach(CLIENTS::remove);
    }

It is as above.

However, even if you make a publish request with POSTMAN, the pushMap information does not appear in the log.

I want to give publish to the client after subscribe, but I think this method is wrong, so I ask this question.

best regards!




Aucun commentaire:

Enregistrer un commentaire