java服务器作为mqtt客户端和服务端实现消息的订阅和发布

1.首先导入pom依赖文件


  
   org.springframework.integration
   spring-integration-core
   4.3.9.RELEASE
  
  
   org.springframework.integration
   spring-integration-mqtt
   4.3.9.RELEASE
  
  
   org.eclipse.paho
   org.eclipse.paho.client.mqttv3
   1.2.0
  

2.我用的xml配置客户端和服务端spring-mqtt.xml



 
  
  
  
  
  
   
    
    tcp://10.130.33.33:1883
   
  
 
 
 
  
  
  
  
 
 
 
 
 
 
 

3.服务端发送消息代码

@Component
public class TestController {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Autowired
 private MqttPahoMessageHandler mqttHandler;
 @RequestMapping("sendMessage")
 public void sendMessage() {
  JSONObject messageJSON = new JSONObject();
  messageJSON.put("flag", true);
  messageJSON.put("code", "1");
  String message = JSONObject.toJSONString(messageJSON);
  logger.info("mqtt发送消息开始:{}", message);
  Message messages = MessageBuilder.withPayload(message)
    .setHeader(MqttHeaders.TOPIC, "infrared/testSend" + ).build();
  logger.info("消息构建:" + messages);
  // 发送消息
  mqttHandler.handleMessage(messages);
  logger.info("mqtt发送消息结束");
 }
 }

4.现在可以使用桌面客户端接收服务器发送的数据了(org.eclipse.paho.ui.app-1.1.1-win32.win32.x86)我使用的这个工具
5.下面是java服务器作为客户端订阅消息的xml配置,服务器订阅所有topic/的主题,#代表所有子集,+代表平级,消息处理类com.mqtt.client.MqttService,调用方法startCase

 
 
 
 
 
 

6.java消息处理代码获取主题和消息内容

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.messaging.Message;
public class MqttService {
 private Logger logger = LoggerFactory.getLogger(this.getClass());
 public void startCase(Message m) {
  String topic = m.getHeaders().get("mqtt_topic").toString();
  String payload = m.getPayload().toString();
  logger.info("MQTT Client=======================");
  logger.info("accept Topic:{}====>>>>payload:{}", topic,payload);
 }
}

你可能感兴趣的:(java开发工程师)