Redis

2024. 1. 28. 21:32Spring Boot

Redis는 Memory DB이다

비교적 속도가 빠르기 때문에 Session Storage으로 이용하기도 한다

 

build.gradle를 이용해 필요한 library를 추가한다

 

 

implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.session:spring-session-data-redis'

 

원하는 방식으로 host와 port를 설정한다

보통 application.properties에 추가해서 설정한다

 

 

spring.session.store-type=redis
spring.data.redis.port = 6379
spring.data.redis.host = localhost

 

혹은 

@Configuration을 이용해 설정 할 수도 있다

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;

import org.springframework.beans.factory.annotation.Value;

@Configuration
@PropertySource("classpath:redis.properties")
public class redis_config {

    @Value("${host}")
    private String host;

    @Value("${port}")
    private int port;

    @Bean
    public RedisConnectionFactory redisConnectionFactory() {
        System.out.printf("%s", host);
        return new LettuceConnectionFactory(host, port);
    }
}

 

 

이제 다른 DB와 크게 다르지 않다

 

import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;
import org.springframework.data.redis.core.TimeToLive;
import org.springframework.data.redis.core.index.Indexed;
import org.springframework.security.core.Authentication;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
@RedisHash(value = "keys")
public class redis_token {

    @Id
    private String authId;

    @Indexed
    private String sessionId;

    @TimeToLive
    private long ttl;

    private Authentication auth;

    public redis_token (String token, long ttl) {
        this.sessionId = token;
        this.ttl = ttl;
    }

}

 

사용할 Entity를 class로 구현하고

 

import org.springframework.data.repository.CrudRepository;

public interface redis_repository extends CrudRepository<redis_token, String>{
}

 

repository를 구현하면 된다

 

또한 위에 Session 관련 설정을 설정 했기 때문에 자동으로 Session Storage도 구성이 되었다

'Spring Boot' 카테고리의 다른 글

Image File Handling  (0) 2024.02.03
Mulit Database by MySQL  (0) 2024.02.03
RestController  (0) 2024.01.28
Oauth2 by Google  (0) 2024.01.22
Docker Container에 JAR 이미지 돌리기  (0) 2024.01.20