1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【超実践】Spring Boot × React でリアルタイム通信!SSE を完全理解

Posted at

🎯 本記事のゴール

この記事では、Spring Boot と React を用いて Server-Sent Events (SSE) を実装し、サーバーからクライアントへのリアルタイム通知を行う方法を解説します!

  • SSE の仕組みを図解で理解する
  • Spring Boot で SSE を実装する
  • React 側で SSE を受信し、UI を更新する

🔥 SSE とは?WebSocket との違いは?

SSE(Server-Sent Events)は、サーバーからクライアントへ一方向のリアルタイム通信を行う技術です。主に以下のような用途に適しています。

通知機能(例:システムの更新情報)
チャットアプリ(ユーザーの新しいメッセージ受信)
データストリーミング(リアルタイムのデータ更新)

📌 WebSocket との比較

特徴 SSE WebSocket
通信方向 一方向(サーバー→クライアント) 双方向(サーバー⇄クライアント)
プロトコル HTTP 独自の WebSocket プロトコル
コネクション管理 HTTP の keep-alive を利用 WebSocket 専用の接続管理
適用例 通知、データストリーミング チャット、インタラクティブなアプリ

🎨 SSE の仕組み(図解)

+-------------+            +-------------+
|  クライアント  |<--HTTPリクエスト--> |   サーバー   |
| (React)     |            | (Spring Boot) |
|-------------|            |-------------|
| EventSource |  ←SSEイベント  | SseEmitter  |
| で接続       |            | で送信       |
+-------------+            +-------------+

🚀 Spring Boot で SSE を実装

まずは Spring Boot 側で SSE のエンドポイント を作成します。

📝 SSE のエンドポイントを作成

@RestController
@RequestMapping("/sse")
public class SseController {

    @GetMapping("/stream")
    public SseEmitter streamSse() {
        SseEmitter emitter = new SseEmitter();
        new Thread(() -> {
            try {
                for (int i = 0; i < 10; i++) {
                    emitter.send(SseEmitter.event()
                        .name("message")
                        .data("リアルタイム通知 " + i));
                    Thread.sleep(1000);
                }
                emitter.complete();
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        }).start();
        return emitter;
    }
}

ポイント

  • SseEmitter を使用し、非同期でイベントを送信
  • 1秒ごとにメッセージを送信(10回繰り返し)
  • エラー発生時は completeWithError を呼び出し

⚡ React で SSE を受信する

React 側で SSE を受信して UI を更新 します。

📝 SSE クライアントの実装

import React, { useEffect, useState } from 'react';

const SseComponent = () => {
    const [messages, setMessages] = useState([]);

    useEffect(() => {
        const eventSource = new EventSource('http://localhost:8080/sse/stream');

        eventSource.onmessage = (event) => {
            setMessages(prevMessages => [...prevMessages, event.data]);
        };

        eventSource.onerror = () => {
            console.error('SSEエラーが発生しました');
            eventSource.close();
        };

        return () => {
            eventSource.close();
        };
    }, []);

    return (
        <div>
            <h1>リアルタイム通知</h1>
            <ul>
                {messages.map((msg, index) => (
                    <li key={index}>{msg}</li>
                ))}
            </ul>
        </div>
    );
};

export default SseComponent;

ポイント

  • EventSource を使用して SSE 接続
  • onmessage で受信したメッセージを messages に追加
  • エラー発生時は SSE 接続を閉じる

✅ まとめ & 実践

🚀 Spring Boot × React で SSE を実装することで、リアルタイム通知が簡単に実現できる!
📌 SSE は WebSocket に比べて実装がシンプルで、通知システムに最適!
💡 サーバー側は SseEmitter、フロントエンドは EventSource を活用!

ぜひ、この記事を参考にしてリアルタイム通知機能を実装してみてください!🙌

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?