【发布时间】:2022-01-19 08:12:27
【问题描述】:
我有很少的 MongoTemplate 和 Repos,我需要在我的可运行类中使用 @Autowire 调用它们,该类正在由执行程序类使用多线程执行,现在的问题是当我运行应用程序时,我的 AutoWire for mongoTempelate 和 Repos 返回空指针异常。 执行者类:
@Component
public class MessageConsumer implements ConsumerSeekAware {
@Autowired
AlarmDataRepository alarmDataRepository;
int assignableCores = ((Runtime.getRuntime().availableProcessors()));
ExecutorService executor = Executors.newFixedThreadPool(
assignableCores > 1 ? assignableCores : 1
);
int counter = 0;
List<String> uniqueRecords = new ArrayList<String>();
@KafkaListener(topics = "teltonikaTest", groupId = "xyz")
public void processMessages(@Payload List<String> payload, @Header(KafkaHeaders.RECEIVED_PARTITION_ID) List<Integer> partitions, @Header(KafkaHeaders.OFFSET) List<Long> offsets) throws UnsupportedEncodingException, DecodeException {
System.out.println("assignable resources are: " + assignableCores);
log.info("Batch Size is: {}", payload.size());
if(counter==0){
log.info("Teletonica Packets Received!");
}
for (int i = 0; i < payload.size(); i++) {
log.info("processing message='{}' with partition off-set='{}'", payload.get(i), partitions.get(i) + " _" + offsets.get(i));
}
uniqueRecords = payload.stream().distinct().collect(Collectors.toList());
Runnable worker = new TeltonikaWorkerThread(uniqueRecords);
executor.execute(worker);
counter++;
}
}
public class TeltonikaWorkerThread implements Runnable{
List<String> records;
List<CurrentDevice> currentDevices = new ArrayList<>();
@Autowired
CurrentDeviceRepository currentDeviceRepository;
@Autowired
MongoTemplate mongoTemplate;
public TeltonikaWorkerThread(List<String> records) {
this.records = records;
}
public void run() {
try {
processMessage();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (DecodeException e) {
e.printStackTrace();
}
}
public void processMessage() throws UnsupportedEncodingException,DecodeException {
for(Object record : records){
if(record!="0"){
try{
int IMEILength = record.toString().indexOf("FF");
String IMEI = record.toString().substring(0,IMEILength);
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
}
【问题讨论】:
-
你应该提供一个可重现的例子
-
请发布您的代码和您尝试过的内容
-
添加代码第一类是我从kafka接收数据包并使其唯一的地方,然后我将唯一记录传递给TeltonikaWorker线程,然后在我想调用的ProcessMessage中定义的IMEI字符串之后从那里开始我的 repo 执行查询并获取 IMEI 上的记录,但不幸的是我无法自动连接我的 repo 并为此抛出 nullPointerException
标签: spring mongodb multithreading autowired runnable