---
title: "HTTP接入层限流"
author: "strongant"
date: "2018-12-13T20:58:09Z"
tags: []
categories: ["企业架构"]
slug: "http"
draft: false
lastmod: "2018-12-13T21:06:24Z"
id: 2435193
url: "https://strongant.iteye.com/blog/2435193"
---

http {
    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user  "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

        <span style="color:red">limit_req_status 509;
        limit_conn_status 509;
        limit_conn_zone  $server_addr zone=one:10m;  #按域来限流
        limit_req_zone  $server_addr  zone=req_one:10m rate=2r/s;</span>


server{

        <span style="color:red">limit_conn  one 2;
        limit_req   zone=req_one nodelay;</span>

        listen 22019;
        access_log /opt/nginx/logs/limit_access.log;
        location / {
                proxy_pass  http://www.baidu.com;

        }

        error_page   509  /509.html;
        location = /509.html {
           root   html;
        }

}

}

关键指令解析：
limit_req_status 指http被限流时的错误码，默认是503
limit_conn_status 指tcp被限流时的错误码，默认是503
limit_req，该指令对Http请求进行限流也就是限并发数，如果burst属性没配置表示不进行http请求缓冲，直接被限流返回
limit_conn，该指令限制tcp连接数，真正服务要不要请求HTTP请求是靠这个指令

准确的说，尽管你配置的limit_req并发数在多，服务真正能不能处理还是靠这个limit_conn配置的数字

比如：limit_req对应的配置是 100 rate/s，表示每秒允许的http请求并发数是100
limit_conn对应的配置是 10，表示服务每秒能同时处理10请求，也就是指这个服务的tps

用户可以无限的发送http请求，但是真正同时被处理的也就10个请求