12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152 |
- package com.szwl.service.base;
- import lombok.extern.slf4j.Slf4j;
- import org.eclipse.paho.client.mqttv3.MqttClient;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.stereotype.Service;
- @Slf4j
- @Service
- public class MqttService {
- @Autowired
- private MqttClient mqttClient;
- /**
- * 发送消息
- * @param topic
- * @param message
- */
- public void sendMessage(String topic, String message, int qos) {
- try {
- mqttClient.publish(topic, message.getBytes(), qos, false);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 订阅主题
- * @param topic
- * @param qos
- */
- public void subscribe(String topic, int qos) {
- try {
- mqttClient.subscribe(topic, qos);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- /**
- * 取消订阅主题
- */
- public void unsubscribe(String topic) {
- try {
- mqttClient.unsubscribe(topic);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
|