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);
}
}
'[Java] > [Spring]' 카테고리의 다른 글
[SpringBoot] Redis 설정 ( Cache 사용 ) (0) | 2024.09.20 |
---|---|
[SpringBoot] Database Logging 설정 (0) | 2024.08.27 |
[SpringBoot] Logback 설정 (0) | 2024.08.27 |
[SpringBoot] Jasypt 설정( 프로퍼티 암호화 ) (0) | 2024.08.26 |
[SpringBoot] Thymeleaf 설정 (0) | 2024.08.26 |