TCP서버에서 REDIS활용
TCP 서버에서 Redis를 활용하여 데이터를 저장하는 방법에 대해 알아보겠습니다. Node.js를 사용하여 TCP 서버를 구축하고, redis 패키지를 사용하여 Redis와 상호작용하는 예제를 단계별로 설명하겠습니다.
1. Node.js와 redis 패키지 설치
TCP 서버와 Redis 클라이언트를 위한 프로젝트를 설정하고 필요한 패키지를 설치합니다.
npm init -y
npm install redis
2. TCP 서버 설정
Node.js의 net 모듈을 사용하여 TCP 서버를 설정합니다.
TCP 서버 코드
const net = require('net');
const redis = require('redis');
// Redis 클라이언트 생성
const redisClient = redis.createClient();
redisClient.on('connect', () => {
console.log('Connected to Redis...');
});
redisClient.on('error', (err) => {
console.log('Redis error: ', err);
});
// TCP 서버 생성
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
// 클라이언트로부터 받은 데이터 처리
const message = data.toString().trim();
const [command, key, value] = message.split(' ');
if (command === 'SET') {
redisClient.set(key, value, (err, reply) => {
if (err) {
socket.write('Error setting value\n');
} else {
socket.write(`Value set for key ${key}\n`);
}
});
} else if (command === 'GET') {
redisClient.get(key, (err, reply) => {
if (err) {
socket.write('Error getting value\n');
} else {
socket.write(`Value for key ${key}: ${reply}\n`);
}
});
} else {
socket.write('Unknown command\n');
}
});
socket.on('end', () => {
console.log('Client disconnected');
});
socket.on('error', (err) => {
console.log('Socket error: ', err);
});
});
server.listen(12345, () => {
console.log('Server listening on port 12345');
});
3. TCP 서버 실행
위 코드를 server.js 파일에 저장하고, 다음 명령어로 서버를 실행합니다.
node server.js
4. 클라이언트에서 TCP 서버와 상호작용
클라이언트는 TCP 서버에 연결하여 데이터를 저장하거나 조회할 수 있습니다. 여기서는 netcat 명령어를 사용하여 간단한 클라이언트를 만듭니다.
데이터 저장 (SET 명령어)
echo "SET mykey myvalue" | nc localhost 12345
서버 로그에는 다음과 같은 출력이 나옵니다:
Client connected
Value set for key mykey
데이터 조회 (GET 명령어)
echo "GET mykey" | nc localhost 12345
서버 로그에는 다음과 같은 출력이 나옵니다:
Client connected
Value for key mykey: myvalue
5. 응용: JSON 데이터 저장 및 조회
더 복잡한 데이터를 저장하려면 JSON을 사용할 수 있습니다.
TCP 서버 코드 수정
const net = require('net');
const redis = require('redis');
const redisClient = redis.createClient();
redisClient.on('connect', () => {
console.log('Connected to Redis...');
});
redisClient.on('error', (err) => {
console.log('Redis error: ', err);
});
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
const message = data.toString().trim();
const [command, key, ...rest] = message.split(' ');
if (command === 'SET') {
const value = rest.join(' ');
redisClient.set(key, value, (err, reply) => {
if (err) {
socket.write('Error setting value\n');
} else {
socket.write(`Value set for key ${key}\n`);
}
});
} else if (command === 'GET') {
redisClient.get(key, (err, reply) => {
if (err) {
socket.write('Error getting value\n');
} else {
socket.write(`Value for key ${key}: ${reply}\n`);
}
});
} else {
socket.write('Unknown command\n');
}
});
socket.on('end', () => {
console.log('Client disconnected');
});
socket.on('error', (err) => {
console.log('Socket error: ', err);
});
});
server.listen(12345, () => {
console.log('Server listening on port 12345');
});
JSON 데이터 저장 및 조회
# JSON 데이터 저장
echo "SET user:1000 {\"name\":\"John Doe\",\"age\":30}" | nc localhost 12345
# JSON 데이터 조회
echo "GET user:1000" | nc localhost 12345
6. 보안 및 최적화
- 보안: 실무에서는 TCP 서버를 직접 노출하지 않고, 방화벽 설정이나 VPN을 통해 접근을 제한합니다.
- 최적화: Redis 클라이언트 설정을 최적화하고, 필요에 따라 Redis 클러스터링을 사용하여 성능을 향상시킵니다.
이로써 TCP 서버에서 Redis를 활용하여 데이터를 저장하고 조회하는 방법을 알아보았습니다. 추가로 Redis의 이점에 대해 알아보겠습니다.
Redis는 고가용성(High Availability) 및 데이터 분산을 위한 다양한 기능을 제공하며, 클러스터 모드를 통해 데이터의 분산 저장 및 복제를 지원합니다. 여기서는 Redis의 고가용성 및 데이터 분산 개념을 소개하고, Redis 클러스터 모드를 설정하는 방법을 설명하겠습니다.
1. Redis 고가용성 (High Availability)
Redis Sentinel
Redis Sentinel은 Redis의 고가용성을 위한 솔루션으로, 마스터-슬레이브 구조를 기반으로 합니다. Sentinel은 마스터와 슬레이브 인스턴스를 모니터링하고, 마스터가 실패하면 슬레이브 중 하나를 새로운 마스터로 승격시키는 역할을 합니다.
Redis Sentinel 설정
- Redis 마스터 및 슬레이브 설정:
- Redis 마스터와 슬레이브 인스턴스를 설정합니다. 슬레이브 인스턴스는 replicaof 지시어를 사용하여 마스터를 지정합니다.
# Master redis.conf
port 6379
# Slave redis.conf
port 6380
replicaof 127.0.0.1 6379
2. Sentinel 설정:
- Sentinel 설정 파일을 생성하고, 마스터 인스턴스를 모니터링하도록 설정합니다.
# sentinel.conf
sentinel monitor mymaster 127.0.0.1 6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000
sentinel parallel-syncs mymaster 1
3. Sentinel 실행:
- Sentinel을 실행합니다.
redis-server sentinel.conf --sentinel
2. Redis 클러스터 모드
Redis 클러스터는 데이터 분산 저장과 고가용성을 제공하는 방식으로, 여러 Redis 노드가 협력하여 데이터를 분산 저장합니다. 각 노드는 데이터의 일부를 담당하며, 노드 간 자동으로 데이터를 복제합니다.
Redis 클러스터 설정
- Redis 클러스터 노드 설정:
- 각 노드의 설정 파일을 생성합니다. 클러스터 모드와 포트 등을 설정합니다
# redis-node-7000.conf
port 7000
cluster-enabled yes
cluster-config-file nodes-7000.conf
cluster-node-timeout 5000
appendonly yes
2. 클러스터 노드 시작:
- 각 노드를 시작합니다
redis-server redis-node-7000.conf
redis-server redis-node-7001.conf
redis-server redis-node-7002.conf
redis-server redis-node-7003.conf
redis-server redis-node-7004.conf
redis-server redis-node-7005.conf
클러스터 구성:
- Redis 클러스터를 구성합니다. redis-cli를 사용하여 클러스터를 설정합니다
redis-cli --cluster create 127.0.0.1:7000 127.0.0.1:7001 127.0.0.1:7002 127.0.0.1:7003 127.0.0.1:7004 127.0.0.1:7005 --cluster-replicas 1
여기서 --cluster-replicas 1은 각 마스터 노드마다 하나의 슬레이브 노드를 설정하겠다는 의미입니다.
클러스터 모드에서 데이터 작업
클러스터 모드에서는 데이터가 노드 간에 분산되어 저장됩니다. 클러스터 모드를 사용하려면 클라이언트에서도 이를 지원해야 합니다. ioredis 패키지를 사용하여 Node.js에서 Redis 클러스터 모드를 사용하는 예시입니다.
ioredis 설치
npm install ioredis
클러스터 클라이언트 설정
const Redis = require('ioredis');
const cluster = new Redis.Cluster([
{ host: '127.0.0.1', port: 7000 },
{ host: '127.0.0.1', port: 7001 },
{ host: '127.0.0.1', port: 7002 },
{ host: '127.0.0.1', port: 7003 },
{ host: '127.0.0.1', port: 7004 },
{ host: '127.0.0.1', port: 7005 }
]);
cluster.set('key', 'value').then(() => {
return cluster.get('key');
}).then((result) => {
console.log(result); // value
}).catch((err) => {
console.error(err);
});
이와 같은 방식으로 Redis 클러스터를 구성하고, 데이터 분산 및 복제를 통해 고가용성을 유지할 수 있습니다. 클러스터 모드를 사용하면 대규모 데이터 처리와 높은 가용성을 요구하는 애플리케이션에 적합합니다.