PageRenderTime 43ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://gitlab.com/Mr.Tomato/linbox_server
Java | 67 lines | 52 code | 12 blank | 3 comment | 6 complexity | f8595dc33db388504d481f36dd608956 MD5 | raw file
  1. package com.linbox.im.server.router.handlers.dispatcher;
  2. import com.alibaba.fastjson.JSON;
  3. import com.linbox.im.exceptions.IMConsumerException;
  4. import com.linbox.im.exceptions.IMException;
  5. import com.linbox.im.message.MessageType;
  6. import com.linbox.im.message.Message;
  7. import com.linbox.im.server.router.handlers.Handler;
  8. import com.linbox.im.server.storage.dao.IGroupDAO;
  9. import org.apache.kafka.clients.consumer.ConsumerRecord;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.beans.factory.annotation.Qualifier;
  14. import org.springframework.stereotype.Service;
  15. import java.util.List;
  16. import java.util.concurrent.ExecutorService;
  17. import java.util.concurrent.Executors;
  18. /**
  19. * Created by lrsec on 8/26/15.
  20. */
  21. @Service
  22. @Qualifier("dispatchToGroupHandler")
  23. public class DispatchToGroupHandler implements Handler<String, String> {
  24. private static final Logger logger = LoggerFactory.getLogger(DispatchToGroupHandler.class);
  25. private final ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
  26. @Autowired
  27. private IGroupDAO groupDAO;
  28. @Autowired
  29. private SendDispatcher dispatcher;
  30. @Override
  31. public void handle(ConsumerRecord<String, String> record) {
  32. String json = record.value();
  33. try {
  34. final Message groupMessage = JSON.parseObject(json, Message.class);
  35. if (groupMessage == null) {
  36. throw new IMException("Message could not be parsed correctly. Message: " + json);
  37. }
  38. final String groupId = groupMessage.groupId;
  39. List<String> members = groupDAO.getGroupMembers(groupId);
  40. for(final String userId : members) {
  41. if(userId == null || userId.equalsIgnoreCase(groupMessage.fromUserId)) {
  42. continue;
  43. }
  44. service.submit(new Runnable() {
  45. @Override
  46. public void run() {
  47. dispatcher.dispatchToSingle(userId, groupId, groupId, MessageType.Group, groupMessage);
  48. }
  49. });
  50. }
  51. } catch (Exception e) {
  52. throw new IMConsumerException(e, json);
  53. }
  54. }
  55. }