MqttService.java 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package com.szwl.service.base;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.eclipse.paho.client.mqttv3.MqttClient;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. @Slf4j
  7. @Service
  8. public class MqttService {
  9. @Autowired
  10. private MqttClient mqttClient;
  11. /**
  12. * 发送消息
  13. * @param topic
  14. * @param message
  15. */
  16. public void sendMessage(String topic, String message, int qos) {
  17. try {
  18. mqttClient.publish(topic, message.getBytes(), qos, false);
  19. } catch (Exception e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. /**
  24. * 订阅主题
  25. * @param topic
  26. * @param qos
  27. */
  28. public void subscribe(String topic, int qos) {
  29. try {
  30. mqttClient.subscribe(topic, qos);
  31. } catch (Exception e) {
  32. e.printStackTrace();
  33. }
  34. }
  35. /**
  36. * 取消订阅主题
  37. */
  38. public void unsubscribe(String topic) {
  39. try {
  40. mqttClient.unsubscribe(topic);
  41. } catch (Exception e) {
  42. e.printStackTrace();
  43. }
  44. }
  45. }