目录
4.2 只发不接收可使用Netty-client 具体看Netty那章,等我空了写
Spring integration交互逻辑
对于发布者:
消息通过消息网关发送出去,由 MessageChannel 的实例 DirectChannel 处理发送的细节。
DirectChannel 收到消息后,内部通过 MessageHandler 的实例 MqttPahoMessageHandler 发送到指定的 Topic。
对于订阅者:
通过注入 MessageProducerSupport 的实例 MqttPahoMessageDrivenChannelAdapter,实现订阅 Topic 和绑定消息消费的 MessageChannel。
同样由 MessageChannel 的实例 DirectChannel 处理消费细节。Channel 消息后会发送给我们自定义的 MqttInboundMessageHandler 实例进行消费。
1、maven依赖
<dependency>
<groupId>org.springframework.integration</groupId>
<artifactId>spring-integration-mqtt</artifactId>
<version>5.3.1.RELEASE</version>
</dependency>
2.yml配置
mqtt:
appid: mqttx_${random.value}
#订阅主题,多个主题用逗号分隔
inputTopic: test009
#MQTT服务器地址
services: tcp://ip:1883
#mqtt用户名
user:
#mqtt密码,默认无
password:
#心跳间隔时间,默认300
KeepAliveInterval: 30
#是否不保持session,默认false
CleanSession: false
#是否自动连接,默认true
AutomaticReconnect: true
#连接超时,默认30000
CompletionTimeout: 30000
#传输质量,默认1
Qos: 1
3.配置获取yml信息
@Service
@Value("${mqtt.appid}")
private String appid;
@Value("${mqtt.inputTopic}")
private String[] inputTopic;//订阅主题
// @Value("${mqtt.outTopic}")
// private String[] outTopic;//发布主题
@Value("${mqtt.services}")
private String[] mqttServices;//服务器地址以及端口
@Value("${mqtt.user}")
private String user;//用户名
@Value("${mqtt.password}")
private String password;//密码
@Value("${mqtt.KeepAliveInterval}")
private Integer KeepAliveInterval;//心跳时间
@Value("${mqtt.CleanSession}")
private Boolean CleanSession;//是否不保持session,默认为session保持
@Value("${mqtt.AutomaticReconnect}")
private Boolean AutomaticReconnect;//是否自动重联,默认为开启自动重联
@Value("${mqtt.CompletionTimeout}")
private Long CompletionTimeout;//连接超时,默认为30秒
@Value("${mqtt.Qos}")
private Integer Qos;//通信质量
@Bean
public MqttPahoClientFactory mqttClientFactory() {
DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();//连接工厂类
MqttConnectOptions options = new MqttConnectOptions();//连接参数
options.setServerURIs(mqttServices);//连接地址
if(user!=null) {
options.setUserName(user);//用户名
}
if(password!=null) {
options.setPassword(password.toCharArray());//密码
}
options.setKeepAliveInterval(KeepAliveInterval);//心跳时间
options.setAutomaticReconnect(AutomaticReconnect);//断开是否自动重联
options.setCleanSession(CleanSession);//保持session
factory.setConnectionOptions(options);
return factory;
}
4.发送
@Configuration
@IntegrationComponentScan
@Slf4j
public class MqttOutboundConfiguration {
@Autowired
private MqttMessageService mqttMessageService;
@Bean
@ServiceActivator(inputChannel = "mqttOutboundChannel")
public MessageHandler mqttOutbound() {
MqttPahoMessageHandler messageHandler = new MqttPahoMessageHandler(mqttMess