文章目录
一、06.09 周五
1.1)Java的令牌桶实现
可以实现 RateLimiter
// 1秒 5个显示令牌桶
RateLimiter rateLimiter = RateLimiter.create(5);
while(true) {
double rate = rateLimiter.acquire(1);
log.info("运行中");
}
这样能保证1秒中只有 5次 "运行中"的输出
1.2)Java的线程池的依赖注入
- 定义 ThreadPoolExecutor的Bean
@Configure
public ThreadPoolExecutorConfig {
@Bean(name = "commonThreadPoolExecutor")
public ThreadPoolExecutor initCommonThreadPoolExecutor() {
ThreadFacutory threadFacutory = new ThreadFacutoryBuild.create().setNamePrefix("common-").build();
ThreadPoolExecutor threadPoolExecutory = new ThreadPoolExecutor(1, 1, 2, TimeUnit.SECONDS, new LinkedBlockingQueue(), threadFacutory);
return threadFacutory;
}
}
- 使用
@Autowired
ThreadPoolExecutor commonThreadPoolExecutor;
commonThreadPoolExecutor.executor(() -> {
log.info("运行中,当前线程: {}", Thread.currentThread.getThreadName());
})
1.3)轻量级实现定时运行
new Timer(true).schedule(new TimeTask() {
@Override
public void run() {
log.info("延迟10秒后,每10分钟运行一次");
}
}, 10000, 600000);
1.4)MDC日志 trace_id功能
- 使用 MDC的组件实现 log输出时添加上 trace_id
MDC.get()
MDC.put()
MDC.clear();
生成的随机数可以使用 RandomStringUtils.randomNumber()
来实现