sean.zhou
2022-03-21 17835b967b48f2676cce3bbed081c6580602ee1c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.dji.sample.component.mqtt.service.impl;
 
import com.dji.sample.component.mqtt.model.CommonTopicResponse;
import com.dji.sample.component.mqtt.service.IMessageSenderService;
import com.dji.sample.component.mqtt.service.IMqttMessageGateway;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
/**
 * @author sean.zhou
 * @date 2021/11/16
 * @version 0.1
 */
@Service
@Slf4j
public class MessageSenderServiceImpl implements IMessageSenderService {
 
    @Autowired
    private IMqttMessageGateway messageGateway;
 
    public void publish(String topic, CommonTopicResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            // Only parameters whose value is not null will be serialised.
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
 
            messageGateway.publish(topic, mapper.writeValueAsBytes(response));
        } catch (JsonProcessingException e) {
            log.info("Failed to publish the message. {}", response.toString());
            e.printStackTrace();
        }
    }
 
    public void publish(String topic, int qos, CommonTopicResponse response) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            // Only parameters whose value is not null will be serialised.
            mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
 
            messageGateway.publish(topic, mapper.writeValueAsBytes(response), qos);
        } catch (JsonProcessingException e) {
            log.info("Failed to publish the message. {}", response.toString());
            e.printStackTrace();
        }
    }
}