개발용 메모장...

[Java]/[Spring]

[SpringBoot] Redis 설정 ( RedisTemplate 사용 )

redeyesboy 2024. 9. 12. 17:16

1. 의존성 추가

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

 

2. Redis 관련 설정 추가

- application.properties

spring.data.redis.host=127.0.0.1
spring.data.redis.port=6379
spring.data.redis.password=비밀번호

 

3. Spring Boot 설정 파일 추가

@Configuration
public class RedisConfig {

	@Value(value = "${spring.data.redis.host}")
	private String host;

	@Value(value = "${spring.data.redis.port}")
	private String port;

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

	@Bean
	RedisConnectionFactory redisConnectionFactory() {
		RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
		redisStandaloneConfiguration.setHostName(host);
		redisStandaloneConfiguration.setPort(Integer.valueOf(port));
		redisStandaloneConfiguration.setPassword(password);
		LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(redisStandaloneConfiguration);
		return lettuceConnectionFactory;
	}

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

}

 

4. Utils 추가

예시용...

@Component
public class RedisUtils {

	private static RedisTemplate<String, Object> redisTemplate;

	public RedisUtils(RedisTemplate<String, Object> redisTemplate) {
		RedisUtils.redisTemplate = redisTemplate;
	}

	public static void delete(String key) {
		RedisUtils.redisTemplate.delete(key);
	}

	public static void set(String key, Object value) {
		RedisUtils.redisTemplate.opsForValue().set(key, value);
	}

	public static void set(String key, Object value, Duration timeout) {
		RedisUtils.redisTemplate.opsForValue().set(key, value, timeout);
	}

	public static void set(String key, String hashKey, Object value) {
		RedisUtils.redisTemplate.opsForHash().put(key, hashKey, value);
	}

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

	public static Object get(String key, String hashKey) {
		return RedisUtils.redisTemplate.opsForHash().get(key, hashKey);
	}

}