为了能到远方,脚下的每一步都不能少.|

园龄:粉丝:关注:

SpringBoot整合EMQ

1.引入依赖

<dependency>
<groupId>org.eclipse.paho</groupId>
<artifactId>org.eclipse.paho.client.mqttv3</artifactId>
<version>1.2.5</version>
</dependency>

2.发布消息到EMQ

(1)搭建基本的springBoot程序。

(2)编写controller,新增发布消息方法。

@GetMapping("/publish")
public void publish() throws MqttException {
MqttClientPersistence persistence = new MemoryPersistence();;//内存持久化
MqttClient client = new MqttClient("tcp://192.168.200.128:1883", "abc", persistence);
//连接选项中定义用户名密码和其它配置
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);//参数为true表示清除缓存,也就是非持久化订阅者,这个时候只要参数设为true,一定是非持久化订阅者。而参数设为false时,表示服务器保留客户端的连接记录
options.setAutomaticReconnect(true);//是否自动重连
options.setConnectionTimeout(30);//连接超时时间 秒
options.setKeepAliveInterval(10);//连接保持检查周期 秒
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); //版本
client.connect(options);//连接
client.publish("topic", "发送内容".getBytes(), 2, false);
}

3.订阅消息

在controller新增方法,订阅消息

@GetMapping("/subscribe")
public void subscribe() throws MqttException {
MqttClientPersistence persistence = new MemoryPersistence();;//内存持久化
MqttClient client = new MqttClient("tcp://192.168.200.128:1883", "abc", persistence);
//连接选项中定义用户名密码和其它配置
MqttConnectOptions options = new MqttConnectOptions();
options.setCleanSession(true);//参数为true表示清除缓存,也就是非持久化订阅者,这个时候只要参数设为true,一定是非持久化订阅者。而参数设为false时,表示服务器保留客户端的连接记录
options.setAutomaticReconnect(true);//是否自动重连
options.setConnectionTimeout(30);//连接超时时间 秒
options.setKeepAliveInterval(10);//连接保持检查周期 秒
options.setMqttVersion(MqttConnectOptions.MQTT_VERSION_3_1_1); //版本
client.setCallback(new MqttCallbackExtended() {
@Override
public void connectionLost(Throwable throwable) {
System.out.println("连接丢失!");
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println( "接收到消息 topic:" +s+" id:"+mqttMessage.getId() +" message:"+ mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
}
@Override
public void connectComplete(boolean b, String s) {
System.out.println("连接成功!");
}
});
client.connect(options);//连接
client.subscribe("test"); //订阅主题
}

注:这里可以把发送消息、接收消息的方法封装为Bean来供其它微服务使用

本文作者:七友的二度浪漫

本文链接:https://www.cnblogs.com/sy2022/p/16637571.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   你会很厉害的  阅读(489)  评论(0编辑  收藏  举报
//雪花飘落效果
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起