定时任务&Cron表达式
spring boot整合定时任务和异步任务
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
/**
* @description:
* 定时任务
* 1. @EnableScheduling 开始定时任务
* 2. @Scheduled 开启一个定时任务
* 3. 自动配置类:TaskSchedulingAutoConfiguration
*
* 异步任务:
* 1、@EnableAsync 开启异步任务功能
* 2、@Async 给希望异步执行的方法上标注
* 3、自动配置类:TaskExecutionAutoConfiguration
*
* @author: wei-xhh
* @create: 2020-08-01
*/
@Slf4j
@Component
//@EnableAsync
//@EnableScheduling
public class HelloSchedule {
/**
* 1、spring中6位组成,不允许第7位的年
* 2、在周几的位置,1-7代表周一到周日 MON-SUN
* 3、定时任务不应该阻塞。默认是阻塞的
* 1、可以让业务运行以异步的方式,自己提交到线程池
* 2、支持定时任务线程池,设置TaskSchedulingProperties
* spring.task.scheduling.pool.size=5
* 3、让定时任务异步执行
* 异步任务;
* 解决:异步+定时任务来完成定时任务不阻塞的功能
*/
// @Async
// @Scheduled(cron = "* * * ? * 6")
// public void hello() throws InterruptedException {
// log.info("hello...");
// Thread.sleep(3000);
// }
}
库存预热,引入缓存,将秒杀商品放入redis,直接扣除缓存中的信号量
提升吞吐量之一就是保障每个方法快速执行
采用动静分离可以流量分担开,一定程度保证了后台服务的安全
恶意请求拦截中的登录拦截也可以保证方法快速执行
队列削峰机制使得秒杀成功就给订单的消息队列发送一个消息,后台订单服务慢慢消费消息
以上方法都是为了高并发的快
通过限流/熔断/降级来保证分布式系统的稳,通过Sentinel实现
限流:对打入服务的请求流量进行控制,使服务能够承担不超过自己能力的流量
Sentinel的简单使用
一、Sentinel-整合SpringBoot
1、导入依赖
2、下载sentinel的控制台
3、配置控制台的地址信息
4、在控制台调整参数【默认所有流控设置保存在内存中,重启失效】
二、每个微服务都导入审计模块
三、自定义流控返回数据
@Configuration
public class SeckillSentinelConfig {
public SeckillSentinelConfig(){
WebCallbackManager.setUrlBlockHandler(new UrlBlockHandler() {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
R error = R.error(BizCodeEnum.TO_MANY_REQUEST.getCode(), BizCodeEnum.TO_MANY_REQUEST.getErrorMessage());
httpServletResponse.setCharacterEncoding("UTF-8");
httpServletResponse.setContentType("application/json");
httpServletResponse.getWriter().write(JSON.toJSONString(error));
}
});
}
}