本篇记录一下MQTT客户端与Spring Mvc整合


  网络上已经有很多的MQTT客户端与SpringBoot整合的技术文档,但是与Spring Mvc框架的整合文档似乎并不太多,可能是因为SpringMvc框架已经逐渐被淘汰了。但很幸运,我这次JAVA后端项目就是用的SpringMvc,所以在整理了网上很多资料后,也为了方便其他后来人,把我这次的整合开发过程用文字记录一下。

POM引入依赖
  千万注意引入依赖的版本,一定要保持3个依赖的版本一致,不同的版本可能造成各种问题。
我在开发过程中碰到因为3个版本不一致,导致Class找不到的情况,所以对版本间区别不清楚的朋友们,就不要改版本。

<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-stream</artifactId>
<version>4.1.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-core</artifactId>
<version>4.1.0.RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
<version>4.1.0.RELEASE</version>
</dependency>

resource目录下添加mqtt.properties配置文件

#用户名
mqtt.username=mqttPubClient
#密码
mqtt.password=123456
#是否清除会话
mqtt.cleanSession=false
#服务端url
mqtt.serverURI1=tcp://127.0.0.1:1883 mqtt.async=true
#超时时间
mqtt.completionTimeout=20000
#心跳
mqtt.keepAliveInterval=30
#客户端id
mqtt.clientId=mqttPubClient
#默认的消息服务质量
mqtt.defaultQos=1
#MQTT-监听的主题
mqtt.topic=hello

写Spring Mqtt 的配置XML
在resource目录下添加spring-mqtt.xml,要确保这个XML能被Spring启动时加载进去。

 1 <?xml version="1.0" encoding="UTF-8"?>
2 <beans xmlns="http://www.springframework.org/schema/beans"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xmlns:int="http://www.springframework.org/schema/integration"
5 xmlns:context="http://www.springframework.org/schema/context"
6 xmlns:int-mqtt="http://www.springframework.org/schema/integration/mqtt"
7 xsi:schemaLocation="
8 http://www.springframework.org/schema/integration
9 http://www.springframework.org/schema/integration/spring-integration-4.1.xsd
10 http://www.springframework.org/schema/beans
11 http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
12 http://www.springframework.org/schema/integration/mqtt
13 http://www.springframework.org/schema/integration/mqtt/spring-integration-mqtt-4.1.xsd
14 http://www.springframework.org/schema/context
15 http://www.springframework.org/schema/context/spring-context-3.1.xsd ">
16
17 <context:property-placeholder location="classpath:mqtt.properties" ignore-unresolvable="true"/>
18
19 <!--MQTT配置-->
20 <bean id="clientFactory"
21 class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory">
22 <property name="userName" value="${mqtt.username}"/>
23 <property name="password" value="${mqtt.password}"/>
24 <property name="cleanSession" value="${mqtt.cleanSession}"/>
25 <property name="keepAliveInterval" value="${mqtt.keepAliveInterval}"/>
26 <property name="serverURIs">
27 <array>
28 <value>${mqtt.serverURI1}</value>
29 </array>
30 </property>
31 </bean>
32
33 <bean id="mqttHandler" class="org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler">
34 <constructor-arg name="clientId" value="${mqtt.clientId}"/>
35 <constructor-arg name="clientFactory" ref="clientFactory"/>
36 <property name="async" value="${mqtt.async}"/>
37 <property name="defaultQos" value="${mqtt.defaultQos}"/>
38 <property name="completionTimeout" value="${mqtt.completionTimeout}"/>
39 </bean>
40
41 <!-- 消息适配器 -->
42 <int-mqtt:message-driven-channel-adapter
43 id="mqttInbound" client-id="${mqtt.clientId}" url="${mqtt.serverURI1}"
44 topics="${mqtt.topic}" qos="${mqtt.defaultQos}" client-factory="clientFactory" auto-startup="true"
45 send-timeout="${mqtt.completionTimeout}" channel="startCase" />
46 <int:channel id="startCase" />
47 <!-- 消息处理类 -->
48 <int:service-activator id="handlerService"
49 input-channel="startCase" ref="mqttCaseService" method="handler" />
50
51 <!-- 消息处理 -->
52 <bean id="mqttCaseService" class="com.loong.mqtt.service.impl.MqttServiceImpl" />
53
54 </beans>

