package com.ambox.timeServer.config;
import com.ambox.timeServer.common.TimeBoxEventHandle;
import com.ambox.timeServer.service.TimerServerService;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;
/**
* @description: mqtt配置类
* @author: LiuZhiJun
* @create: 2019-10-27 11:03
**/
@Configuration
public class MqttConfig {
private static final byte[] WILL_DATA;
static {
WILL_DATA = "offline".getBytes();
}
@Autowired
TimeBoxEventHandle timeBoxEventHandle;
/**
* 订阅的bean名称
*/
public static final String CHANNEL_NAME_IN = "mqttInboundChannel";
public static final String CHANNEL_NAME_IN_TWO = "mqttInboundChannel2";
public static final String ACTION_START_TIME = "startTiming";
public static final String ACTION_END_TIME = "endTiming";
public static final String ACTION_PAUSE_TIME = "pauseTiming";
public static final String ACTION_RESUME_TIME = "resumeTiming";
public static final String ACTION_EXTEND_TIME = "extendTiming";
public static final String ACTION_UPDATE_ADV = "updateAdvertising";
/**
* 发布的bean名称
*/
public static final String CHANNEL_NAME_OUT = "mqttOutboundChannel";
@Value("${mqtt.username}")
private String username;
@Value("${mqtt.password}")
private String password;
@Value("${mqtt.url}")
private String url;
@Value("${mqtt.producer.clientId}")
private String producerClientId;
@Value("${mqtt.producer.defaultTopic}")
private String producerDefaultTopic;
@Value("${mqtt.consumer.clientId}")
private String consumerClientId;
@Value("${mqtt.consumer.defaultTopic}")
private String consumerDefaultTopic;
@Value("${mqtt.completionTimeout}")
private int completionTimeout;
@Value("${mqtt.willTopic}")
private String willTopic;
@Autowired
TimerServerService timerServerService;
/**
* MQTT连接器选项
*
* @return {@link org.eclipse.paho.client.mqttv3.MqttConnectOptions}
*/
@Bean
public MqttConnectOptions getMqttConnectOptions() {
MqttConnectOptions options = new MqttConnectOptions();
// 设置是否清空session,这里如果设置为false表示服务器会保留客户端的连接记录,
// 这里设置为true表示每次连接到服务器都以新的身份连接
options.setCleanSession(false);
// 设置连接的用户名
options.setUserName(username);
// 设置连接的密码
options.setPassword(password.toCharArray());
options.setServerURIs(url.split(","));
// 设置超时时间 单位为秒
options.setConnectionTimeout(10);
// 设置会话心跳时间 单位为秒 服务器会每隔1.5*20秒的时间向客户端发送心跳判断客户端是否在线,但这个方法并没有重连的机制
options.setKeepAliveInterval(20);
options.setAutomaticReconnect(true);
// 设置“遗嘱”消息的话题,若客户端与服务器之间的连接意外中断,服务器将发布客户端的“遗嘱”消息。
options.setWill(willTopic, WILL_DATA, 2, false);
options.setAutomaticReconnect(true);
//最大的飞行窗口
options.setMaxInflight(1000);
return options;
}
/**
* MQTT客户端
*
* @return {@link org.springframework.integration.mqtt.core.MqttPahoClientFactory}
*/
@Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
factory.setConnectionOptions(getMqttConnectOptions());
return factory;
}
/**
* MQTT信息通道(生产者)
*
* @return {@link org.springframework.messaging.MessageChannel}
*/
@Bean(name = CHANNEL_NAME_OUT)
public MessageChannel mqttOutboundChannel() {
return new DirectChannel();
}
/**
* MQTT消息处理器(生产者)
*
* @return {@link org.springframework.messaging.MessageHandler}
*/
@Bean
@ServiceActivator(inputChannel = CHANNEL_NAME_OUT)
public MessageHandler mqttOutbound() {
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(
producerClientId,
mqttClientFactory());
messageHandler.setAsync(true);
messageHandler.setDefaultTopic(producerDefaultTopic);
return messageHandler;
}
/**
* MQTT消息订阅绑定(消费者)
*
* @return {@link org.springframework.integration.core.MessageProducer}
*/
@Bean
public MessageProducer inbound() {
//订阅主题
//获得真实门店id
// 可以同时消费(订阅)多个Topic
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter(
consumerClientId, mqttClientFactory(),
consumerDefaultTopic.split(","));
adapter.setCompletionTimeout(5000);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
// 设置订阅通道
adapter.setOutputChannel(mqttInboundChannel());
return adapter;
}
/**
* MQTT信息通道(消费者)
*
* @return {@link org.springframework.messaging.MessageChannel}
*/
@Bean(name = CHANNEL_NAME_IN)
public MessageChannel mqttInboundChannel() {
return new DirectChannel();
}
/**
* MQTT消息处理器(消费者)
*
* @return {@link org.springframework.messaging.MessageHandler}
*/
@Bean
@ServiceActivator(inputChannel = CHANNEL_NAME_IN)
public MessageHandler handler() {
return message -> {
try{
// System.out.println();
System.out.println("消息处理器1:message:"+message.getPayload().toString());
timeBoxEventHandle.handle(message.getPayload().toString());
}catch (Exception e){
e.printStackTrace();
}
};
}
// 通道2
@Bean(name = CHANNEL_NAME_IN_TWO)
public MessageChannel mqttInputChannelTwo() {
return new DirectChannel();
}
//配置client2,监听的willTopic
@Bean
public MessageProducer inbound1() {
MqttPahoMessageDrivenChannelAdapter adapter =
new MqttPahoMessageDrivenChannelAdapter(consumerClientId+"_inboundTwo", mqttClientFactory(),
willTopic);
adapter.setCompletionTimeout(completionTimeout);
adapter.setConverter(new DefaultPahoMessageConverter());
adapter.setQos(1);
adapter.setOutputChannel(mqttInputChannelTwo());
return adapter;
}
//通过通道2获取数据
@Bean
@ServiceActivator(inputChannel = CHANNEL_NAME_IN_TWO)
public MessageHandler handlerTwo() {
return message -> {
String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
String type = topic.substring(topic.lastIndexOf("/")+1, topic.length());
// todo 确定离线标识是不是设备号? 处理遗愿消息
System.out.println(topic);
try{
System.out.println("消息处理器2:message:"+message.getPayload().toString());
timeBoxEventHandle.handle(message.getPayload().toString());
}catch (Exception e){
e.printStackTrace();
}
};
}
}
spring 配置文件
mqtt:
username: admin
password: public
url: tcp://ip地址:1883端口
willTopic: will_message
completionTimeout: 3000
producer:
clientId: MqttProducer_Server_167
defaultTopic: TimeBox/Control/1
consumer:
clientId: MqttConsumer_Server_167
defaultTopic: TimeBox/Event/#