Redis와 Node.js 연동하기 샘플
redis 패키지를 이용한 Node.js와 Redis 연동 가이드
1. redis 패키지란?
redis는 Node.js 환경에서 Redis 데이터베이스와 상호작용하기 위한 공식 클라이언트 라이브러리입니다. 간단한 Key-Value 저장뿐만 아니라, Pub/Sub, 스트림, 트랜잭션 등 Redis의 강력한 기능들을 Node.js에서 쉽게 사용할 수 있도록 지원합니다.
redis 패키지는 v4를 기점으로 큰 변화가 있었으므로, 사용 중인 버전을 확인하고 그에 맞는 문법을 사용하는 것이 매우 중요합니다. 새로운 프로젝트에는 v4 사용을 강력히 권장합니다.
2. 설치
# 최신 버전 (v4.x) 설치
npm install redis
# 이전 버전 (v3.x 또는 v2.x) 설치 (레거시 프로젝트용)
npm install redis@3.1.2
3. redis v4 사용법 (최신 - 권장)
v4는 Promise와 async/await를 기본으로 지원하여 코드를 훨씬 깔끔하고 직관적으로 작성할 수 있습니다. createClient의 옵션과 연결 방식이 v3와 완전히 다르므로 주의해야 합니다.
1) 클라이언트 생성 (createClient) 및 주요 옵션
v4에서는 모든 옵션을 하나의 설정 객체로 전달하며, await client.connect()를 통해 수동으로 연결해야 합니다.
import { createClient } from "redis"; // ESM 방식
// const { createClient } = require('redis'); // CommonJS 방식
// 1. 클라이언트 생성
const client = createClient({
// --- 연결 옵션 (url 또는 socket 중 택일) ---
// 방법 A: URL 사용 (가장 간편하고 권장됨)
// 형식: redis[s]://[[username][:password]@][host][:port][/database]
url: "redis://:YOUR_PASSWORD@127.0.0.1:6379/1",
// 방법 B: Socket 객체 사용 (더 상세한 설정 필요 시)
socket: {
host: "127.0.0.1",
port: 6379,
// tls: true, // SSL/TLS 연결 시
// reconnectStrategy: (retries) => Math.min(retries * 50, 500) // 재연결 전략(ms)
},
// --- 인증 및 DB 선택 (URL에 포함되지 않았을 경우) ---
password: "YOUR_PASSWORD",
database: 1, // v3의 'db'가 'database'로 변경됨 (기본값: 0)
// --- 기타 옵션 ---
// name: 'my-client', // 클라이언트 이름 지정 (Redis 6.2 이상)
// commandsQueueMaxLength: 1000, // 연결 끊겼을 때 쌓아둘 명령어 최대 갯수
});
// 2. 에러 리스너 설정 (필수)
client.on("error", (err) => console.log("Redis Client Error", err));
// 3. 연결 (비동기 함수 내에서 실행)
async function connectRedis() {
try {
await client.connect();
console.log("Successfully connected to Redis!");
} catch (err) {
console.error("Could not connect to Redis:", err);
}
}
connectRedis();
2) 기본 명령어 사용법 (async/await)
모든 명령어는 Promise를 반환하므로 await을 사용할 수 있습니다.
SET / GET (문자열)
async function testString() {
try {
const setResult = await client.set("my_key", "Hello Async Redis");
console.log(setResult); // 'OK'
const getResult = await client.get("my_key");
console.log(getResult); // 'Hello Async Redis'
} catch (err) {
console.error(err);
}
}
testString();
LPUSH / LRANGE (리스트)
async function testList() {
try {
// 여러 값을 배열로 전달 가능
const listLength = await client.lPush("my_list", ["item1", "item2"]);
console.log("List length:", listLength); // 2
const listItems = await client.lRange("my_list", 0, -1);
console.log(listItems); // ['item2', 'item1']
} catch (err) {
console.error(err);
}
}
testList();
3) Pub/Sub (발행/구독) 예제
v4에서는 client.duplicate()를 통해 클라이언트를 복제하여 구독용으로 사용합니다.
const publisher = client.duplicate();
const subscriber = client.duplicate();
(async () => {
try {
// 각 클라이언트를 개별적으로 연결
await publisher.connect();
await subscriber.connect();
// 1. 채널 구독 및 메시지 핸들러 등록
await subscriber.subscribe("news_channel", (message, channel) => {
console.log(`Received message from channel '${channel}': ${message}`);
});
// 2. 3초마다 메시지 발행
setInterval(() => {
const message = `Current time is ${new Date().toLocaleTimeString()}`;
publisher.publish("news_channel", message);
}, 3000);
} catch (err) {
console.error(err);
}
})();
4. redis v2 / v3 사용법 (레거시 - 참고용)
redis v2와 v3는 거의 동일한 API를 사용하며, 콜백(Callback) 기반의 비동기 처리가 기본입니다. 기존 프로젝트 유지보수 시 참고할 수 있습니다.
1) 클라이언트 생성 (createClient) 및 주요 옵션
v2/v3에서는 createClient의 인자로 port, host를 직접 전달하고, 나머지 옵션을 객체로 전달합니다.
const redis = require("redis");
const client = redis.createClient(6379, "127.0.0.1", {
// --- 주요 옵션 ---
password: "YOUR_PASSWORD",
db: 1, // v4의 'database'와 다름
// --- 재시도 전략 (중요) ---
retry_strategy: (options) => {
if (options.error && options.error.code === "ECONNREFUSED") {
return new Error("The server refused the connection");
}
// ... 기타 재시도 로직 ...
return 1000; // 1초 후 재시도
},
});
// 에러 이벤트 리스너는 필수로 작성해야 합니다.
client.on("error", (err) => {
console.error("Redis Client Error:", err);
});
client.on("connect", () => {
console.log("Successfully connected to Redis!");
});
2) 기본 명령어 사용법 (콜백 기반)
모든 명령어는 마지막 인자로 (err, reply) 형태의 콜백 함수를 받습니다.
SET / GET (문자열)
client.set("my_key", "Hello Redis", (err, reply) => {
if (err) throw err;
console.log(reply); // 'OK'
client.get("my_key", (err, reply) => {
if (err) throw err;
console.log(reply); // 'Hello Redis'
});
});
LPUSH / LRANGE (리스트)
client.lpush("my_list", "item1", "item2", (err, reply) => {
if (err) throw err;
client.lrange("my_list", 0, -1, (err, reply) => {
if (err) throw err;
console.log(reply); // ['item2', 'item1']
});
});
3) Pub/Sub (발행/구독) 예제
Pub/Sub을 위해서는 일반 클라이언트와 별도의 구독용 클라이언트를 생성해야 합니다.
const publisher = redis.createClient(/* ... */);
const subscriber = redis.createClient(/* ... */);
// 1. 구독 클라이언트 설정
subscriber.on("message", (channel, message) => {
console.log(`Received message from channel '${channel}': ${message}`);
});
subscriber.subscribe("news_channel");
// 2. 발행 클라이언트로 메시지 발행
setInterval(() => {
const message = `Current time is ${new Date().toLocaleTimeString()}`;
publisher.publish("news_channel", message);
}, 3000);