背景:接到一个需求服务器的cpu利用率必须达到16%以上,不然会回收部分服务器资源。写一个程序消耗服务器cpu资源但要保持在16%不能太高也不能太低。
shell
脚本消耗cpu和内存。要么消耗1颗要么消耗2颗整数递增。感觉有点假。java
程序消耗cpu和内存。可以按照百分比消耗。可以以假乱真。
shell
消耗cpu脚本cpu.sh
#!/bin/bash
# Destription: test cpu usage
# Example : sh cpu_usage.sh consume 8 | sh cpu_usage.sh release
FILE_NAME=`basename $0`
cpunum=$2
pid_array=()
function usage()
{
echo "Usage:$FILE_NAME consume cpu_number|release -----the value of cpu_number is an integer,such as 1,2,3"
echo "Example: $FILE_NAME consume 12"
echo " $FILE_NAME release"
}
function endless_loop()
{
echo -ne "i=0;
while true
do
i=i+100;
i=100
done" | /bin/bash &
}
function consume()
{
for i in `seq $1`
do
endless_loop
pid_array[$i]=$!
done
echo "consume cpu resources process ids are: ${pid_array[*]}"
}
function release()
{
for pid in $(ps -ef |grep /bin/bash |grep -v grep |awk '{print $2}' |xargs)
do
kill -9 $pid
done
}
function main()
{
case "$1" in
consume) consume $cpunum;;
release) release;;
*) usage;exit 1;;
esac
}
main $*
使用之前使用命令先查询下cpu的个数cat /proc/cpuinfo | grep “processor”|wc -l
或 grep processor /proc/cpuinfo |wc -l
需要构造消耗2颗cpu的资源运行脚本sh cpu.sh consume 2
,此时运行top命令查看cpu的使用率。如果要释放cpu资源,运行sh cpu.sh release
即可释放cpu资源。
shell
消耗内存脚本memory.sh
#!/bin/bash
# Destription: testing memory usage
# Example : sh memory_usage.sh 500M | sh memory_usage.sh 1G | sh memory_usage.sh release
FILE_NAME=`basename $0`
memsize=$2
function usage()
{
echo "Usage:$FILE_NAME consume memory_size|release -----the value of memory_size like 100M 2G and etc"
echo "Example: $FILE_NAME consume 1G"
echo " $FILE_NAME release"
}
function consume()
{
if [ -d /tmp/memory ];then
echo "/tmp/memory already exists"
else
mkdir /tmp/memory
fi
mount -t tmpfs -o size=$1 tmpfs /tmp/memory
dd if=/dev/zero of=/tmp/memory/block
}
function release()
{
rm /tmp/memory/block;ret=$?
if [ $ret != 0 ]; then
echo "remove memory data failed"
return $ret
fi
umount /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "umount memory filedir failed"
return $ret
fi
rmdir /tmp/memory;ret=$?
if [ $ret != 0 ]; then
echo "remove memory filedir failed"
return $ret
fi
}
function main()
{
case "$1" in
consume) consume $memsize;;
release) release;;
*) usage;exit 1;;
esac
}
main $*
sh memory.sh consume 1G
即消耗1G的内存,sh memory.sh release
取消消耗内存。
至此shell脚本消耗内存和cpu的代码完成
java
消耗cpu和内存的脚本
package com.example.demo.cpu;
import java.util.Vector;
/**
* CPU 内存 控制
*
* @author smy
*/
public class JavaListener {
public static final double TIME = 1000;
public static final double MB100 = 104857600;
public static void main(String[] args) {
if (args == null || args.length < 1) {
exit();
}
String rates = null, memory = null;
for (String param : args) {
if (param.startsWith("-c:")) {
param = param.substring(3, param.length());
if (param != null && param.length() > 0) {
rates = param;
}
}
if (param.startsWith("-m:")) {
param = param.substring(3, param.length());
if (param != null && param.length() > 0) {
memory = param;
}
}
}
if ((rates == null || rates.length() < 1) && (memory == null || memory.length() < 1)) {
exit();
}
if (rates != null && rates.length() > 0) {
final String[] rateArr = rates.split(",");
for (String rate : rateArr) {
new Thread(new Runnable() {
@Override
public void run() {
double r = Double.valueOf(rate) / 100;
lineGraph(r);
}
}).start();
}
}
if (memory != null && memory.length() > 0) {
Integer finalMemory = Integer.valueOf(memory);
new Thread(new Runnable() {
@Override
public void run() {
memory(finalMemory);
}
}).start();
}
}
private static void exit() {
System.out.println("Please enter parameters");
System.out.println("such as: java xxxxx -c:80,40 -m:600");
System.out.println("-C represents the control core, and - m represents the control memory");
System.out.println("-c: 80 and 40 represent two cores, with utilization rates of 80% and 40% respectively");
System.out.println("-m: 600 means about 600MB of memory (unit: megabyte)");
System.exit(0);
}
private static double random() {
return (7 + Math.random() * (3)) / 10;
}
@SuppressWarnings("unchecked")
private static void memory(int mb) {
@SuppressWarnings("rawtypes")
Vector v = new Vector();
for (int i = 0; i < ((int) mb / 100); i++) {
int size = (int) (MB100 * random());
byte b1[] = new byte[size]; // 100M
v.add(b1);
}
while (true) {
try {
Thread.sleep(1000);
System.gc();
} catch (InterruptedException e) {
e.printStackTrace();
}
if (v.size() > 0) {
v.remove(0);
int size = (int) (MB100 * random());
byte b1[] = new byte[size]; // 100M
v.add(b1);
}
}
}
private static void lineGraph(double rate) {
while (true) {
doSomeSimpleWork(rate * TIME);
try {
long sleep = (long) (TIME - rate * TIME);
if (sleep < 1) {
sleep = 1L;
}
Thread.sleep(sleep);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private static void doSomeSimpleWork(double time) {
long startTime = System.currentTimeMillis();
while ((System.currentTimeMillis() - startTime) < time) {
// do nothing
}
}
}
编译注意包名,javac JavaListener.java -d .
生成class文件。启动(只占用其中两核心,分别占用60%、60%;占用50兆内存左右)java com.example.demo.cpu.JavaListener-c:60,60 -m:50 &
这里注意com.example.demo.cpu
是class文件的包名,也就是java文件的package
目录必须要加,否则报错找不到主类。
添加到服务器crontab
中定时执行
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)
# | .------------- hour (0 - 23)
# | | .---------- day of month (1 - 31)
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# | | | | |
# * * * * * user-name command to be executed
#30分钟一次执行脚本
*/30 * * * * root sh /repo/hict-cpu/start.sh
启动脚本在/repo/hict-cpu/
下创建vi start.sh
#!/bin/bash
source /etc/profile
SERVICE_NAME=com.example.demo.cpu.JavaListener
echo ">>> kill -9 $(jps -ml | grep $SERVICE_NAME | awk '{print $1}')"
kill -9 $(jps -ml | grep $SERVICE_NAME | awk '{print $1}')
#一定要加否则找不到这个目录
cd /repo/hict-cpu/
java $SERVICE_NAME -c:60,60 -m:50 &
至此java消耗服务器cpu和内存的脚本完成