| | |
| | | import org.springframework.core.annotation.Order; |
| | | import org.springframework.stereotype.Component; |
| | | |
| | | import javax.annotation.Resource; |
| | | import java.io.UnsupportedEncodingException; |
| | | |
| | | /** |
| | |
| | | @Slf4j(topic = "mqtt") |
| | | @Order(1) |
| | | public class MqttProducer implements ApplicationRunner { |
| | | @Value("${spring.mqtt.enabled}") |
| | | private Boolean MQTT_ENABLED; |
| | | @Value("${spring.mqtt.host}") |
| | | private String MQTT_HOST; |
| | | @Value("${spring.mqtt.clientId}") |
| | | private String MQTT_CLIENT_ID; |
| | | @Value("${spring.mqtt.username}") |
| | | private String MQTT_USER_NAME; |
| | | @Value("${spring.mqtt.password}") |
| | | private String MQTT_PASSWORD; |
| | | @Value("${spring.mqtt.timeout}") |
| | | private int MQTT_TIMEOUT; |
| | | @Value("${spring.mqtt.keepalive}") |
| | | private int MQTT_KEEP_ALIVE; |
| | | @Resource |
| | | MqttConfiguration mqttConfig; |
| | | |
| | | private static MqttClient client; |
| | | |
| | | @Override |
| | | public void run(ApplicationArguments args) { |
| | | log.debug("初始化并启动mqtt......"); |
| | | if (MQTT_ENABLED) { |
| | | if (mqttConfig.getEnabled()) { |
| | | this.connect(); |
| | | } |
| | | } |
| | |
| | | getClient(); |
| | | // 2 设置配置 |
| | | MqttConnectOptions options = getOptions(); |
| | | options.setMaxInflight(1000); |
| | | // 3 最后设置 |
| | | create(options); |
| | | } catch (Exception e) { |
| | |
| | | public void getClient() { |
| | | try { |
| | | if (null == client) { |
| | | client = new MqttClient(MQTT_HOST, MQTT_CLIENT_ID, new MemoryPersistence()); |
| | | client = new MqttClient(mqttConfig.getHost(), mqttConfig.getClientId(), new MemoryPersistence()); |
| | | } |
| | | log.debug("--创建mqtt客户端"); |
| | | } catch (Exception e) { |
| | |
| | | public MqttConnectOptions getOptions() { |
| | | MqttConnectOptions options = new MqttConnectOptions(); |
| | | //设置用户名密码 |
| | | options.setUserName(MQTT_USER_NAME); |
| | | options.setPassword(MQTT_PASSWORD.toCharArray()); |
| | | options.setUserName(mqttConfig.getUsername()); |
| | | options.setPassword(mqttConfig.getPassword().toCharArray()); |
| | | // 设置超时时间 |
| | | options.setConnectionTimeout(MQTT_TIMEOUT); |
| | | options.setConnectionTimeout(mqttConfig.getTimeout()); |
| | | // 设置会话心跳时间 |
| | | options.setKeepAliveInterval(MQTT_KEEP_ALIVE); |
| | | options.setKeepAliveInterval(mqttConfig.getKeepalive()); |
| | | // 是否清除session |
| | | options.setCleanSession(false); |
| | | log.debug("--生成mqtt配置对象"); |