系统上线之前需要做一系列的评估来确保系统稳定,Semphore非常适合高并发访问限制。
相关概念
PV(Page View):网站的总访问量,页面浏览量货点击量,用户每刷新一次就会被记录一次。
UV(Unique Visitor):访问网站的一台电脑客户端为一个访客。
QPS(Query Per Second):每秒查询数。
RT(Response Time):请求的响应时间。
容量评估:通过开发、运维、测试以及业务等相关人员,综合出系统的一系列域值,然后根据关键域值如qps、rt等,对系统进行有效的变更。
一般进行多次测试评估以后,可以对系统进行峰值评估。采用所谓的80/20原则,及80%的访问请求将在20%的时间内达到。这样就可以通过系统对应的PV计算出峰值qps。
峰值qps = (总PV * 80%) / (60 * 60 * 24 * 20%)
所需要机器的数量 = 总峰值qps / 压测得出的单机极限qps
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
public class SemaphoreTest {
public static void main(String[] args) {
//首先定义线程池最多线程数
ExecutorService executorService = Executors.newFixedThreadPool(20);
//初始化信号量并规定阀值,阀值的意思是最多有呢么多的线程并发执行
Semaphore semaphore = new Semaphore(5);
for(int i = 1;i <= 20;i++) {
final int index = i;
executorService.execute(new Runnable() {
@Override
public void run() {
try {
//许可此线程执行业务逻辑
semaphore.acquire();
System.err.println("当前运行的第 " + index + " 个线程,获得许可执行操作.. ");
//进行业务逻辑操作
long bsTime = (long)(Math.random() * 10000);
Thread.sleep(bsTime);
System.err.println("当前运行的第 " + index + " 个线程,执行业务逻辑时间为 " + bsTime + " 毫秒" );
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//释放许可
semaphore.release();
}
}
});
}
executorService.shutdown();
}
}
执行结果为:
结果显现,先有5个线程获取许可并发执行,然后才一个一个获取许可执行。