Video tayyorlanmoqda

Bitta WebSocketSession'ga ikki thread bir vaqtda sendMessage() qilsa nima bo'ladi?

// har bir event uchun alohida thread pool'dan chaqiriladi
@Async
public void onPriceChanged(Price p) {
    for (WebSocketSession s : sessions) {
        s.sendMessage(new TextMessage(toJson(p)));
    }
}

Standart JSR-356 sessiyasi parallel yuborishni qo'llamaydi: IllegalStateException ("TEXT_FULL_WRITING" kabi) chiqadi yoki frame'lar aralashib ketadi. Spring'da yechim — sessiyani ConcurrentWebSocketSessionDecorator bilan o'rash yoki yuborishni bitta thread'ga yig'ish.

📖 Javob

Narx soniyasiga 50 marta o'zgaradi, @Async tufayli bir nechta thread bir vaqtda bitta sessiyaga yozadi. Tomcat'da natija — kutilmaganda chiqadigan IllegalStateException: The remote endpoint was in state [TEXT_PARTIAL_WRITING]. Lokal testda bitta foydalanuvchi bilan ko'rinmaydi, prodda yuklama ostida chiqadi.

Spring'ning tayyor yechimi:

@Override
public void afterConnectionEstablished(WebSocketSession session) {
    WebSocketSession safe = new ConcurrentWebSocketSessionDecorator(
            session,
            10_000,        // sendTimeLimit, ms
            512 * 1024);   // bufferSizeLimit, bayt
    sessions.add(safe);
}

Decorator yuborishlarni navbatga qo'yadi va bir vaqtda faqat bitta thread haqiqatan socket'ga yozadi. Bonus: client sekin bo'lsa va buffer to'lib ketsa, u sessiyani yopadi — butun serverni bitta yomon client sekinlashtirmaydi.

STOMP ishlatsangiz, Spring buni ichkarida o'zi qiladi, bu muammo asosan xom WebSocketHandler bilan yozilgan kodda chiqadi.