Redis(레디스)는 REmote DIctionary Server의 약자로 오픈소스(BSD licensed) DBMS입니다.
In-memory(인메모리) 데이터 저장소이며, Key-Value기반의 NoSQL DBMS입니다.
보통 DB, Cache(캐시), 메시지 브로커 등의 용도로 사용합니다.
For instance, using pipelining Redis running on an average Linux system can deliver even 1 million requests per second.
초당 10만 ~ 15만건의 명령을 수행할 수 있으며, 위 공식문서의 내용처럼 파이프링을 통해
리눅스시스템에서 초당 100만건의 요청도 수행이 가능하다고 합니다.
성능
모든 Redis 데이터는 메모리에 저장되어 대기 시간을 낮추고 처리량을 높인다.
평균적으로 읽기 및 쓰기의 작업 속도가 1ms로 디스크 기반 데이터베이스보다 빠르다.
유연한 데이터 구조
Redis의 데이터는 String, List, Set, Hash, Sorted Set, Bitmap, JSON 등 다양한 데이터 타입을 지원한다.
따라서, 애플리케이션의 요구 사항에 알맞은 다양한 데이터 타입을 활용할 수 있다.
개발 용이성
Redis는 쿼리문이 필요로 하지 않으며, 단순한 명령 구조로 데이터의 저장, 조회 등이 가능하다.
또한, Java, Python, C, C++, C#, JavaScript, PHP, Node.js, Ruby 등을 비롯한 다수의 언어를 지원한다.
영속성
Redis는 영속성을 보장하기 위해 데이터를 디스크에 저장할 수 있다. 서버에 치명적인 문제가 발생하더라도 디스크에 저장된 데이터를 통해 복구가 가능하다.
싱글 스레드 방식
Redis는 싱글 스레드 방식을 사용하여 한 번에 하나의 명령어만을 처리한다. 따라서 연산을 원자적으로 처리하여 Race Condition(경쟁 상태)가 거의 발생하지 않는다.
하지만, 멀티 스레드를 지원하지 않기 때문에 시간 복잡도가 O(n)인 명령어의 사용은 주의해서 사용해야 한다.
RedisConfig.java
import org.springframework.beans.factory.annotation.Value;
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.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
@EnableRedisRepositories
public class RedisConfig {
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Bean
public RedisConnectionFactory redisConnectionFactory() {
return new LettuceConnectionFactory(host, port);
}
@Bean
public RedisTemplate<String, String> redisTemplate() {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setValueSerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory());
return redisTemplate;
}
}
application.yml
spring:
redis:
host: localhost
port: 6379
여기까지 기본 로컬에 설치되는 값들을 추가해주고
조회수 기능을 넣어볼것이다.
service단에서 처리를 해줄겁니다.
BoardService.java
@Service
@RequiredArgsConstructor
public class BoardService {
// 레디스 사용하기위함
private final RedisTemplate<String, String> redisTemplate;
// 조회수 증가
public int incrementViewCount(int postId) {
String key = "postId:" + postId + ":views";
ValueOperations<String, String> ops = redisTemplate.opsForValue();
ops.increment(key);
int viewCount = this.getViewCount(postId);
if(viewCount % 100 == 0){
boardMapper.updateHit(postId,viewCount);
}
return viewCount;
// 조회수 조회
public int getViewCount(int postId){
String key = "postId:" + postId + ":views";
ValueOperations<String, String> ops = redisTemplate.opsForValue();
return Integer.parseInt(ops.get(key));
}
위와 같이
ValueOperations<String, String> ops = redisTemplate.opsForValue(); 생성후
increment(key) : 생성
get(key) : 조회
String자료형 말고도 많은 자료구조를 지원하니 더 공부해서 활용적으로 쓸수있을거같다.