spring boot ApplicationRunner使用
它的使用比较简单,实现ApplicationRunner的run方法
package com.hikvision.pbg.jc.confuciussecurity.modules.task;
import com.hikvision.pbg.jc.confuciussecurity.modules.constant.Constant;
import com.hikvision.pbg.jc.confuciussecurity.modules.util.kafka.KafkaProducerPool;
import com.hikvision.pbg.jc.confuciussecurity.modules.util.kafka.StringUtil;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(1)
public class KafkaFaceProducerTest implements ApplicationRunner {
private static Logger logger = LoggerFactory.getLogger(KafkaFaceProducerTest.class);
Producer<String, String> producer = KafkaProducerPool.getInstance(Constant.KAFKA_ADDR);
public KafkaFaceProducerTest(){
}
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
while(true){
Thread.sleep(1000);
logger.info("kafka produce message");
try {
String str =String.valueOf(System.currentTimeMillis());
producer.send(new KeyedMessage<String, String>("JSON_TOPIC", StringUtil.getUUID(), str));
} catch (Exception e) {
e.printStackTrace();
}
}
//Thread.sleep(5000);
//Producer<String, String> producer = KafkaProducerPool.getInstance(Constant.KAFKA_ADDR);
}
}
它什么时候使用
一般我们spring boot 启动类这么写
public static void main(String[] args) {
System.out.println("begin1");
SpringApplication.run(XX.class, args);
System.out.println("begin2");
}
ApplicationRunner的使用就在SpringApplication.run,里面有一段这样的代码实现就是:先把ApplicationRunner list执行完,再接着执行SpringApplication.run方法。
如果想通过先把ApplicationRunner起一个task,如果死循环,就很危险!因为main方法也进入到了死循环的阶段
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
Iterator var4 = (new LinkedHashSet(runners)).iterator();
while(var4.hasNext()) {
Object runner = var4.next();
if (runner instanceof ApplicationRunner) {
this.callRunner((ApplicationRunner)runner, args);
}
if (runner instanceof CommandLineRunner) {
this.callRunner((CommandLineRunner)runner, args);
}
}
}