MQTT Service 接口

1 public interface MqttService {
2
3 public void send(String topic,String content) throws Exception;
4
5 public void handler(String message) throws Exception;
6 }

MQTT Service 实现

 1 import com.mqtt.service.MqttService;
2 import lombok.extern.slf4j.Slf4j;
3 import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
4 import org.springframework.integration.mqtt.support.MqttHeaders;
5 import org.springframework.integration.support.MessageBuilder;
6 import org.springframework.messaging.Message;
7 import org.springframework.stereotype.Service;
8
9 import javax.annotation.Resource;
10
11 @Service("MqttService")
12 @Slf4j
13 public class MqttServiceImpl implements MqttService {
14
15 @Resource
16 private MqttPahoMessageHandler mqttHandler;
17
18 @Override
19 public void send(String topic, String content) throws Exception {
20 // 构建消息
21 Message<String> messages =
22 MessageBuilder.withPayload(content).setHeader(MqttHeaders.TOPIC, topic).build();
23 // 发送消息
24 mqttHandler.handleMessage(messages);
25 }
26
27
28 @Override
29 public void handler(String message) throws Exception {
30 log.info("收到消息:"+message);
31 }
32 }
33

MQTT Controller

 1 package com.loong.mqtt.controller;
2
3 import com.loong.api.model.ApiQueryOrderModel;
4 import com.loong.kuaizhi.service.KuaizhiService;
5 import com.loong.mqtt.service.MqttService;
6 import com.loong.ysf.dto.Protocol;
7 import com.loong.ysf.model.OrderInfo;
8 import lombok.extern.slf4j.Slf4j;
9 import org.jeecgframework.core.common.service.impl.RedisService;
10 import org.jeecgframework.core.util.ResourceUtil;
11 import org.springframework.beans.factory.annotation.Autowired;
12 import org.springframework.web.bind.annotation.*;
13
14 import javax.annotation.Resource;
15 import javax.servlet.http.HttpServletRequest;
16 import javax.servlet.http.HttpServletResponse;
17
18 /**
19 */
20 @RestController
21 @RequestMapping("/mqttController")
22 @Slf4j
23 public class MqttController {
24
25 @Resource(name = "MqttService")
26 private MqttService mqttService;
27
28 @RequestMapping(params = "testSend", method = RequestMethod.POST)
29 @ResponseBody
30 public String testSend(HttpServletRequest request, HttpServletResponse response) {
31 try {
32 String topic = ResourceUtil.getParameter("topic");
33 String content = ResourceUtil.getParameter("content");
34 this.mqttService.send(topic,content);
35 } catch (Exception ex) {
36 ex.printStackTrace();
37 log.error("发送失败", ex);
38 }
39
40 return "发送成功";
41 }
42 }

发送消息测试

  • MQTTBOX先连上MQTT服务器,并订阅topic为hello的消息
  • POSTMAN向mqttController.testSend接口发送请求,topic为hello,内容为{"hello":"200315"}
  • MQTTBOX里面的订阅者收到消息

接收消息测试

  • MQTTBOX创建一个消息发布者,发MQTT服务器发送topic为hello,内容为{"hello":"513002"}

     

  • 项目后台日志输出订阅到的内容

作者:admin
原文地址:www.jiansword.com

