使用spring事件机制,异步发送消息到kafka
步骤:
1、创建event
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class KafkaSendMsgEvent extends ApplicationEvent { private List dtoList; public KafkaSendMsgEvent(Object source, List dtoLists) { super(source); dtoList = dtoLists; } public List getDtoList() { return dtoList; } }
2、创建listener
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@Configuration @EnableAsync public class KafkaSndMsgListener { @Resource private Producer producer; private ObjectMapper mapper; @PostConstruct public void init() { mapper = new ObjectMapper(); } /** * 使用spring的事件机制,异步往kafka发送消息 * @param event */ @Async @EventListener public void kafkaSndMsgListener(KafkaSendMsgEvent event){ String message = getMessage(event.getDtoList()); producer.sendMsg(message); } private String getMessage(List<String> dto) { try { return mapper.writeValueAsString(dto); } catch (JsonProcessingException ex) { throw new OpcException(ex); } } }
3、发布spring事件
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
@RequestMapping("/") public void readImmData() { long startTime = System.nanoTime(); // 采集实时数据 List<String> dtoList = Lists.newArrayList(); dtoList.add("test-1"); dtoList.add("test-2"); dtoList.add("test-3"); // 使用spring事件机制,异步发送消息到kafka eventPublisher.publishEvent(new KafkaSendMsgEvent(this, dtoList)); log.info("读取数据耗时:{} 毫秒, 数据量:{}", Duration.ofNanos(System.nanoTime() - startTime).toMillis(), dtoList.size()); }
ref:https://blog.csdn.net/weixin_43770545/article/details/105971971