Java 调用emqx 主动删除某个clientid连接
要删除emqx的某个clientid连接,
1、可以通过界面直接手动删除。
2、可以通过命令行:
查询所有clientid # ./bin/emqx_ctl clients list 删除某个clientid # ./bin/emqx_ctl clients kick <Clientid>
进行删除。
3、还可以通过Java接口调用删除:
我的emqx 版本是 4.0.4 。删除地址为
http://127.0.0.1:18083/api/v4/clients/clientid_test
其他版本访问地址可能有所不同,请注意。
@Override public ResultDTO deleteClientId(String clientid){ log.info("deleteClientId 设备禁用,下行指令剔除原mqtt的clientid连接,入参clientid: {}", clientid); try { /* 传入的clientid 可能有特殊字符,先进行字符转换 */ clientid = URLEncoder.encode(clientid,"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ResultDTO.getFailure(); } // 这里拼接处要删除clientid 地址。例:http://127.0.0.1:18083/api/v4/clients/clientid_test String url = String.format(ConstantConfig.MQTT_DASHBOARD_URL_STR, ConstantConfig.getServerConfig().getProperty(ConstantConfig.MQTT_DASHBOARD_URL).trim(), clientid ); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpDelete httpDelete = new HttpDelete(url); RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(35000).setConnectionRequestTimeout(35000).setSocketTimeout(60000).build(); httpDelete.setConfig(requestConfig); // 这里emqx web的登录名密码。例:admin:public String authString = ConstantConfig.getServerConfig().getProperty(ConstantConfig.MQTT_DASHBOARD_USER).trim()+":"+ConstantConfig.getServerConfig().getProperty(ConstantConfig.MQTT_DASHBOARD_PASSWORD).trim(); byte[] authEncBytes = Base64.encodeBase64(authString.getBytes()); String authStringEnc = new String(authEncBytes); httpDelete.setHeader("Authorization", "Basic " + authStringEnc); httpDelete.setHeader("Content-type", "application/json"); httpDelete.setHeader("DataEncoding", "UTF-8"); CloseableHttpResponse httpResponse = null; try { // 通过http请求进行访问。 httpResponse = httpClient.execute(httpDelete); HttpEntity entity = httpResponse.getEntity(); // 获得删除结果 String result = EntityUtils.toString(entity); } catch (ClientProtocolException e) { e.printStackTrace(); return ResultDTO.getFailure(); } catch (IOException e) { e.printStackTrace(); return ResultDTO.getFailure(); } finally { if (httpResponse != null) { try { httpResponse.close(); } catch (IOException e) { e.printStackTrace(); } } if (null != httpClient) { try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return ResultDTO.getSuccess(); }