Spring boot+redis session共有を実現


今回はspring boot+redisでセッション共有を実現するチュートリアルをお届けします.
 
spring bootのドキュメントでは、spring sessionサポートを開始するために@E n a b l e RedisHttpSessionを追加する方法を説明しています.次のように構成されています.
@Configuration
@EnableRedisHttpSession
public class RedisSessionConfig {
}
,@EnableRedisHttpSessionこの注釈はspring-session-data-redisによって提供されるのでpom.xmlファイルに追加:
<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-redis</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.session</groupId>
        <artifactId>spring-session-data-redis</artifactId>
</dependency>
 
 
次に、アプリケーション.propertiesでredisサーバを構成する場所です.ここでは、ネイティブを使用します.
spring.redis.host=localhost
spring.redis.port=6379

これにより,最も簡単なspring boot+redis実装セッション共有が完了し,以下でテストを行う.
 
まず、アプリケーションでは8080と9090の2つのtomcatサービスを開始します.propertiesで設定:
server.port=8080

 
次に、Controllerを定義します.
@RestController
@RequestMapping(value = "/admin/v1")
public class QuickRun {
    @RequestMapping(value = "/first", method = RequestMethod.GET)
    public Map<String, Object> firstResp (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        request.getSession().setAttribute("request Url", request.getRequestURL());
        map.put("request Url", request.getRequestURL());
        return map;
    }

    @RequestMapping(value = "/sessions", method = RequestMethod.GET)
    public Object sessions (HttpServletRequest request){
        Map<String, Object> map = new HashMap<>();
        map.put("sessionId", request.getSession().getId());
        map.put("message", request.getSession().getAttribute("map"));
        return map;
    }
}

 
起動後にアクセステストを行い、まず8080ポートのtomcatにアクセスし、次のように返します.
{"request Url":"http://localhost:8080/admin/v1/first"}

次に、8080ポートのセッションにアクセスし、次のように返します.
{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}

最後に、9090ポートのセッションに再アクセスし、次のように戻ります.
{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:8080/admin/v1/first"}

8080は9090の2つのサーバが結果を返すのと同じようにセッションの共有を実現していることがわかる.
 
この時点で9090ポートのfirstに再アクセスすると、まず戻ります.
{"request Url":"http://localhost:9090/admin/v1/first"}

両方のサーバのセッションは返されます.
{"sessionId":"efcc85c0-9ad2-49a6-a38f-9004403776b5","message":"http://localhost:9090/admin/v1/first"}

 
spring boot+redisによるsessionの共有は非常に簡単であり,用途も極めて大きく,nginxと組み合わせて負荷等化を行うことで分布式の応用を実現できる.
今回のredisでは主従、読み書き分離などの構成は行われていません(:;)з」∠)_実はブロガーは怠け者で、まだ試したことがありません......)
そして、nginxの単点障害も私たちの応用の障害です......今後、zookeeperを用いたロードバランシングなど、今回のブログの改良バージョンがある可能性がありますので、ご期待ください.