SpringBoot에서 Redis로 Session 구현하기

반응형
728x90
반응형

상황

SpringBoot 프로젝트를 진행하면서 로그인/로그아웃 API를 개발할 단계가 되었다. SpringBoot 프레임워크 프로젝트에 세션 관리를 Redis로 진행해보자.

 

 

Redis 설치

우선 프로젝트가 Redis를 연동할 수 있도록 Redis를 설치해야한다. docker에 redis를 간단하게 설치하였다.

docker redis 설치 포스팅 : devfunny.tistory.com/424?category=820624

 

docker로 redis 설치 (with docker-compose)

Redis 이미지 설치 docker pull redis docker-compose 파일 생성 version: '3.0' services: redis1: image: redis command: redis-server --requirepass root --port 6379 restart: always ports: - 6379:6379 doc..

devfunny.tistory.com

 

 

SpringBoot Redis Session 연동

  • 1) build.gradle
/* redis */
compile 'org.springframework.boot:spring-boot-starter-data-redis:2.4.2'
compile 'org.springframework.session:spring-session-data-redis:2.4.2'

 

  • 2) application.yml 수정
spring:
  # Redis
  redis:
    host: 127.0.0.1
    port: 6379
    password: changeme
  # Session
  session:
    store-type: redis
    redis:
        flush-mode: on_save

 

  • 3) RedisConfig.java 파일 생성
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.web.context.AbstractHttpSessionApplicationInitializer;

@Configuration
@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 60) /* 세션 만료 시간 : 60초 */
@RequiredArgsConstructor
public class RedisConfig extends AbstractHttpSessionApplicationInitializer {
    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private Integer port;

    @Value("${spring.redis.password}")
    private String password;

    private final ObjectMapper objectMapper;

    @Bean public RedisConnectionFactory lettuceConnectionFactory() {
        RedisStandaloneConfiguration standaloneConfiguration = new RedisStandaloneConfiguration(host, port);
        standaloneConfiguration.setPassword(password.isEmpty() ? RedisPassword.none() : RedisPassword.of(password));
        return new LettuceConnectionFactory(standaloneConfiguration);
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();

        redisTemplate.setConnectionFactory(lettuceConnectionFactory());
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer(objectMapper));

        return redisTemplate;
    }
}

 

 

로그인 API 구현

  • 1) AuthController.java 파일 생성
@RestController
@RequestMapping("/auth")
@RequiredArgsConstructor
@Slf4j
public class AuthController {
    private final MemberService memberService;

    @PostMapping("/login")
    public ResponseEntity<?> login(@ModelAttribute LoginDto loginDto, @ApiParam(hidden = true) HttpSession session) {
        session.setAttribute("session", loginDto.getMemberId());
        return CommonResponse.send(session.getId());
    }
}

 

  • 2) redis-cli에 key 조회
keys *

 

관련 session 정보가 redis에 들어가있는 상태를 확인할 수 있다.

 

 

 

반응형

Designed by JB FACTORY