wuzeyu
2024-11-27 e2c28bc98587c6edd6a38f06b972ff51d998028f
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
51
52
53
54
55
56
57
58
59
60
61
62
package com.dy.pipIrrApp.workOrder.mqtt;
 
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author ZhuBaoMin
 * @date 2024-11-16 11:32
 * @LastEditTime 2024-11-16 11:32
 * @Description
 */
 
@Slf4j
@RestController
@RequestMapping(path = "mqtt")
public class TestController {
 
    @Value("${mqtt.broker}")
    private String broker;
 
    @Value("${mqtt.username}")
    private String username;
 
    @Value("${mqtt.password}")
    private String password;
 
    @Value("${mqtt.topic}")
    private String topic;
 
    @Value("${mqtt.qos}")
    private Integer qos;
 
    @GetMapping("/mqtt/{msg}")
    public String testSendMqttMsg(@PathVariable("msg") String msg){
        log.info("消息内容:{}.", msg);
 
        MqttClient mqttClient = MqttClientConnectorPool.connectMQTT(broker, username, password);
        MqttMsgSender sender = new MqttMsgSender();
 
        String content = "{" + " \"message\": \"" + msg + "\"," + " \"val\": 100.00" + "}";
 
        if (null != mqttClient){
            sender.sendMessage(mqttClient, topic, content, qos);
        } else {
            log.info("MqttClient为空,无法发送!");
            return "失败!";
        }
        return "成功!";
    }
 
    @GetMapping("/receive")
    public String receiveMsg() {
        MqttMsgSubscriber subscriber = new MqttMsgSubscriber();
        subscriber.readSubscribeTopicMessage();
        return "success";
    }
}