
1. Redis 설치 및 클라이언트 설정
지난 시간에 nodejs를 사용해 redis 서버를 구성해보았습니다. 이번 시간에는 전 포스팅과 같이 nodejs로 redis 서버를 설정하고 CRUD 기능을 추가해보도록 하겠습니다. 아래 명령어로 새 Node.js 프로젝트를 생성합니다.
npm init -y
redis를 구성하기 위해 필요한 기본 Node 라이브러리 설치가 필요합니다. 아래 명령어로 라이브러리를 설치합니다.
npm install express redis
2. Redis 클라이언트 설정
프로젝트 디렉토리에 index.js 파일을 생성 후 아래와 같은 코드를 추가합니다.
// node-js setting
const express = require("express");
const { createClient } = require("redis");
const app = express();
const PORT = 3000;
// 비동기 클라이언트 생성
const client = createClient();
client.on("error", (err) => {
console.error("Redis Client Error:", err);
});
app.use(express.json());
// Redis 클라이언트 연결
(async () => {
await client.connect();
})();
이제 기본적인 CRUD를 구현하기 위해 똑같이 index.js에 아래 코드를 입력해 CRUD API 엔드포인트를 설정합니다.
// CRUD setting
// Create
app.post("/data", async (req, res) => {
const { key, value } = req.body;
try {
await client.set(key, value);
res.send("Data create Successfully");
} catch (err) {
res.status(500).send(err);
}
});
// Read
app.get("/data/:key", async (req, res) => {
const { key } = req.params;
try {
const value = await client.get(key);
res.send(value);
} catch (err) {
res.status(500).send(err);
}
});
// Delete
app.delete("/data/:key", async (req, res) => {
const { key } = req.params;
try {
await client.del(key);
res.send("Data deleted Successfully");
} catch (err) {
res.status(500).send(err);
}
});
app.listen(PORT, () => {
console.log(`Server is running on http://localhost:${PORT}`);
});
3. 서버 실행
아래 명령어로 서버를 실행하고 브라우저 또는 Postman API를 사용해 테스트합니다.
node index.js
- 브라우저 또는 Postman을 사용해 API 테스트
- POST /data : 데이터 작성
- GET /data/:key : 데이터 읽기
- DELETE /data/:key : 데이터 삭제하기
4. PostMan 테스트
- 데이터 작성 (POST 요청)
- HTTP 메서드: POST
- URL: http://localhost:3000/data
- Headers: Content-Type: application/json
- 바디: JSON 형식으로 데이터 전달
{
"key": "exampleKey",
"value": "exampleValue"
}
- 방법
- Postman을 열고 새로운 요청 생성
- 메서드를 POST로 설정
- URL에 http://localhost:3000/data을 입력함
- Headers 탭에서 Content-Type을 application/json으로 설정
- Body 탭을 선택하고 raw를 선택한 후 JSON 데이터 입력
- Send 버튼을 클릭해서 요청을 보냄
- 데이터 조회 (GET 요청)
- HTTP 메서드: GET
- URL: http://localhost:3000/data/exampleKey (exampleKey 부분은 조회할 키)
- 데이터 삭제 (DELETE 요청)
- HTTP 메서드: DELETE
- URL: http://localhost:3000/data/exampleKey를 입력
- Send 버튼 클릭으로 삭제 요청을 보냄
- 응답으로 삭제 결과가 반영
GitHub - Koras02/redis-blog
Contribute to Koras02/redis-blog development by creating an account on GitHub.
github.com
LIST
'Back-End > Redis' 카테고리의 다른 글
[Redis] 1장 Redis란? (0) | 2025.03.01 |
---|