单个username认证
| mqtt: |
| broker-url: tcp://192.168.96.168:1883 |
| client-id: emq-client |
| username: user |
| password: 123456 |
| @Component |
| public class EmqClient { |
| |
| private static final Logger log = LoggerFactory.getLogger(EmqClient.class); |
| |
| private IMqttClient mqttClient; |
| |
| @Autowired |
| private MqttProperties mqttProperties; |
| |
| @Autowired |
| private MqttCallback mqttCallback; |
| |
| @PostConstruct |
| public void init(){ |
| MqttClientPersistence mempersitence = new MemoryPersistence(); |
| try { |
| mqttClient = new MqttClient(mqttProperties.getBrokerUrl(),mqttProperties.getClientId(),mempersitence); |
| } catch (MqttException e) { |
| log.error("初始化客户端mqttClient对象失败,errormsg={},brokerUrl={},clientId={}",e.getMessage(),mqttProperties.getBrokerUrl(),mqttProperties.getClientId()); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public void connect(String username,String password){ |
| MqttConnectOptions options = new MqttConnectOptions(); |
| options.setAutomaticReconnect(true); |
| options.setUserName(username); |
| options.setPassword(password.toCharArray()); |
| options.setCleanSession(true); |
| mqttClient.setCallback(mqttCallback); |
| try { |
| mqttClient.connect(options); |
| } catch (MqttException e) { |
| log.error("mqtt客户端连接服务端失败,失败原因{}",e.getMessage()); |
| } |
| } |
| |
| |
| |
| |
| @PreDestroy |
| public void disConnect(){ |
| try { |
| mqttClient.disconnect(); |
| } catch (MqttException e) { |
| log.error("断开连接产生异常,异常信息{}",e.getMessage()); |
| } |
| } |
| |
| |
| |
| |
| public void reConnect(){ |
| try { |
| mqttClient.reconnect(); |
| } catch (MqttException e) { |
| log.error("重连失败,失败原因{}",e.getMessage()); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public void publish(String topic, String msg, QosEnum qos, boolean retain){ |
| MqttMessage mqttMessage = new MqttMessage(); |
| mqttMessage.setPayload(msg.getBytes()); |
| mqttMessage.setQos(qos.value()); |
| mqttMessage.setRetained(retain); |
| try { |
| mqttClient.publish(topic,mqttMessage); |
| } catch (MqttException e) { |
| log.error("发布消息失败,errormsg={},topic={},msg={},qos={},retain={}",e.getMessage(),topic,msg,qos.value(),retain); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| public void subscribe(String topicFilter,QosEnum qos){ |
| try { |
| mqttClient.subscribe(topicFilter,qos.value()); |
| } catch (MqttException e) { |
| log.error("订阅主题失败,errormsg={},topicFilter={},qos={}",e.getMessage(),topicFilter,qos.value()); |
| } |
| } |
| |
| |
| |
| |
| |
| public void unSubscribe(String topicFilter){ |
| try { |
| mqttClient.unsubscribe(topicFilter); |
| } catch (MqttException e) { |
| log.error("取消订阅失败,errormsg={},topicfiler={}",e.getMessage(),topicFilter); |
| } |
| } |
| |
| } |
| @Component |
| public class MessageCallback implements MqttCallback { |
| |
| private static final Logger log = LoggerFactory.getLogger(MessageCallback.class); |
| |
| |
| |
| |
| |
| @Override |
| public void connectionLost(Throwable cause) { |
| |
| log.info("丢失了对服务端的连接"); |
| } |
| |
| |
| |
| |
| |
| |
| |
| @Override |
| public void messageArrived(String topic, MqttMessage message) throws Exception { |
| log.info("订阅者订阅到了消息,topic={},messageid={},qos={},payload={}", |
| topic, |
| message.getId(), |
| message.getQos(), |
| new String(message.getPayload())); |
| } |
| |
| |
| |
| |
| |
| @Override |
| public void deliveryComplete(IMqttDeliveryToken token) { |
| int messageId = token.getMessageId(); |
| String[] topics = token.getTopics(); |
| log.info("消息发布完成,messageid={},topics={}",messageId,topics); |
| } |
| |
| } |
| public enum QosEnum { |
| |
| QoS0(0),QoS1(1),QoS2(2); |
| |
| private final int value; |
| |
| QosEnum(int value) { |
| this.value = value; |
| } |
| |
| public int value(){ |
| return this.value; |
| } |
| |
| } |
| @Component |
| @Configuration |
| @ConfigurationProperties(prefix = "mqtt") |
| public class MqttProperties { |
| |
| private String brokerUrl; |
| |
| private String clientId; |
| |
| private String username; |
| |
| private String password; |
| |
| public String getBrokerUrl() { |
| return brokerUrl; |
| } |
| |
| public void setBrokerUrl(String brokerUrl) { |
| this.brokerUrl = brokerUrl; |
| } |
| |
| public String getClientId() { |
| return clientId; |
| } |
| |
| public void setClientId(String clientId) { |
| this.clientId = clientId; |
| } |
| |
| public String getUsername() { |
| return username; |
| } |
| |
| public void setUsername(String username) { |
| this.username = username; |
| } |
| |
| public String getPassword() { |
| return password; |
| } |
| |
| public void setPassword(String password) { |
| this.password = password; |
| } |
| |
| @Override |
| public String toString() { |
| return "MqttProperties{" + |
| "brokerUrl='" + brokerUrl + '\'' + |
| ", clientId='" + clientId + '\'' + |
| ", username='" + username + '\'' + |
| ", password='" + password + '\'' + |
| '}'; |
| } |
| |
| } |
| @Component |
| @Slf4j |
| public class MqttInitMsgUtil { |
| |
| @Resource |
| private MqttInitUtil mqttInitUtil; |
| |
| @Resource |
| private PlatFormSystemMessageService platFormSystemMessageService; |
| |
| private static MqttInitMsgUtil mqttInitMsgUtil; |
| |
| @PostConstruct |
| public void init(){ |
| mqttInitMsgUtil = this; |
| mqttInitMsgUtil.mqttInitUtil = this.mqttInitUtil; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public void sendMqttMsg(String templateId, String pubId, String userType) { |
| try { |
| |
| StringBuffer result = new StringBuffer(); |
| result.append("testtopic"); |
| result.append("/"); |
| result.append(pubId); |
| |
| TMessageTemplate tMessageTemplate = platFormSystemMessageService.queryTMessageTemplate(templateId); |
| Map<String,String> map = new HashMap<String,String>(); |
| map.put("msgTemplateTitle",tMessageTemplate.getMsgTemplateTitle()); |
| map.put("templateContent",tMessageTemplate.getTemplateContent()); |
| String str = ConverUitl.getMapToString(map); |
| |
| mqttInitUtil.publish(result.toString(), str, QosEnum.QoS2,false); |
| |
| TMessage tMessage = new TMessage(); |
| tMessage.setId(SnowflakeIdWorkerUtil.nextId()); |
| tMessage.setCreated(new Date()); |
| tMessage.setUpdated(new Date()); |
| tMessage.setReadStatus("1"); |
| tMessage.setMsgTitle(map.get("msgTemplateTitle")); |
| tMessage.setMsgContent(map.get("templateContent")); |
| tMessage.setUserType(userType); |
| tMessage.setUserId(pubId); |
| tMessage.setMtId(templateId); |
| tMessage.setDeleted(0); |
| platFormSystemMessageService.addTMessage(tMessage); |
| }catch (Exception e){ |
| log.error(e.getMessage()); |
| throw new GlobalException(e.getMessage()); |
| } |
| } |
| |
| } |
| @RestController |
| @RequestMapping("/tMessageTest") |
| @AllArgsConstructor |
| @Api(tags = "消息通知测试") |
| public class TMessageTest { |
| |
| @Autowired |
| private EmqClient emqClient; |
| |
| @Autowired |
| private MqttProperties properties; |
| |
| @Autowired |
| private MsgPubMqttUtil msgPubMqttUtil; |
| |
| @Autowired |
| private MqttInitUtil mqttInitUtil; |
| |
| @Autowired |
| private MqttInitMsgUtil mqttInitMsgUtil; |
| |
| |
| |
| |
| |
| @RequestMapping("/test1") |
| @ResponseBody |
| public String test1(){ |
| msgPubMqttUtil.sendMqttMessage("955407201726365696", "951524255252611072", TMessageUserTypeEnum.USER.getValue()); |
| return "success"; |
| } |
| |
| } |
多个username认证
| mqtt: |
| broker-url: tcp://192.168.96.168:1883 |
| client-id: emq-client |
| username: user |
| password: 123456 |
| authurl: http://192.168.96.168:8081/api/v4/auth_username/ |
| authname: admin |
| authpwd: public |
| @Component |
| public class MqttInitUtil { |
| |
| public static String authurl; |
| |
| public static String authname; |
| |
| public static String authpwd; |
| |
| @Value("${mqtt.authurl}") |
| public void setAuthurl(String authurl) { |
| MqttInitUtil.authurl = authurl; |
| } |
| |
| @Value("${mqtt.authname}") |
| public void setAuthname(String authname) { |
| MqttInitUtil.authname = authname; |
| } |
| |
| @Value("${mqtt.authpwd}") |
| public void setAuthpwd(String authpwd) { |
| MqttInitUtil.authpwd = authpwd; |
| } |
| |
| private static final Logger log = LoggerFactory.getLogger(EmqClient.class); |
| |
| private IMqttClient mqttClient; |
| |
| @Autowired |
| private MqttProperties mqttProperties; |
| |
| @Autowired |
| private MqttCallback mqttCallback; |
| |
| |
| |
| |
| |
| |
| |
| |
| public void createEmqxUser(String emqUser, String emqPwd, String clientId) throws IOException { |
| |
| String url = authurl; |
| String token = authname + ":" + authpwd; |
| Map<String, String> prarms = new HashMap<>(); |
| prarms.put("username",emqUser); |
| prarms.put("password", emqPwd); |
| String jsonPrarms = JSON.toJSONString(prarms); |
| CloseableHttpClient httpClient = HttpClientBuilder.create().build(); |
| HttpPost httpPost = new HttpPost(url); |
| String encoding = DatatypeConverter.printBase64Binary(token.getBytes("UTF-8")); |
| httpPost.setHeader("Authorization", "Basic " + encoding); |
| HttpEntity entityParam = new StringEntity(jsonPrarms, ContentType.create("application/json", "UTF-8")); |
| httpPost.setEntity(entityParam); |
| HttpResponse response = httpClient.execute(httpPost); |
| StatusLine statusLine = response.getStatusLine(); |
| int responseCode = statusLine.getStatusCode(); |
| if (responseCode == 200) { |
| |
| HttpEntity entity = response.getEntity(); |
| InputStream input = entity.getContent(); |
| BufferedReader br = new BufferedReader(new InputStreamReader(input,"utf-8")); |
| String str1 = br.readLine(); |
| System.out.println("服务器的响应是:" + str1); |
| br.close(); |
| input.close(); |
| } else { |
| System.out.println("响应失败"); |
| } |
| |
| init(clientId); |
| |
| connect(emqUser,emqPwd); |
| |
| } |
| |
| |
| |
| |
| |
| |
| public String delEmqxUser(String emqUser) throws IOException { |
| String url = authurl + emqUser; |
| String token = authname + ":" + authpwd; |
| String encoding = DatatypeConverter.printBase64Binary(token.getBytes("UTF-8")); |
| CloseableHttpClient httpClient = HttpClients.createDefault(); |
| HttpDelete httpDelete = new HttpDelete(url); |
| RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build(); |
| httpDelete.setConfig(requestConfig); |
| httpDelete.setHeader("Content-type", "application/json"); |
| httpDelete.setHeader("DataEncoding", "UTF-8"); |
| httpDelete.setHeader("Authorization", "Basic " + encoding); |
| CloseableHttpResponse httpResponse = null; |
| try { |
| httpResponse = httpClient.execute(httpDelete); |
| HttpEntity entity = httpResponse.getEntity(); |
| String result = EntityUtils.toString(entity); |
| return result; |
| } catch (ClientProtocolException e) { |
| |
| e.printStackTrace(); |
| } catch (IOException e) { |
| |
| e.printStackTrace(); |
| } finally { |
| if (httpResponse != null) { |
| try { |
| httpResponse.close(); |
| } catch (IOException e) { |
| |
| e.printStackTrace(); |
| } |
| } |
| if (null != httpClient) { |
| try { |
| httpClient.close(); |
| } catch (IOException e) { |
| e.printStackTrace(); |
| } |
| } |
| } |
| return null; |
| } |
| |
| |
| |
| |
| |
| |
| public void init(String clientId){ |
| MqttClientPersistence mempersitence = new MemoryPersistence(); |
| try { |
| mqttClient = new MqttClient(mqttProperties.getBrokerUrl(),clientId,mempersitence); |
| } catch (MqttException e) { |
| log.error("初始化客户端mqttClient对象失败,errormsg={},brokerUrl={},clientId={}",e.getMessage(),mqttProperties.getBrokerUrl(),clientId); |
| } |
| } |
| |
| |
| |
| |
| |
| public void connect(String username,String password){ |
| MqttConnectOptions options = new MqttConnectOptions(); |
| options.setAutomaticReconnect(true); |
| options.setUserName(username); |
| options.setPassword(password.toCharArray()); |
| options.setCleanSession(true); |
| mqttClient.setCallback(mqttCallback); |
| try { |
| mqttClient.connect(options); |
| } catch (MqttException e) { |
| log.error("mqtt客户端连接服务端失败,失败原因{}",e.getMessage()); |
| } |
| } |
| |
| |
| |
| |
| public void disConnect(){ |
| try { |
| mqttClient.disconnect(); |
| } catch (MqttException e) { |
| log.error("断开连接产生异常,异常信息{}",e.getMessage()); |
| } |
| } |
| |
| |
| |
| public void reConnect(){ |
| try { |
| mqttClient.reconnect(); |
| } catch (MqttException e) { |
| log.error("重连失败,失败原因{}",e.getMessage()); |
| } |
| } |
| |
| |
| |
| |
| |
| |
| |
| public void publish(String topic, String msg, QosEnum qos, boolean retain){ |
| MqttMessage mqttMessage = new MqttMessage(); |
| mqttMessage.setPayload(msg.getBytes()); |
| mqttMessage.setQos(qos.value()); |
| mqttMessage.setRetained(retain); |
| try { |
| mqttClient.publish(topic,mqttMessage); |
| } catch (MqttException e) { |
| log.error("发布消息失败,errormsg={},topic={},msg={},qos={},retain={}",e.getMessage(),topic,msg,qos.value(),retain); |
| } |
| } |
| |
| |
| |
| |
| |
| public void subscribe(String topicFilter,QosEnum qos){ |
| try { |
| mqttClient.subscribe(topicFilter,qos.value()); |
| } catch (MqttException e) { |
| log.error("订阅主题失败,errormsg={},topicFilter={},qos={}",e.getMessage(),topicFilter,qos.value()); |
| } |
| } |
| |
| |
| |
| |
| public void unSubscribe(String topicFilter){ |
| try { |
| mqttClient.unsubscribe(topicFilter); |
| } catch (MqttException e) { |
| log.error("取消订阅失败,errormsg={},topicfiler={}",e.getMessage(),topicFilter); |
| } |
| } |
| |
| } |
| @Component |
| @Slf4j |
| public class MqttInitMsgUtil { |
| |
| @Resource |
| private MqttInitUtil mqttInitUtil; |
| |
| @Resource |
| private PlatFormSystemMessageService platFormSystemMessageService; |
| |
| private static MqttInitMsgUtil mqttInitMsgUtil; |
| |
| @PostConstruct |
| public void init(){ |
| mqttInitMsgUtil = this; |
| mqttInitMsgUtil.mqttInitUtil = this.mqttInitUtil; |
| } |
| |
| |
| |
| |
| |
| |
| |
| |
| public void sendMqttMsg(String templateId, String pubId, String userType) { |
| try { |
| |
| StringBuffer result = new StringBuffer(); |
| result.append("testtopic"); |
| result.append("/"); |
| result.append(pubId); |
| |
| TMessageTemplate tMessageTemplate = platFormSystemMessageService.queryTMessageTemplate(templateId); |
| Map<String,String> map = new HashMap<String,String>(); |
| map.put("msgTemplateTitle",tMessageTemplate.getMsgTemplateTitle()); |
| map.put("templateContent",tMessageTemplate.getTemplateContent()); |
| String str = ConverUitl.getMapToString(map); |
| |
| mqttInitUtil.publish(result.toString(), str, QosEnum.QoS2,false); |
| |
| TMessage tMessage = new TMessage(); |
| tMessage.setId(SnowflakeIdWorkerUtil.nextId()); |
| tMessage.setCreated(new Date()); |
| tMessage.setUpdated(new Date()); |
| tMessage.setReadStatus("1"); |
| tMessage.setMsgTitle(map.get("msgTemplateTitle")); |
| tMessage.setMsgContent(map.get("templateContent")); |
| tMessage.setUserType(userType); |
| tMessage.setUserId(pubId); |
| tMessage.setMtId(templateId); |
| tMessage.setDeleted(0); |
| platFormSystemMessageService.addTMessage(tMessage); |
| }catch (Exception e){ |
| log.error(e.getMessage()); |
| throw new GlobalException(e.getMessage()); |
| } |
| } |
| |
| } |
| |
| |
| |
| |
| |
| |
| @RequestMapping("/test2") |
| @ResponseBody |
| public String test2() throws IOException { |
| mqttInitUtil.createEmqxUser("goudan1", "goudan", "clientId_3239856123141"); |
| return "success"; |
| } |
| |
| |
| |
| |
| |
| @RequestMapping("/test3") |
| @ResponseBody |
| public String test3(){ |
| mqttInitMsgUtil.sendMqttMsg("955407201726365696", "951524255252611072", TMessageUserTypeEnum.USER.getValue()); |
| return "success"; |
| } |
| |
| |
| |
| |
| |
| @RequestMapping("/test4") |
| @ResponseBody |
| public String test4() throws IOException { |
| mqttInitUtil.delEmqxUser("goudan1"); |
| return "success"; |
| } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· 写一个简单的SQL生成工具
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)