微服务时代,有时候为了方便,经常在一台高配置服务器运行很多服务,这个时候CPU资源抢占就成了一个非常头痛的问题。闲时不会出现什么问题,比如一台16核服务器,当某一个时刻某个微服出现高并发访问时,此服务会抢占大量的CPU资源,从而影响了此服务器其他服务的正常访问,比如下图的情况:
docker容器在资源限制做的完善,kubernetes集群还可以通过资源使用率自动扩缩容,但是在非docker环境的时候,要实现CPU限制还是比较麻烦的,好在Linux有个命令可以做这样的事情,它就是cpulimit,安装也比较简单。今天阿汤博客就简单介绍一下cpulimit命令。
Ubuntu/Debian系统:
apt-get install cpulimit -y
RedHat/CentOS系统:(先安装好epel源)
yum install cpulimit -y
cpulimit使用也非常简单,看下帮助信息:
Usage: cpulimit [OPTIONS...] TARGET OPTIONS -l, --limit=N percentage of cpu allowed from 0 to 1600 (required) -v, --verbose show control statistics -z, --lazy exit if there is no target process, or if it dies -i, --include-children limit also the children processes -h, --help display this help and exit TARGET must be exactly one of these: -p, --pid=N pid of the process (implies -z) -e, --exe=FILE name of the executable program file or path name COMMAND [ARGS] run this command and limit it (implies -z)
主要说明下- l参数,单核cpu的使用率范围为0%-100%,4核CPU的使用率范围为0%-400%,16核CPU的使用率范围为0%-1600%,以此类推,此值是一个绝对值。
- e参数可以根据进程路径限制。
下面通过wrk压测工具,对cpulimit命令做一下测试。
首先限制为200%:
cpulimit -p 26546 -l 200
看下测试结果:
再限制为800%:
cpulimit -p 26546 -l 800
看下测试结果:
实际压测试过程中,该进程的CPU使用率可能会超过cpulimit的限制,但是不会超过太多,这是因为是cpu使用率在动态变动,cpulimit不能非常及时准确的调整,偶尔会超过一点限制。这也说明和docker的CPU限制有点区别。