Development/Spring

[Spring + Redis] Spring Redis 연동

hyelie 2022. 10. 4. 15:00

dependency

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

 

application.properties

spring.redis.host=127.0.0.1 spring.redis.port=6379

 

RedisUtil.java

import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisUtil {
    @Autowired 
	private StringRedisTemplate redisTemplate;

    public void set(String key, String value, Long minutes){
        redisTemplate.opsForValue().set(key, value, minutes, TimeUnit.MILLISECONDS);
    }

    public String get(String key){
        return redisTemplate.opsForValue().get(key);
    }

    public Boolean delete(String key){
        return redisTemplate.delete(key);
    }

    public Boolean hasKey(String key){
        return redisTemplate.hasKey(key);
    }
}

 

이렇게 util 파일 만들면 StringRedisTemplate에 알아서 redis가 연결된다. 사용은

@Autowired private final RedisUtil redisUtil;
redisUtil.get("key1");
redisUtil.set("key1", "value1", 10);

 

이렇게 쓰면 된다.