Spring 与MQTT的结合

1. MQTT配置文件mqtt.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:int="http://www.springframework.org/schema/integration"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:int-mqtt="http://www.springframework.org/schema/integration/mqtt"
    xsi:schemaLocation="
        http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-4.1.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
        http://www.springframework.org/schema/integration/mqtt http://www.springframework.org/schema/integration/mqtt/spring-integration-mqtt-4.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.1.xsd">

	<bean id="clientFactory"
		class="org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory">
		<property name="userName" value="用户名" />
		<property name="password" value="密码" />
		<property name="serverURIs">
			<array>
				<value>mqtt服务地址</value>
			</array>
		</property>
	</bean>
	
	<bean id="mqtt" class="org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler">
		<constructor-arg name="clientId" value="CID_2016524123456"></constructor-arg>
		<constructor-arg name="clientFactory" ref="clientFactory"></constructor-arg>
	</bean>
</beans>
	
2. 将MQTT配置文件引入spring配置文件中:

<!-- 引入mqtt配置文件 -->  
<import resource="xml/mqtt.xml"/>  
3. 发布代码:

@Controller
@RequestMapping("/mqtt")
public class MessageController {
	@Resource
	private MqttPahoMessageHandler mqtt;
	
	@RequestMapping(value="/send")
	public void sendMessage(){
		Message<String> message = MessageBuilder.withPayload("==========1111111111111111111111111=========").setHeader(MqttHeaders.TOPIC, "robot_server").build();
		mqtt.handleMessage(message);
		System.out.println("成功");
	}
}
4. 订阅代码:

public class MqttService {

	    public void startCase(String message){
	        System.out.println(message);
	    }
}






发布了85 篇原创文章 · 获赞 345 · 访问量 84万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 撸撸猫 设计师: 设计师小姐姐

分享到微信朋友圈

×

扫一扫,手机浏览