|
|
@@ -4,8 +4,8 @@ import cn.hutool.core.date.StopWatch; |
|
|
|
import cn.hutool.core.util.RandomUtil; |
|
|
|
import cn.hutool.system.oshi.OshiUtil; |
|
|
|
import lombok.extern.slf4j.Slf4j; |
|
|
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression; |
|
|
|
import org.springframework.context.annotation.Configuration; |
|
|
|
import org.springframework.context.annotation.Profile; |
|
|
|
import org.springframework.lang.NonNull; |
|
|
|
import org.springframework.scheduling.annotation.Scheduled; |
|
|
|
|
|
|
@@ -25,16 +25,21 @@ import java.util.stream.Stream; |
|
|
|
* @since 20:30 2024/3/5 |
|
|
|
*/ |
|
|
|
@Slf4j |
|
|
|
@Profile("prod") |
|
|
|
@Configuration |
|
|
|
@ConditionalOnExpression("${cpu-load-task.open:false}") |
|
|
|
public class CpuLoadTask { |
|
|
|
|
|
|
|
private static final int LIMIT_COUNT = 2000000000; |
|
|
|
private final AtomicInteger taskNo = new AtomicInteger(0); |
|
|
|
public CpuLoadTask() { |
|
|
|
CpuLoadThreadFactory threadFactory = new CpuLoadThreadFactory(Thread.MIN_PRIORITY); |
|
|
|
fixedThreadPool = Executors.newFixedThreadPool(1, threadFactory); |
|
|
|
} |
|
|
|
|
|
|
|
private final ExecutorService fixedThreadPool; |
|
|
|
|
|
|
|
private static final Integer CPU_LIMIT = 20; |
|
|
|
private static final int LIMIT_COUNT = 1000000000; |
|
|
|
private final AtomicInteger taskNo = new AtomicInteger(0); |
|
|
|
|
|
|
|
private static final ExecutorService FIXED_THREAD_POOL; |
|
|
|
|
|
|
|
private static class CpuLoadThreadFactory implements ThreadFactory { |
|
|
|
|
|
|
@@ -53,13 +58,6 @@ public class CpuLoadTask { |
|
|
|
|
|
|
|
} |
|
|
|
|
|
|
|
static { |
|
|
|
int logicalProcessorCount = OshiUtil.getProcessor().getLogicalProcessorCount(); |
|
|
|
int max = Math.max(logicalProcessorCount * CPU_LIMIT / 100, 1); |
|
|
|
CpuLoadThreadFactory threadFactory = new CpuLoadThreadFactory(Thread.MIN_PRIORITY); |
|
|
|
FIXED_THREAD_POOL = Executors.newFixedThreadPool(max, threadFactory); |
|
|
|
} |
|
|
|
|
|
|
|
|
|
|
|
@Scheduled(fixedRate = 1, timeUnit = TimeUnit.MINUTES) |
|
|
|
public void run() { |
|
|
@@ -67,7 +65,7 @@ public class CpuLoadTask { |
|
|
|
log.info("当前CPU使用率:{}", cpuUsage); |
|
|
|
if (cpuUsage < CPU_LIMIT) { |
|
|
|
log.info("提交计算任务:{}", taskNo.incrementAndGet()); |
|
|
|
FIXED_THREAD_POOL.execute(() -> { |
|
|
|
fixedThreadPool.execute(() -> { |
|
|
|
StopWatch watch = new StopWatch(); |
|
|
|
watch.start(); |
|
|
|
long sum = Stream.generate(() -> RandomUtil.randomLong(1, LIMIT_COUNT)) |
|
|
|