第五章
Spring整合kafka
生产者:kafkaTemplate.send()
消费者:@KafkaListener(topic= {"test"})
生产者手动生产数据,消费者自动消费
public class KafkaTest { @Autowired private kafkaProducer kafkaProducer; @Test public void testKafka(){ kafkaProducer.sendMessage("test", "你好"); kafkaProducer.sendMessage("test", "在吗?"); try { Thread.sleep(1000*10); }catch (InterruptedException e){ e.printStackTrace(); } } } @Component class kafkaProducer{ @Autowired private KafkaTemplate kafkaTemplate; public void sendMessage(String topic, String content){ kafkaTemplate.send(topic,content); } } @Component class kafkaConsumer{ @KafkaListener(topics = {"test"}) public void handleMessage(ConsumerRecord record){ System.out.println(record.value()); } }
发送系统通知
触发事件:评论、点赞、关注
处理事件:封装事件对象、开发事件生产者、 消费者
@Component public class EventProducer { @Autowired private KafkaTemplate kafkaTemplate; //处理事件 public void fireEvent(Event event){ //将事件发布到主题 kafkaTemplate.send(event.getTopic(), JSONObject.toJSONString(event)); } }
@KafkaListener(topics = {TOPIC_COMMENT,TOPIC_LIKE,TOPIC_FOLLOW}) public void handleCommentMessage(ConsumerRecord record){ if (record == null && record.value() == null){ logger.error("消息内容不能为空"); return; } Event event = JSONObject.parseObject(record.value().toString(), Event.class); if (event == null){ logger.error("消息格式错误" ); return; } //发送站内通知 Message message = new Message(); message.setFromId(SYSTEM_USER_ID); message.setToId(event.getEntityUserId()); message.setConversationId(event.getTopic()); message.setCreateTime(new Date()); Map<String, Object> content = new HashMap<>(); content.put("userId", event.getUserId()); content.put("eventType", event.getEntityType()); content.put("entityId", event.getEntityId()); if (!event.getData().isEmpty()){ for (Map.Entry<String,Object> entry:event.getData().entrySet()){ content.put(entry.getKey(), entry.getValue()); } } message.setContent(JSONObject.toJSONString(content)); messageService.addMessage(message); }