본문 바로가기
개발정리 (nodeJS)

[nodeJS] Node.js와 redis 연동하기

by 할리갈리0 2024. 5. 7.

Redis는 "Remote Dictionary Server"의 약자로, 고성능 키-값 저장소로 널리 사용되는 오픈 소스 인-메모리 데이터 구조 서버입니다. 다양한 데이터 구조를 지원하며, 데이터베이스, 캐시, 메시지 브로커 역할을 할 수 있습니다. 
Redis는 메모리 내 데이터 저장소로서 빠른 읽기 및 쓰기 작업을 제공하며, 디스크에도 지속적으로 데이터를 저장할 수 있어 재시작 후에도 데이터를 유지할 수 있습니다.

 

1. Node.js에서 Redis 사용 준비하기

Node.js에서 Redis를 사용하기 위해서는 먼저 Redis 서버가 설치되어 있어야 하며, Node.js 애플리케이션에서 Redis 클라이언트를 사용할 수 있도록 redis 패키지도 설치 필요

npm install redis

 

 

2. Redis 연결 및 기본 사용법

Redis에 연결하고 기본적인 키-값 데이터를 저장하고 조회하는 방법

const redis = require('redis');
const client = redis.createClient({
    url: 'redis://localhost:6379'
});

client.on('error', (err) => console.log('Redis Client Error', err));

async function run() {
    await client.connect();

    // 값 저장
    await client.set('key', 'value');

    // 값 조회
    const value = await client.get('key');
    console.log(value); // 'value'

    await client.quit();
}

run();

 

 

3. Redis를 이용한 고급 데이터 관리

Redis는 리스트, 세트, 해시 등 다양한 데이터 구조 지원

async function advancedDataManagement() {
    await client.connect();

    // 리스트에 데이터 추가
    await client.rPush('list', 'item1');
    await client.rPush('list', 'item2');

    // 리스트의 모든 항목 조회
    const list = await client.lRange('list', 0, -1);
    console.log(list); // ['item1', 'item2']

    await client.quit();
}

advancedDataManagement();

 

 

4. 실시간 애플리케이션에서의 Redis 활용

Redis는 빠른 데이터 처리 속도를 바탕으로 실시간 애플리케이션에서 널리 사용.
실시간 채팅 애플리케이션에서 메시지 캐싱, 세션 관리 등에 활용 가능

async function realTimeApplication() {
    await client.connect();

    // 실시간 채팅 메시지 저장
    await client.lPush('chat:room1', 'Hello, Redis!');
    await client.lPush('chat:room1', 'Welcome to the chat room.');

    // 최근 10개의 메시지 조회
    const messages = await client.lRange('chat:room1', 0, 9);
    console.log(messages);

    await client.quit();
}

realTimeApplication();

 

 

Node.js와 Redis를 결합함으로써, 개발자들은 빠른 데이터 처리와 관리가 필요한 다양한 애플리케이션을 효율적으로 개발할 수 있습니다. Redis는 실시간 채팅 애플리케이션, 메시지 큐, 세션 관리 등과 같은 실시간 데이터 처리가 중요한 시나리오에서 특히 가치가 있습니다.

반응형