프로젝트를 개발하고 서버 스펙 대비 얼마나 서비스를 운영할 수 있는지 예측이 필요했다.
pyhon으로 개발된 locust를 이용해 부하를 테스트해보기로 했다.
locust 설치
먼저 python3.8 이상이 설치된 환경에서 설치를 진행한다.
pip를 이용해 locust를 설치한다.
pip3 install -U --pre locust
코드작성
기본 예제
from locust import HttpUser, task
class HelloWorldUser(HttpUser):
@task
def hello_world(self):
self.client.get("/hello")
self.client.get("/world")
실행명령어
python locust -f 생성한파이썬파일
명령어 입력 후 다음과 같이 서버가 실행되는 것을 볼 수 있다
테스트
http://localhost:8089로 접속하면 UI를 이용해 부하를 테스트 할 수 있다.
Number of users : 총 접속 수
Spawn rate : 초당 접속 증가 수
Host : 접속할 host
Advanced options 토글을 이용해 열면 가동할 시간을 작성해서 이용할 수 있다.
본 글에서는 200명의 접속을 처음부터 200명이 2분간 접속하는 테스트하는 형태로 진행하였다.
Start swarming을 클릭해 테스트 시작
테스트를 시작하면 Startistics에서 적요를 확인할 수 있고 오른쪽 상단에 RPS와 현재 상태를 확인할 수 있다.
Chars 탭에서는 진행되는 테스트를 시각화를 통해 확인할 수 있다.
Failes와 Exceptions에서는 실패, 에러메세지에 대한 정보를 확인할 수 있다.
작업이 끝나면 Download Data에서 테스트 결과를 다운로드할 수 있는데 본 글에서는 Download Report 링크를 클릭해 현 대시보드형태로 저장하여 사용한다.
GET
from locust import HttpUser, TaskSet, task, between
import json
class WebsiteUser(HttpUser):
wait_time = between(3,4)
host = "http://IP:PORT"
@task(1)
def gether(self):
self.client.get("/PATH/")
POST with headers
from locust import HttpUser, TaskSet, task, between
import json
class WebsiteUser(HttpUser):
wait_time = between(3,4)
host = "http://IP:PORT"
@task(1)
def gether(self):
self.client.post("/PATH/",
json={
"Key": "value",
},
headers={"Authorization":"TOKEN"}
)