在windows10环境下,springboot怎么用mqtt服务端发送json数据
时间: 2024-02-01 10:15:48 浏览: 77
在Windows10环境下,使用Spring Boot发送JSON数据可以按照以下步骤操作:
1. 添加依赖
在pom.xml文件中添加以下依赖:
```
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
<version>5.3.2.RELEASE</version>
</dependency>
```
2. 配置MQTT服务端
在application.properties中添加以下配置信息:
```
spring.mqtt.username=<your_username>
spring.mqtt.password=<your_password>
spring.mqtt.url=<mqtt_server_url>
spring.mqtt.defaultTopic=<default_topic>
```
3. 编写发送JSON数据的代码
```java
import org.springframework.integration.mqtt.support.MqttHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import com.fasterxml.jackson.databind.ObjectMapper;
@Service
public class MqttService {
private static final String CHARSET = "UTF-8";
private static final int QOS = 1;
private final String mqttUrl;
private final String username;
private final String password;
private final String defaultTopic;
public MqttService(
@Value("${spring.mqtt.url}") String mqttUrl,
@Value("${spring.mqtt.username}") String username,
@Value("${spring.mqtt.password}") String password,
@Value("${spring.mqtt.defaultTopic}") String defaultTopic) {
this.mqttUrl = mqttUrl;
this.username = username;
this.password = password;
this.defaultTopic = defaultTopic;
}
public void sendMessage(Object payload, String topic) {
String json = toJson(payload);
Message<String> message = MessageBuilder
.withPayload(json)
.setHeader(MqttHeaders.TOPIC, topic)
.setHeader(MqttHeaders.QOS, QOS)
.build();
send(message);
}
private void send(Message<String> message) {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName(username);
options.setPassword(password.toCharArray());
try {
MqttClient client = new MqttClient(mqttUrl, MqttClient.generateClientId(), new MemoryPersistence());
client.connect(options);
client.publish(message.getHeaders().get(MqttHeaders.TOPIC).toString(),
new MqttMessage(message.getPayload().getBytes(CHARSET)));
client.disconnect();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private String toJson(Object value) {
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.writeValueAsString(value);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
```
4. 在需要发送JSON数据的地方调用MqttService.sendMessage()方法
例如,在Controller中调用MqttService的sendMessage()方法:
```java
@RestController
public class MyController {
@Autowired
MqttService mqttService;
@PostMapping("/send")
public void send(@RequestBody MyData data) {
mqttService.sendMessage(data, "my/topic");
}
}
```
这样,就可以使用Spring Boot发送JSON数据到MQTT服务端了。
阅读全文