初始化时吧所有的都用了

This commit is contained in:
Jerry Yan 2025-04-05 17:43:22 +08:00
parent cecc7aa181
commit c8874064f0
3 changed files with 32 additions and 3 deletions

View File

@ -0,0 +1,22 @@
package com.ycwl.basic.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
@Configuration
@EnableScheduling
public class SchedulerConfig {
@Bean
public ThreadPoolTaskScheduler taskScheduler() {
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
scheduler.setPoolSize(32); // 核心/最大线程数
scheduler.setAwaitTerminationSeconds(0); // 空闲线程存活时间
scheduler.setThreadNamePrefix("Scheduler-");
scheduler.setAwaitTerminationSeconds(60); // 等待任务终止的时间
scheduler.setRemoveOnCancelPolicy(true); // 取消任务后移除线程
return scheduler;
}
}

View File

@ -10,17 +10,18 @@ public class FixedRateLimiter implements IRateLimiter {
private final ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
public FixedRateLimiter(float maxRequestsPerSecond) {
int rate = Float.valueOf(1000000 / maxRequestsPerSecond).intValue();
semaphore.tryAcquire();
int rate = Float.valueOf(1000 / maxRequestsPerSecond).intValue();
scheduler.scheduleAtFixedRate(() -> {
if (semaphore.availablePermits() < 1) {
semaphore.release(1);
}
}, rate, rate, TimeUnit.NANOSECONDS);
}, rate, rate, TimeUnit.MILLISECONDS);
}
public FixedRateLimiter(int rate, TimeUnit timeUnit) {
// 启动一个线程每0.5秒释放一个许可
semaphore.tryAcquire();
scheduler.scheduleAtFixedRate(() -> {
if (semaphore.availablePermits() < 1) {
semaphore.release(1);

View File

@ -12,6 +12,9 @@ public class SlidingWindowRateLimiter implements IRateLimiter {
public SlidingWindowRateLimiter(int maxRequestsPerSecond) {
this.semaphore = new Semaphore(maxRequestsPerSecond);
for (int i = 0; i < maxRequestsPerSecond; i++) {
semaphore.tryAcquire();
}
scheduler.scheduleAtFixedRate(() -> {
if (semaphore.availablePermits() < maxRequestsPerSecond) {
semaphore.release(maxRequestsPerSecond - semaphore.availablePermits());
@ -21,6 +24,9 @@ public class SlidingWindowRateLimiter implements IRateLimiter {
public SlidingWindowRateLimiter(int maxRequests, int perSecond) {
this.semaphore = new Semaphore(maxRequests);
for (int i = 0; i < maxRequests; i++) {
semaphore.tryAcquire();
}
scheduler.scheduleAtFixedRate(() -> {
if (semaphore.availablePermits() < maxRequests) {
semaphore.release(maxRequests - semaphore.availablePermits());