Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。
在项目启动的时候立即执行某个方法:
我们可以通过实现ApplicationRunner和CommandLineRunner接口来实现,他们都是在SpringApplication执行之后开始执行的。
CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的。
这两种方式的实现都很简单,直接实现了相应的接口就可以了。记得在类上加@Component注解。
如果想要指定启动方法执行的顺序,可以通过实现org.springframework.core.Ordered接口或者使用org.springframework.core.annotation.Order注解来实现。
@Component
@Order(1)
public class ConsumeMqTask implements ApplicationRunner
{
/**
* 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ConsumeMqTask.class);
private ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(
1);
@Override
public void run(ApplicationArguments args)
throws Exception
{
LOGGER.info("start to run ConsumeMqTask.");
// 参数:1、任务体 2、首次执行的延时时间
// 3、任务执行间隔 4、间隔时间单位
scheduledExecutorService.scheduleAtFixedRate(new Runnable()
{
@Override
public void run()
{
consumeDataFromMq();
}
}, 0, 3, TimeUnit.SECONDS);
LOGGER.info("end to run ConsumeMqTask.");
}
/**
* <从rabbitmq中消费机场数据>
*
* @throws
*/
private void consumeDataFromMq()
{
LOGGER.info("[ConsumeMqTask] start to consumeDataFromMq.");
LOGGER.info("[ConsumeMqTask] end to consumeDataFromMq.");
}
}
@Component
public class Runner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
//此处为了记录一下线程的使用,没任何意义
new Thread(() -> {
try {
execute();
} catch (Exception e) {
e.printStackTrace();
}
}
).start();
}
private void execute() throws Exception {
System.out.println("hhahahahha");
}