티스토리 뷰
이전 글에서 캐시에 대해 기본적으로 작성을 하였으니 이번에는 캐시 메모리를 사용하는 데이터베이스 중에 하나인 레디스에 대해 간략하게 구성하는 방법을 알려드리고자 합니다.
기본적으로 AutoConfiguration 이 가능하지만 사용자의 설정에 맞게 설정을 할 수도 있습니다.
환경
Spring Boot 2.5.0
JDK 11
Java 11
build.gradle 에 아래와 같이 의존성을 추가해줍니다.
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
그리고 추가로 저같은 경우 다른 *.properties 파일을 사용했기 때문에 아래와 같은 의존성 하나를 더 추가해주었습니다.
implementation 'org.springframework.boot:spring-boot-configuration-processor'
그 다음 RedisConfig 파일을 생성하고 내부에 다음과 같이 설정해줍니다.
@PropertySource("classpath:redis.properties")
@Configuration
@Slf4j
@ConfigurationProperties(prefix = "spring.redis")
@EnableRedisRepositories(basePackages = "com.package.name")
@Setter
public class RedisConfig implements Serializable {
private static final long serialVersionUID = 3487495895819393L;
private String host;
private int port;
private String password;
private int database;
@Bean
public LettuceConnectionFactory getRedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);
redisStandaloneConfiguration.setPassword(password);
redisStandaloneConfiguration.setDatabase(database);
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
@Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(getRedisConnectionFactory());
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
redisTemplate.setHashKeySerializer(new Jackson2JsonRedisSerializer<>(Object.class));
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
}
기본적인 설명은 다음과 같습니다.
Redis Database 에서 사용할 기본적인 설정값들의 명세 프로퍼티 파일입니다. 여기에는 기본적으로 redis에서 사용하는 값이 host, port 정도가 세팅되는데 저 같은 경우 Redis 데이터베이스 내 인증이 필요한 부분이 설정되어 있기 때문에 비밀번호를 password 라는 값으로 같이 넣었습니다.
@PropertySource("classpath:redis.properties")
redis.properties
spring.redis.host=${redis-host}
spring.redis.port=${redis-port}
spring.redis.database=${redis-db-number}
spring.redis.password=${redis-auth}
@ConfigurationProperties(prefix = "spring.redis")
위 설정은 redis.properties 파일 내에 prefix 를 자동으로 매핑해주는 설정입니다.
@EnableRedisRepositories(basePackages = "com.package.name")
위 설정은 아까 spring-boot-configuration-processor 의존성을 추가한 부분에서 가져온 내용입니다. Redis 를 사용할 수 있는 패키지 범위를 의미합니다. 처음에 프로젝트를 생성할 때 Artifact ID, Group ID 와 관련된 내용입니다.
@Bean
public LettuceConnectionFactory getRedisConnectionFactory() {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration(host, port);
redisStandaloneConfiguration.setPassword(password);
redisStandaloneConfiguration.setDatabase(database);
return new LettuceConnectionFactory(redisStandaloneConfiguration);
}
다음으로 LettuceConnectionFactory 에 대한 내용입니다. 이 내용은 이전에도 제가 작성한 글에 존재하네요.
Jedis 보다는 Lettuce를 쓰자
Author: 니용 서버 개발자라면 한 번은 들어본 Redis라는 캐시 메모리가 있습니다. 성능적인 면에서도 우수하고 부하가 거의 없기에 잘 사용하고 있는 라이브러리 중 하나이지요. Java는 2가지의 Redis
abbo.tistory.com
다만 여기서 다른 점은 password, database 를 설정하는 것인데 Redis Database 는 0부터 15번의 데이터베이스 중 하나를 선택하여 지정할 수 있습니다. 기본값은 0으로 알고 있습니다. password 는 Redis Database 에 접근할 때 필요한 패스워드를 의미합니다. 이 패스워드 설정은 서버에서 설정할 수 있고, 나중에 따로 글을 작성해보겠습니다.
@Bean
public RedisTemplate<?, ?> redisTemplate() {
RedisTemplate<byte[], byte[]> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(getRedisConnectionFactory());
redisTemplate.setHashValueSerializer(new Jackson2JsonRedisSerializer<>(Object.class));
redisTemplate.setHashKeySerializer(new Jackson2JsonRedisSerializer<>(Object.class));
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
return redisTemplate;
}
이전과는 조금 달라진 것이, Jackson2JsonRedisSerializer를 사용하고 있습니다. Spring boot 버전이 달라진 만큼 (저는 2.5.0 버전을 사용하고 있습니다.) 기본적으로 취급하는 Serializer 가 달라지긴 했는데, 직렬화와 관련된 글은 아래에 따로 작성해두었습니다.
자바 직렬화(Java Object Serialization)에 유연성 더하기
자바 객체를 영속화하는 방법의 하나로 자바 직렬화를 사용할 수 있다. 단순하게는 Serializable 인터페이스를 구현하거나 더 확장성 있는 방법으로는 Externalizable 인터페이스를 구현하는 것을 선택
abbo.tistory.com
이제 세팅을 다 했으니 사용을 해보겠습니다~! 사용 방법은 아래에 작성해볼게요 :)
[Spring] Redis 실제 사용해보기
abbo.tistory.com
'Server' 카테고리의 다른 글
[Java] 자바 19 에서 달라진 점 코드로 확인하기 (0) | 2022.12.29 |
---|---|
[Gradle] build.gradle 에 적은 project.version 을 푸터에 표시해보자 (0) | 2022.12.28 |
[Spring] Redis 실제 사용해보기 (0) | 2022.12.16 |
[Spring] 캐시의 추상화와 사용법 (@Cacheable, @CachePut, @CacheEvict) (0) | 2022.12.16 |
[AWS] IAM 에서 사용하는 사용자 이메일 변경하기 (4) | 2022.12.09 |
[Nginx] 서버에 요청받는 Request Body Size 늘리기 (2) | 2022.12.09 |