Skip to content

Commit

Permalink
Merge pull request #73 from SWM-SMART/feat/#72
Browse files Browse the repository at this point in the history
SSE 30초 주기 알림 구현
  • Loading branch information
noparamin authored Nov 21, 2023
2 parents bb9e4ab + 4ad41bc commit de9d06e
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/main/java/com/smart/watchboard/WatchboardApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;

@SpringBootApplication
@EnableScheduling
public class WatchboardApplication {

public static void main(String[] args) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package com.smart.watchboard.common.support;

import com.smart.watchboard.service.SseService;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class ScheduledTask {
private final SseService sseService;

@Scheduled(fixedRate = 30000)
public void executeNotifyTask() {
sseService.notifyCycle();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,10 @@
import org.springframework.stereotype.Repository;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Repository
@RequiredArgsConstructor
Expand All @@ -23,4 +25,9 @@ public void deleteById(Long id) {
public SseEmitter get(Long id) {
return emitters.get(id);
}

public List<Long> getAllKeys() {
return emitters.keySet().stream()
.collect(Collectors.toList());
}
}
18 changes: 18 additions & 0 deletions src/main/java/com/smart/watchboard/service/SseService.java
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,24 @@ public void notify(Long documentId, List<String> keywords) {
sendToClient(documentId, keywords);
}

public void notifyCycle() {
sendCycle();
}

private void sendCycle() {
List<Long> keys = emitterRepository.getAllKeys();
for (Long documentId : keys) {
SseEmitter emitter = emitterRepository.get(documentId);
try {
emitter.send(SseEmitter.event().id(String.valueOf(documentId)).name("ping").data("ping"));
} catch (IOException exception) {
emitterRepository.deleteById(documentId);
emitter.completeWithError(exception);
}

}
}

private void sendToClientFirst(Long documentId, Object data) {
SseEmitter emitter = emitterRepository.get(documentId);
if (emitter != null) {
Expand Down

0 comments on commit de9d06e

Please sign in to comment.