๐ 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.