백엔드 개발 PHP 튜토리얼 nginx+루아+레디스

nginx+루아+레디스

Aug 08, 2016 am 09:19 AM
request requests time

최근에는 nginx+lua+redis를 사용하여 높은 동시성 및 트래픽이 많은 애플리케이션을 지원하는 시스템을 구축하고 있습니다. 개발 중에 문득 golang도 같은 효과를 낼 수 있지 않을까 하는 생각이 들었습니다. 그래서 비교를 위해 간단한 코드를 작성했습니다. 자세히 설명하지는 않겠습니다. nginx+lua+redis를 사용하여 동시성 높은 애플리케이션을 구축하는 방법에 대한 소개는 인터넷에 많이 있습니다. 저는 openresty+lua+redis를 사용하고 있습니다. 테스트 결과를 먼저 게시하세요. 기기는 2013년에 출시된 새로운 로우 프로파일 air입니다. - (1.3 GHz Intel Core i5, 4 GB 1600 MHz DDR3), 명령: ab -n 1000 -c 100 http://localhost:8880/openresty+lua+redis: Concurrency Level: 100 Time taken for tests: 0.458 seconds Complete requests: 1000 Failed requests: 0 Total transferred: 689000 bytes HTML transferred: 533000 bytes Requests per second: 2183.67 [#/sec] (mean) Time per request: 45.794 [ms] (mean) Time per request: 0.458 [ms] (mean, across all concurrent requests) Transfer rate: 1469.29 [Kbytes/sec] received golang+redis: Concurrency Level: 100 Time taken for tests: 0.503 seconds Complete requests: 1000 Failed requests: 0 Total transferred: 650000 bytes HTML transferred: 532000 bytes Requests per second: 1988.22 [#/sec] (mean) Time per request: 50.296 [ms] (mean) Time per request: 0.503 [ms] (mean, across all concurrent requests) Transfer rate: 1262.05 [Kbytes/sec] received lua 코드: -- redis 配置localparams={host='127.0.0.1',port=6379,}localred=redis:new()localok,err=red:connect(params.host,params.port)ifnotokthenngx.say("failed to connect: ",err)returnendlocalposition_key=ngx.var.position_keylocalcontent=red:get(position_key)ngx.print(content)golang 코드: packagemainimport("fmt""github.com/garyburd/redigo/redis""log""net/http""time")funcgetConn()(redis.Conn,error){conn,err:=redis.DialTimeout("tcp",":6379",0,1*time.Second,1*time.Second)iferr!=nil{fmt.Println(err)}returnconn,err}funcindexHandler(whttp.ResponseWriter,r*http.Request){conn,err:=getConn()iferr!=nil{http.Error(w,err.Error(),http.StatusInternalServerError)return}result,err:=conn.Do("get","content_1")iferr!=nil{http.Error(w,err.Error(),http.StatusInternalServerError)return}fmt.Fprintf(w,"Hello, %q",result)}funcmain(){http.HandleFunc("/",indexHandler)err:=http.ListenAndServe(":8880",nil)iferr!=nil{log.Fatal("ListenAndServe: ",err.Error())}} 이후 다수 번 스트레스 테스트를 거친 후 우리는 nginx + lua + redis의 조합이 실제로 효율적이며 golang + redis의 솔루션도 크게 다르지 않다는 것을 발견했습니다. 전체 시스템을 개발하여 배포하는 방식과 비교하면 golang이 개발 습관에 더 적합하고 더 적합할 수 있습니다. 결국 nginx + lua의 개발 및 테스트는 약간 어색합니다. Connection Pool 보충 사용법 및 테스트 결과

마지막 테스트를 마치고 이 코드에 개선의 여지가 있다고 느껴서 golang에서 Redis Connection Pool을 어떻게 사용하는지 확인해 봤습니다. (실제로는 redigo를 사용하는 방법입니다.) Lua에서 redis 연결 풀을 사용하는 방법은 (실제로는 Rest.redis를 사용하는 방법입니다.)

먼저 결과로 이동:

