PageRenderTime 50ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/src/main/java/com/linbox/im/server/router/handlers/dispatcher/SendDispatcher.java

https://gitlab.com/Mr.Tomato/linbox_server
Java | 60 lines | 46 code | 9 blank | 5 comment | 4 complexity | 679fa4b58aa872962cc6d25f72fd1981 MD5 | raw file
  1. package com.linbox.im.server.router.handlers.dispatcher;
  2. import com.alibaba.fastjson.JSON;
  3. import com.linbox.im.exceptions.IMException;
  4. import com.linbox.im.message.MessageType;
  5. import com.linbox.im.message.Message;
  6. import com.linbox.im.server.constant.MessageTopic;
  7. import org.apache.kafka.clients.producer.KafkaProducer;
  8. import org.apache.kafka.clients.producer.ProducerRecord;
  9. import org.slf4j.Logger;
  10. import org.slf4j.LoggerFactory;
  11. import org.springframework.beans.factory.annotation.Autowired;
  12. import org.springframework.stereotype.Service;
  13. /**
  14. * Created by lrsec on 8/26/15.
  15. */
  16. @Service
  17. public class SendDispatcher {
  18. private static Logger logger = LoggerFactory.getLogger(SendDispatcher.class);
  19. @Autowired
  20. private KafkaProducer<String, String> kafkaProducer;
  21. // dispatch to single user
  22. public void dispatchToSingle(String userId, String remoteId, String sessionKey, MessageType type, Message msg) {
  23. try {
  24. SendDispatchMessage message = new SendDispatchMessage();
  25. message.setUserId(userId);
  26. message.setRemoteId(remoteId);
  27. message.setSessionKey(sessionKey);
  28. message.setMessage(msg);
  29. message.setType(type);
  30. String json = JSON.toJSONString(message);
  31. if (json == null) {
  32. throw new IMException("Message to user " + userId + "can not be parsed to json correctly.");
  33. }
  34. kafkaProducer.send(new ProducerRecord<String, String>(MessageTopic.TOPIC_DISPATCH_SEND_SINGLE, json));
  35. } catch (Exception e) {
  36. logger.error("Dispatch send message to single user " + userId + "fail.", e);
  37. }
  38. }
  39. //dispatch to group
  40. public void dispatchToGroup(String groupId, Message message) {
  41. try {
  42. String json = JSON.toJSONString(message);
  43. if (json == null) {
  44. throw new IMException("Message to group " + groupId + "can not be parsed to json correctly.");
  45. }
  46. kafkaProducer.send(new ProducerRecord<String, String>(MessageTopic.TOPIC_DISPATCH_SEND_GROUP, json));
  47. } catch (Exception e) {
  48. logger.error("Dispatch send message to group " + groupId + " fail.", e);
  49. }
  50. }
  51. }