반응형

https://github.com/Seungkyu-Han/Notice_Board_Project

 

GitHub - Seungkyu-Han/Notice_Board_Project: WebFlux를 사용한 게시판 토이 프로젝트

WebFlux를 사용한 게시판 토이 프로젝트. Contribute to Seungkyu-Han/Notice_Board_Project development by creating an account on GitHub.

github.com

 

이번에 서버를 하나 만들면서 WebFlux에 Session을 사용할 일이 생겼다.

 

Servlet에서 Session을 관리해 본 적이 있는데, WebFlux에서는 처음이다.

아마 실제로 서비스를 하면 Redis에 session 정보들을 저장할테지만, 토이 프로젝트이기 때문에 그냥 session 자체에 저장해보자.

 

보통 WebFlux의 Service 부분은

override suspend fun login(request: ServerRequest): ServerResponse {}

 

이런 식으로 구성이 되어있다.

 

Session 정보는 이 중 ServerRequest에 있다.

 

        request.session()
            .doOnNext{
                it.attributes["id"] = loginReq.id
            }
            .awaitFirst()

 

이런 식으로 session의 attribute에 원하는 값을 Key와 value로 넣어준다.

 

가져올 때는 

        val userId = request.session()
            .map {
                it.attributes.getOrDefault("id", "") as String
            }.awaitSingle()

 

이런 식으로 it.attribute에서 가져온다.

[]로 가져올 수 있고, get이나 getOrDefault로 가져올 수 있다.

Any Type이기 때문에 Casting이 필요할 수도 있다.

 

Session을 종료하고 싶으면 invalidate를 사용하면 된다.

    override suspend fun logout(request: ServerRequest): ServerResponse {

        request.session().map{
            it.invalidate()
        }.awaitSingle()

        return ServerResponse.ok().buildAndAwait()
    }

 

이런 식으로 session을 가져오고 invalidate로 끊어주자

 

그러고는 intellij의 http client로 테스트 해보자.

POST http://localhost:8080/users/login
Content-Type: application/json

{
  "id": "seungkyu",
  "password": "12041204"
}

###
GET http://localhost:8080/users/my-info
Content-Type: application/json
Cookie: sessionId=<session>

 

 

intellij의 http client는 session을 유지하여 다음 http를 요청해준다.

 

이렇게 연속으로 2개 다 성공하는 것을 볼 수 있다.

사용자의 정보도 잘 가져오는 것을 볼 수 있었다.

+ Recent posts