openresty + lua + redis Concurrency Level: 100 Time taken for tests: 0.284 seconds Complete requests: 1000 Failed requests: 0 Total transferred: 687000 bytes HTML transferred: 531000 bytes Requests per second: 3522.03 [#/sec] (mean) Time per request: 28.393 [ms] (mean) Time per request: 0.284 [ms] (mean, across all concurrent requests) Transfer rate: 2362.93 [Kbytes/sec] received

그런 다음 golang을 살펴보세요.

golang + redis Concurrency Level: 100 Time taken for tests: 0.327 seconds Complete requests: 1000 Failed requests: 0 Total transferred: 650000 bytes HTML transferred: 532000 bytes Requests per second: 3058.52 [#/sec] (mean) Time per request: 32.696 [ms] (mean) Time per request: 0.327 [ms] (mean, across all concurrent requests) Transfer rate: 1941.44 [Kbytes/sec] received

lua 코드:

-- redis 配置localparams={host='127.0.0.1',port=6379,}localred=redis:new()localok,err=red:connect(params.host,params.port)ifnotokthenngx.say("failed to connect: ",err)returnendlocalposition_key=ngx.var.position_keylocalcontent=red:get(position_key)ngx.print(content)localok,err=red:set_keepalive(10000,100)ifnotokthenngx.say("failed to set keepalive: ",err)returnend

golang 코드:

packagemainimport("flag""fmt""github.com/garyburd/redigo/redis""log""net/http""runtime""time")var(pool*redis.PoolredisServer=flag.String("redisServer",":6379",""))funcindexHandler(whttp.ResponseWriter,r*http.Request){t0:=time.Now()conn:=pool.Get()t1:=time.Now()fmt.Printf("The call took %v to run.\n",t1.Sub(t0))deferconn.Close()result,err:=conn.Do("get","content_1")iferr!=nil{http.Error(w,err.Error(),http.StatusInternalServerError)return}fmt.Fprintf(w,"Hello, %q",result)}funcnewPool(serverstring)*redis.Pool{return&redis.Pool{MaxIdle:3,IdleTimeout:240*time.Second,Dial:func()(redis.Conn,error){c,err:=redis.Dial("tcp",server)iferr!=nil{returnnil,err}returnc,err},TestOnBorrow:func(credis.Conn,ttime.Time)error{_,err:=c.Do("PING")returnerr},}}funcmain(){runtime.GOMAXPROCS(runtime.NumCPU())flag.Parse()pool=newPool(*redisServer)http.HandleFunc("/",indexHandler)err:=http.ListenAndServe(":8880",nil)iferr!=nil{log.Fatal("ListenAndServe: ",err.Error())}}

golang은 스레드 풀을 추가하는 것 외에도 CPU 코어 수도 설정합니다.

그러나 이 테스트는 그다지 엄격하지 않습니다. Redis, nginx, golang http 서버 및 ab 스트레스 테스트는 모두 동일한 시스템에 있으며 서로 영향을 미칩니다. 관심이 있는 경우 별도로 배포하고 테스트할 수 있습니다.

위에서는 nginx+lua+redis에 대한 내용을 소개했으며, PHP 튜토리얼에 관심이 있는 친구들에게 도움이 되기를 바랍니다.

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python에서 CURL과 Python 요청 간의 상호 변환을 실현하는 방법 Python에서 CURL과 Python 요청 간의 상호 변환을 실현하는 방법 May 03, 2023 pm 12:49 PM

컬과 Pythonrequests는 모두 HTTP 요청을 보내는 강력한 도구입니다. 컬은 터미널에서 직접 요청을 보낼 수 있는 명령줄 도구인 반면, Python의 요청 라이브러리는 Python 코드에서 요청을 보내는 보다 프로그래밍적인 방법을 제공합니다. 컬을 Pythonrequestscurl 명령으로 변환하는 기본 구문은 다음과 같습니다. 컬[OPTIONS]URL 컬 명령을 Python 요청으로 변환할 때 옵션과 URL을 Python 코드로 변환해야 합니다. 다음은 컬POST 명령의 예입니다: 컬-XPOST https://example.com/api

Python 크롤러 요청 라이브러리를 사용하는 방법 Python 크롤러 요청 라이브러리를 사용하는 방법 May 16, 2023 am 11:46 AM

1. 요청 라이브러리를 설치합니다. 학습 과정에서는 Python 언어를 사용하기 때문에 Python 3.8을 미리 설치해야 합니다. Python --version 명령을 실행하여 설치한 Python 버전을 확인할 수 있습니다. Python 3.X 이상을 설치하려면 Python을 설치한 후 다음 명령을 통해 요청 라이브러리를 직접 설치할 수 있습니다. pipinstallrequestsPs: Alibaba, Douban 등 국내 pip 소스로 전환할 수 있는데, 그 기능을 시연하기 위해 간단한 웹사이트를 시뮬레이션하기 위해 nginx를 사용했습니다. 다운로드 후 루트 디렉터리에서 nginx.exe 프로그램을 실행하면 됩니다.

PHP 요청은 무엇을 의미합니까? PHP 요청은 무엇을 의미합니까? Jul 07, 2021 pm 01:49 PM

요청의 중국어 의미는 "요청"입니다. PHP의 전역 변수이며 "$_POST", "$_GET" 및 "$_COOKIE"를 포함하는 배열입니다. "$_REQUEST" 변수는 POST 또는 GET으로 제출된 데이터 및 COOKIE 정보를 얻을 수 있습니다.

시간 패키지의 단조로운 시계 처리 시간 패키지의 단조로운 시계 처리 Aug 04, 2023 pm 05:45 PM

오늘은 golang time 패키지의 시간 적용 방법을 주로 살펴보겠습니다. 둘 사이의 일반적인 규칙은 "벽 시간"이 시간을 알려주는 데 사용되고 "단조 시계"가 시간을 측정하는 데 사용된다는 것입니다. 다른 시계 처리 방법이 있습니다.

Python 3.x에서 urllib.request.urlopen() 함수를 사용하여 GET 요청을 보내는 방법 Python 3.x에서 urllib.request.urlopen() 함수를 사용하여 GET 요청을 보내는 방법 Jul 30, 2023 am 11:28 AM

Python3.x에서 urllib.request.urlopen() 함수를 사용하여 GET 요청을 보내는 방법 네트워크 프로그래밍에서는 HTTP 요청을 보내 원격 서버에서 데이터를 가져와야 하는 경우가 많습니다. Python에서는 urllib 모듈의 urllib.request.urlopen() 함수를 사용하여 HTTP 요청을 보내고 서버에서 반환된 응답을 얻을 수 있습니다. 이 기사에서는 사용 방법을 소개합니다.

Python이 요청을 사용하여 웹 페이지를 요청하는 방법 Python이 요청을 사용하여 웹 페이지를 요청하는 방법 Apr 25, 2023 am 09:29 AM

요청은 urllib2의 모든 기능을 상속합니다. Requests는 HTTP 연결 지속성 및 연결 풀링을 지원하고, 쿠키를 사용하여 세션을 유지하도록 지원하고, 파일 업로드를 지원하고, 응답 콘텐츠의 인코딩 자동 결정을 지원하고, 국제화된 URL 및 POST 데이터의 자동 인코딩을 지원합니다. 설치 방법은 pip를 사용하여 설치 $pipinstallrequestsGET 요청 기본 GET 요청(헤더 매개 변수 및 parmas 매개 변수) 1. 가장 기본적인 GET 요청은 get 메서드 'response=requests.get("http://www.baidu.com/)을 직접 사용할 수 있습니다. &quot

Python 요청 게시물을 사용하는 방법 Python 요청 게시물을 사용하는 방법 Apr 29, 2023 pm 04:52 PM

Python은 게시물 요청을 보내는 브라우저를 시뮬레이션합니다. importrequests 형식 request.postrequest.post(url,data,json,kwargs)#post 요청 형식 request.get(url,params,kwargs)#get 요청과 비교하여 게시물 요청 보내기 매개변수는 다음과 같이 나뉩니다. form( x-www-form-urlencoded) json(application/json) 데이터 매개변수는 사전 형식과 문자열 형식을 지원합니다. 사전 형식은 json.dumps() 메서드를 사용하여 데이터를 합법적인 json 형식 문자열로 변환합니다.

Python의 요청 및 BeautifulSoup을 사용하여 PDF 파일 다운로드 Python의 요청 및 BeautifulSoup을 사용하여 PDF 파일 다운로드 Aug 30, 2023 pm 03:25 PM

Request 및 BeautifulSoup는 모든 파일이나 PDF를 온라인으로 다운로드할 수 있는 Python 라이브러리입니다. 요청 라이브러리는 HTTP 요청을 보내고 응답을 받는 데 사용됩니다. BeautifulSoup 라이브러리는 응답으로 수신된 HTML을 구문 분석하고 다운로드 가능한 PDF 링크를 얻는 데 사용됩니다. 이 기사에서는 Python에서 Request 및 BeautifulSoup을 사용하여 PDF를 다운로드하는 방법을 알아봅니다. 종속성 설치 Python에서 BeautifulSoup 및 Request 라이브러리를 사용하기 전에 pip 명령을 사용하여 시스템에 이러한 라이브러리를 설치해야 합니다. 요청과 BeautifulSoup 및 요청 라이브러리를 설치하려면,

See all articles