MQTT 3 ——MQTT与Spring Mvc整合的更多相关文章

  1. Spring与Struts2整合VS Spring与Spring MVC整合

    Spring与Struts2整合,struts.xml在src目录下 1.在web.xml配置监听器 web.xml <!-- 配置Spring的用于初始化ApplicationContext的 ...

  2. spring MVC 整合mongodb

    Spring Mongodb 目录 1 SPRING整合MONGODB 1 1.1 环境准备 1 1.2 包依赖 1 1.3 配置 2 2 案列 5 2.1 SPRING MVC整合MONGODB代码 ...

  3. MyBatis+Spring+Spring MVC整合开发

    MyBatis+Spring+Spring MVC整合开发课程观看地址:http://www.xuetuwuyou.com/course/65课程出自学途无忧网:http://www.xuetuwuy ...

  4. 【RabbitMQ系列】 Spring mvc整合RabbitMQ

    一.linux下安装rabbitmq 1.安装erlang环境 wget http://erlang.org/download/otp_src_18.2.1.tar.gz tar xvfz otp_s ...

  5. Java基础-SSM之Spring和Mybatis以及Spring MVC整合案例

    Java基础-SSM之Spring和Mybatis以及Spring MVC整合案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 能看到这篇文章的小伙伴,详细你已经有一定的Java ...

  6. spring mvc整合mybaitis和log4j

    在上一篇博客中,我介绍了在mac os上用idea搭建spring mvc的maven工程,但是一个完整的项目肯定需要数据库和日志管理,下面我就介绍下spring mvc整合mybatis和log4j ...

  7. Spring MVC 整合Swagger的一些问题总结

    在做Spring MVC 整合swagger的时候,遇到的两个问题: 第一个问题 在网上找了一些Spring MVC 和Swagger的例子,照着一步步的配置,结果,到最后,项目都起来了,没有任何问题 ...

  8. 【Java Web开发学习】Spring MVC整合WebSocket通信

    Spring MVC整合WebSocket通信 目录 ========================================================================= ...

  9. 【转载】Spring MVC 整合 Freemarker

    前言 1.为什么要使用Spring MVC呢? 2.为什么要使用Freemarker呢? 3.为什么不使用Struts2呢? 此示例出现的原因就是发现了struts2的性能太差,所以学习Spring ...

随机推荐

  1. mybatis学习——类型别名(typeAliases)

    为什么要用类型别名? 答:类型别名可为 Java 类型设置一个缩写名字. 它仅用于 XML 配置,意在降低冗余的全限定类名书写. 举个例子说明: 在我们编写映射文件的时候: <?xml vers ...

  2. Typora 配置码云图床

    目录 在码云创建一个项目作为自己床图 设置私人令牌 下载安装 PigGo Typora中设置图片上传选项 在码云创建一个项目作为自己床图 创建的项目必须为公开项目,创建的过程不细说了. 设置私人令牌 ...

  3. 【题解】codeforces 219D Choosing Capital for Treeland 树型dp

    题目描述 Treeland国有n个城市,这n个城市连成了一颗树,有n-1条道路连接了所有城市.每条道路只能单向通行.现在政府需要决定选择哪个城市为首都.假如城市i成为了首都,那么为了使首都能到达任意一 ...

  4. Android集合中对象排序

    如果将集合中的对象进行排序,最近使用了一个简单的方法解决了,随笔记下来. 主要思路: 首先,新建类实现Comparator<?>,这个类是做比较的关键类,一般做比较的类型 int 或 St ...

  5. 『心善渊』Selenium3.0基础 — 9、使用Seleniun中的By类定位元素

    目录 1.使用By定位的前提 2.By定位的方法 3.By定位的使用 4.复数形式的示例 我们还可以通过Seleniun测试框架中的By类,来实现页面中的元素定位. 1.使用By定位的前提 需要导入B ...

  6. Vue(9)购物车练习

    购物车案例 经过一系列的学习,我们这里来练习一个购物车的案例   需求:使用vue写一个表单页面,页面上有购买的数量,点击按钮+或者-,可以增加或减少购物车的数量,数量最少不得少于0,点击移除按钮,会 ...

  7. redis实现分布式锁天然的缺陷

    redis分布式锁基本原理 采用 redis 实现分布式锁,主要是利用其单线程命令执行的特性,一般是 setnx, 只会有一个线程会执行成功,也就是只有一个线程能成功获取锁: 看着很完美 看看可能有什 ...

  8. Linux安装及管理程序

    一,常见的软件包封装类型 二.RPM包管理工具 三.查询RPM软件包信息 四.安装.升级.卸载RPM软件包 五.解决软件包依赖关系的方法 六.源代码编译 七.安装yum源仓库 一,常见的软件包封装类型 ...

  9. JavaScript实现的7种排序算法

    所谓排序算法,即通过特定的算法因式将一组或多组数据按照既定模式进行重新排序.这种新序列遵循着一定的规则,体现出一定的规律,因此,经处理后的数据便于筛选和计算,大大提高了计算效率.对于排序,我们首先要求 ...

  10. 9.6、zabbix监控总结

    1.自动发现和自动注册的区别: (1)自动发现: 1)用于zabbix-agent的被动模式,是zabbix-server主动去添加主机.在web上创建自动发现的规则 后,zabbix-server会 ...