(수근수근)

Node.js에서 redis사용하기 본문

web

Node.js에서 redis사용하기

InformationFarm 2021. 8. 25. 17:31

Redis(Remote Dictionary server)?

레디스는 NOSQL데이터베이스의 일종으로 비관계형 데이터베이스이다.

Redis는 key-value의 형태로 데이터를 저장하며, 메모리기반의 저장방식이라는 것이 큰 특징이다.

  • 메모리 기반의 'key-value' 구조관리 시스템
  • 메모리에 저장하고 조회하기 때문에 read-write가 속도빠름
    → MySql보다 10배정도 입력삭제가 빠르다.
  • 스냅샷기능을 제공하여 .rdb파일로 저장하여 해당시점의 데이터를 저장할 수 있다.

node.js에 Redis 설치하기

node.js와 redis 설치하기는 되어있다고 가정한다.
  1. 커멘드 창에 설치명령어 입력

→ npm i redis
2. 모듈 불러오기 코드 작성

const redis = require('redis');
const client = redis.createClient();

3.  redis-server 실행 후 데이터 조작


데이터 조작하기

위에 과정까지 완료했으면 이제 node.js를 활용하여 redis에 데이터를 조작해보자!

🔶 REDIS의 자료구조

  • String
    • 가장 기본적인 형태 key-value 로 저장된다
client.set('key','value');
client.get('key')
  • Set
    • 순서가 없는 문자열의 모임
    • 유일한 요소만 저장
client.sadd('student','주하');
client.sadd('student','민하');
client.sadd('student','주하'); // 저장X

client.smembers('student', 
    function(err,data){
        console.log(data);
    }
)
  • Sorted Set
    • 정렬된 set으로 생각하면 된다.
  • List
    • 리스트는 중복값허용 순서저장
    • 메모리가 허용하는 한 많은 데이터 저장가능
clinet.lpush('className', 'node.js')
clinet.lpush('className', 'redis')
//lrange(리스트, 시작인자, 종료인자)
clinet.lrange('className', 0, -1, 
    function(err, items){
            //item에 관련한 기능 수행
}) //모두다
  • Hashes
    • 헤시테이블 안에 키와 벨류값으로 데이터를 조작이 가능하다.
    • hset : 해시테이블에 key로 식별되는 value 값들을 항목으로 추가. 단, hmset은 여러 개를 입력할 수 있지만 hset은 하나만 가능.
    • hget : 해당 해시테이블에서, 인자로 받는 항목의 값을 가져옴. 첫 번째 인자(해시테이블명), 두 번째 인자(항목), 세 번째 인자 함수(첫 번째 인자(에러), 두 번째 인자(항목값))
    • hkeys: 해당 해시테이블의 저장된 항목의 키값을 가져옴. 첫 번째 인자(해시테이블명), 두 번째 인자(함수(첫 번째 인자(에러), 두 번째 인자(항목의 키들))
client.hmset('student',{
    '주하' : '6살',
    '민하' : '5살'
})

client.hset('student','세하','1살');

client.hget('student','주하', function(err, value){
    if(err) throw err;
    console.log(value);
})

client.hkeys('student', function(err, keys){
    if(err) throw err;
    keys.foreach(function(key, i){
        console.log(`student name is {key} `)
    })
})

심화 ) 파일을 읽어서 Redis에 저장

  • ini파일을 불러서 redis DB에 저장하려고 한다.
  • ini파일을 아래의 형태를 하고 있다. caption key value

 

👨🏿‍💻 완성 코드

const redis = require("redis");
const fs = require("fs");
const readline =  require('readline');
const client = redis.createClient(6379,"127.0.0.1");

client.on("error",(err) =>{
  console.error(err);
});

client.on("ready", ()=>{
  console.log("redis is ready");
});

function setData(hstable, key, value){
  console.log(hstable+' key,  '+key +",value : "+value);
  client.hset(hstable, key, value);
}

function readConfig(filepath, encodingType){ 
  let instream = fs.createReadStream(filepath);
  let reader =  readline.createInterface(instream, process.stdout);
  let tableName ='';

  reader.on('line', function(line){
    if(line.indexOf('caption1')>0) {
        tableName ='ENCRYPT';
    }

    if(line.indexOf('student')>0){
      tableName ='KERNEL';
    }

    if(line && line.indexOf('=')>0){
      const pair = line.split('=');
      setData(tableName, pair[0], pair[1]);
    }  

  });

  reader.on('close', function(line) {
    console.log('파일을 모두 읽음.');
  });

} 

var filename = 'D:\\개인\\text.ini';
readConfig(filename,'utf-8');

👊🏽 실행 결과

'web' 카테고리의 다른 글

react Build 및 실행하기  (0) 2021.12.21
브라우저 저장소(Web Storage)  (0) 2021.11.19
CSS Basic  (0) 2021.07.04
Service worker  (0) 2020.06.24
Web APP Manifest  (0) 2020.06.22
Comments