본문 바로가기

개발일지

20231127 - redis 사용법

1. redis를 설치해준다

https://github.com/microsoftarchive/redis/releases

 

Releases · microsoftarchive/redis

Redis is an in-memory database that persists on disk. The data model is key-value, but many different kind of values are supported: Strings, Lists, Sets, Sorted Sets, Hashes - microsoftarchive/redis

github.com

 

2.build.gradle

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

 

3.application.properties

spring.redis.uri = redis://localhost:6379

 

4.RedisConfig.java

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.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisConnectionFactory redisConnectionFactory(){
        return new LettuceConnectionFactory();
    }

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

}

 

5.사용

private final RedisTemplate<String , String > redisTemplate;

    redisTemplate.opsForValue().set(key, value, timeout, timeunit); // 데이터 입력
    redisTemplate.hasKey(key); // 데이터 유무
    redisTemplate.delete(key); // 데이터 삭제
}