<Executor name="tomcatThreadPool" namePrefix="tomcatThreadPool-" maxThreads="1000" maxIdleTime="300000" minSpareThreads="200"/>
<Connector executor="tomcatThreadPool" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" minProcessors="5" maxProcessors="75" acceptCount="1000"/>
/** * 自定義註解 限流 */ @Target({ElementType.PARAMETER, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ServiceLimit { String description() default ""; }
/** * 限流 AOP */ @Component @Scope @Aspect public class LimitAspect { //每秒只發出100個令牌,此處是單進程服務的限流,內部採用令牌捅算法實現 private static RateLimiter rateLimiter = RateLimiter.create(100.0); //Service層切點 限流 @Pointcut("@annotation(com.itstyle.seckill.common.aop.ServiceLimit)") public void ServiceAspect() { } @Around("ServiceAspect()") public Object around(ProceedingJoinPoint joinPoint) { Boolean flag = rateLimiter.tryAcquire(); Object obj = null; try { if(flag){ obj = joinPoint.proceed(); } } catch (Throwable e) { e.printStackTrace(); } return obj; } }
@Override @ServiceLimit @Transactional public Result startSeckil(long seckillId, long userId) { //省略部分業務代碼,詳見秒殺源碼 }
#統一在http域中進行配置 #限制請求 limit_req_zone $binary_remote_addr $uri zone=api_read:20m rate=50r/s; #按ip配置一個鏈接 zone limit_conn_zone $binary_remote_addr zone=perip_conn:10m; #按server配置一個鏈接 zone limit_conn_zone $server_name zone=perserver_conn:100m; server { listen 80; server_name seckill.52itstyle.com; index index.jsp; location / { #請求限流排隊經過 burst默認是0 limit_req zone=api_read burst=5; #鏈接數限制,每一個IP併發請求爲2 limit_conn perip_conn 2; #服務所限制的鏈接數(即限制了該server併發鏈接數量) limit_conn perserver_conn 1000; #鏈接限速 limit_rate 100k; proxy_pass http://seckill; } } upstream seckill { fair; server 172.16.1.120:8080 weight=1 max_fails=2 fail_timeout=30s; server 172.16.1.130:8080 weight=1 max_fails=2 fail_timeout=30s; }
# 安裝 yum -y install httpd-tools # 查看ab版本 ab -v # 查看幫助 ab --help 測試命令: ab -n 1000 -c 100 http://127.0.0.1/ 測試結果: Server Software: openresty/1.13.6.1 #服務器軟件 Server Hostname: 127.0.0.1 #IP Server Port: 80 #請求端口號 Document Path: / #文件路徑 Document Length: 12 bytes #頁面字節數 Concurrency Level: 100 #請求的併發數 Time taken for tests: 4.999 seconds #總訪問時間 Complete requests: 1000 #總請求樹 Failed requests: 0 #請求失敗數量 Write errors: 0 Total transferred: 140000 bytes #請求總數據大小 HTML transferred: 12000 bytes #html頁面實際總字節數 Requests per second: 200.06 [#/sec] (mean) #每秒多少請求,這個是很是重要的參數數值,服務器的吞吐量 Time per request: 499.857 [ms] (mean) #用戶平均請求等待時間 Time per request: 4.999 [ms] (mean, across all concurrent requests) # 服務器平均處理時間,也就是服務器吞吐量的倒數 Transfer rate: 27.35 [Kbytes/sec] received #每秒獲取的數據長度 Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.8 0 4 Processing: 5 474 89.1 500 501 Waiting: 2 474 89.2 500 501 Total: 9 475 88.4 500 501 Percentage of the requests served within a certain time (ms) 50% 500 66% 500 75% 500 80% 500 90% 501 95% 501 98% 501 99% 501 100% 501 (longest request)