本篇记录一下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. ADAS可行驶区域道路积水反光区域的识别算法

    ADAS可行驶区域道路积水反光区域的识别算法 Water logging area reflecting recognition algorithm for ADAS 1. 工程概要 1.1  概述: ...

  2. Mobileye独创性创新

    Mobileye独创性创新 尽管存在相似之处,但Nvidia的SFF无法与Mobileye的RSS相匹配,后者是领先的AV安全模型 迈向无人驾驶的未来,Mobileye继续以新的创新引领行业,不仅将使 ...

  3. Yolo:实时目标检测实战(上)

    Yolo:实时目标检测实战(上) YOLO:Real-Time Object Detection 你只看一次(YOLO)是一个最先进的实时物体检测系统.在帕斯卡泰坦X上,它以每秒30帧的速度处理图像, ...

  4. Velodyne VLP-16激光雷达数据分析

    Velodyne VLP-16激光雷达数据分析 Velodyne VLP-16激光雷达保持了 Velodyne 在 LiDAR 中的突破性重要功能:实时收发数据.360 度全覆盖.3D 距离测量以及校 ...

  5. SpringBoot系列——cache缓存

    前言 日常开发中,缓存是解决数据库压力的一种方案,通常用于频繁查询的数据,例如新闻中的热点新闻,本文记录springboot中使用cache缓存. 官方文档介绍:https://docs.spring ...

  6. Docker-compose搭建ELK环境并同步MS SQL Server数据

    前言 本文作为学习记录,供大家参考:一次使用阿里云(Aliyun)1核2G centos7.5 云主机搭建Docker下的ELK环境,并导入MS SQL Server的商品数据以供Kibana展示的配 ...

  7. 「是时候升级Java11了」 JDK11优势和JDK选择

    Java8 商用收费 从2019年1月份开始,Oracle JDK 开始对 Java SE 8 之后的版本开始进行商用收费,确切的说是 8u201/202 之后的版本.如果你用 Java 开发的功能如 ...

  8. 4.2tensorflow多层感知器MLP识别手写数字最易懂实例代码

    自己开发了一个股票智能分析软件,功能很强大,需要的点击下面的链接获取: https://www.cnblogs.com/bclshuai/p/11380657.html 1.1  多层感知器MLP(m ...

  9. SpringCloud Alibaba实战(8:使用OpenFeign服务调用)

    源码地址:https://gitee.com/fighter3/eshop-project.git 持续更新中-- 在上一个章节,我们已经成功地将服务注册到了Nacos注册中心,实现了服务注册和服务发 ...

  10. Luat Demo | 一文读懂,如何使用Cat.1开发板实现Camera功能

    让万物互联更简单,合宙通信高效便捷的二次开发方式Luat,为广大客户提供了丰富实用的Luat Demo示例,便于项目开发灵活应用. 本期采用合宙全新推出的VSCode插件LuatIDE,为大家演示如何 ...