π Websocket - STOMP μ±ν μλ² κ΅¬μΆ
π Websocket - STOMP μ±ν
μλ² κ΅¬μΆ
Websocket - STOMP λμ
κ·Όκ±°
- μ±ν
μλΉμ€λ₯Ό μν΄
Websocketμ°κ²° λ° λ©μμ§λ₯Ό μ μ‘ν΄μMongoDBμ λ°μ΄ν°λ₯Ό λ±λ‘ν΄λ³΄λ €κ³ νλ€. - μ±ν
μ μλ°©ν₯ ν΅μ μ΄λ―λ‘
SSEλ λΆκ°νκ³ , ν¨μ¨μ±μ μν΄Pollingλ°©μ λν λ°°μ λμ΄Websocketμ λμ νκ² λμλ€.
μμ± μ½λ
β μ€μ νμΌ
1
2
3
4
5
6
7
8
9
10
/**
* μλν¬μΈνΈ μ€μ
* @param registry
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/ws")
.setAllowedOriginPatterns("*");
.withSockJS();
}
β
Controller
1
2
3
4
@MessageMapping("/chat.sendSystemMessage")
public void enterUser(Message message) {
service.sendSystemMessage(message);
}
β
Service
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public void sendSystemMessage(Message message) {
MessageType type = message.getType();
Long roomId = message.getRoomId();
Message systemMessage = Message.builder()
.type(type)
.content(
String.format(
type.name().equals("ENTER") ? "[%s] %s λμ΄ μ
μ₯νμ΅λλ€." : "[%s] %s λμ΄ ν΄μ₯νμ΅λλ€.",
LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
message.getSenderName()
)
)
.senderId(message.getSenderId())
.roomId(roomId)
.sendAt(LocalDateTime.now())
.build();
repository.save(systemMessage);
template.convertAndSend("/topic/room_" + roomId, systemMessage);
}
- ν΄λΌμ΄μΈνΈκ° λ©μμ§λ₯Ό μμ²ν κ²½μ°
DBμ ν΄λΉ λ©μμ§λ₯Ό μ μ₯νκ³ , ν΄λΉ μ¬μ©μκ° κ΅¬λ νTopicμ λ©μμ§λ₯Ό μ μ‘νλ€. SimpleMessagingTemplateμ κ°λ¨νκ²Topicμ λ©μμ§λ₯Ό μ λ¬ν μ μλ λ©μλλ₯Ό μ 곡νλ€.
ν μ€νΈ
PostmanμμλSTOMPμλΈ νλ‘ν μ½μ μ§μνμ§ μμΌλ―λ‘ μ λ§ν¬λ₯Ό νμ©ν΄μΌ νλ€.
1
2
3
4
5
6
7
8
9
10
11
12
2025-04-05T15:14:04.404+09:00
DEBUG 23688 --- [nboundChannel-4] o.s.m.s.b.SimpleBrokerMessageHandlerΒ Β Β Β
: Processing MESSAGE
destination=/topic/room_2
session=null
payload={
"senderId":1,
"roomId":1,
"senderName":null,
"type":"ENTER",
"send...(truncated)"
}
- μμ 첨λΆν λ§ν¬μμλ
CONNECT,SUBSCRIBE,SENDλ± μμ² νλ μμ μμ±ν νμ μμ΄ κ°λ¨νκ² ν μ€νΈν μ μλ€. - μ€μ λͺ©μ μ§μ μ λλ‘
Broadcastλλμ§λFrontendμμμ ꡬνν΄μΌ μ μ μκΈ°λ νμ§λ§BackendμμLoggingμ νμΈνλ μ μμ ν μ€νΈλ₯Ό λ§μ³€λ€.Β Sessionμ΄nullκ°μΌλ‘Loggingλκ³ μλλ°, μ΄κ±΄SimpMessagingTemplateλ₯Ό μ¬μ©ν κ²½μ°Sessionμ 보λ₯Ό ν¬ν¨νμ§ μκ³ λ©μμ§λ₯Ό λΈλ‘μ»€λ‘ λ³΄λ΄κΈ° λλ¬Έμ΄λ€.SockJSλ₯Ό μ¬μ©ν κ²½μ° νλ‘ν μ½μwsκ° μλhttpλ₯Ό κΈ°μ¬ν΄μΌ νλ€.
This post is licensed under CC BY 4.0 by the author.
