• Home
  • About
    • Lajancia Workspace photo

      Lajancia Workspace

      .

    • Learn More
    • Email
    • LinkedIn
    • Instagram
    • Tumblr
    • Github
  • Posts
    • All Posts
    • All Tags
  • Projects
  • Record
  • Blender
  • Blockchain

세션과 http

27 Oct 2021

Reading time ~2 minutes

세션, http/http2, 클러스터

2021-10-27


세션

쿠키 정보는 노출되고 수정되는 위험이 존재한다.

따라서 세션 쿠키를 통해 중요한 정보를 브라우저로 보내지 않도록 한다.

브라우저 → 서버: 세션 쿠키(의미를 알 수 없는 키를 통해 유저의 정보를 가져옴)

실제로는 이렇게 구현하지 않음. 실제 세션은 express session을 사용

http/http2

최근 대부분 https가 필수 → 자물쇠 아이콘이 나타남

실무에서는 https를 꼭 사용하도록 하자.

#http
const http = require('http');

http.createServer((req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(8080, () => { // 서버 연결
    console.log('8080번 포트에서 서버 대기 중입니다!');
  });
#https
const https = require('https');
const fs = require('fs');

https.createServer({
  cert: fs.readFileSync('도메인 인증서 경로'),
  key: fs.readFileSync('도메인 비밀키 경로'),
  ca: [
    fs.readFileSync('상위 인증서 경로'),
    fs.readFileSync('상위 인증서 경로'),
  ],
}, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(443, () => {
    console.log('443번 포트에서 서버 대기 중입니다!');
  });
  • 인증 키를 통해 접근
  • 서버를 초기화할때는 sync를 써도 됨
  • cert를 사용하지 않고 https를 사용하면, 인증 에러가 뜸

let’s encrypt에서 무료로 인증 가능

#http2
const http2 = require('http2');
const fs = require('fs');

http2.createSecureServer({
  cert: fs.readFileSync('도메인 인증서 경로'),
  key: fs.readFileSync('도메인 비밀키 경로'),
  ca: [
    fs.readFileSync('상위 인증서 경로'),
    fs.readFileSync('상위 인증서 경로'),
  ],
}, (req, res) => {
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
  res.write('<h1>Hello Node!</h1>');
  res.end('<p>Hello Server!</p>');
})
  .listen(443, () => {
    console.log('443번 포트에서 서버 대기 중입니다!');
  });
  • http1.1보다 훨씬 빠름
  • 동시성
  • 웹의 속도도 개선
  • 이미지 처리 속도 높음
  • http2와 https 두 개 다 사용하는게 좋음

개발할때는 http 사용하고 실무에서는 http2 사용하기

cluster

기본적으로 싱글 스레드인 노드가 CPU 코어를 모두 사용할 수 있게 해주는 모듈이다.

  • 8개 코어 돌린다고 성능이 8배가 되지는 않는다.
  • 프로세스를 여러개 만든다.
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;

if (cluster.isMaster) {
  console.log(`마스터 프로세스 아이디: ${process.pid}`);
  // CPU 개수만큼 워커를 생산
  for (let i = 0; i < numCPUs; i += 1) {
    cluster.fork();
  }
  // 워커가 종료되었을 때
  cluster.on('exit', (worker, code, signal) => {
    console.log(`${worker.process.pid}번 워커가 종료되었습니다.`);
    console.log('code', code, 'signal', signal);
    cluster.fork();#새로운 워커 프로세스가 생성. 에러로 인해 서버가 강제로 종료될 시에 다시 서버 실행
  });
} else {
  // 워커들이 포트에서 대기
  http.createServer((req, res) => {
    res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
    res.write('<h1>Hello Node!</h1>');
    res.end('<p>Hello Cluster!</p>');
    setTimeout(() => { // 워커 존재를 확인하기 위해 1초마다 강제 종료
      process.exit(1);
    }, 1000);
  }).listen(8086);

  console.log(`${process.pid}번 워커 실행`);
}
  • const numCPUs = require(‘os’).cpus().length;에서 cpu 개수 확인


backendsessionhttpnode.js Share Tweet +1