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