EMQX文档:https://www.emqx.io/docs/zh/v5.0/
1.安装 https://www.emqx.io/zh/downloads
找到自己合适的平台和版本安装
①:后台启动
emqx start
启动成功后可以使用 emqx ping 命令检测节点运行状态,返回 pong 则表示正常运行:
emqx ping
systemctl 启动
sudo systemctl start emqx
sudo systemctl status emqx
ZIP 安装包启动
切换到 EMQX 解压目录,执行以下命令启动 EMQX:
./bin/emqx start
开发模式下可以使用 console 命令在控制台启动 EMQX,该模式可以实时查看 EMQX 启动和运行输出日志信息:
./bin/emqx console
默认监听: http://localhost:18083/
默认登录账号密码:admin public
default_username = “admin”
default_password = “public”
代码如下
## emqx配置
emqx:
api:
url: http://ip:端口/api/v4/clients/
username: 用户名称
password: 用户密码
@Value("${emqx.api.url}")
private String url;
@Value("${emqx.api.username}")
private String username;
@Value("${emqx.api.password}")
private String password;
/**
* 查询网关在线离线状态
* @param clientId 客户端标识符
* @return 返回在线离线状态
*/
@Override
public String loadEmqxOnlineStatus(String clientId) {
try {
String urlStr = url + clientId;
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.setDoOutput(true);
String authString = username + ":" + password;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
// 设置Authorization字段
conn.setRequestProperty("Authorization", "Basic " + authStringEnc);
conn.connect();
int status = conn.getResponseCode();
if (status == HttpStatus.OK.value()) {
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str = "";
StringBuffer sb = new StringBuffer();
while ((str = reader.readLine()) != null) {
sb.append(str);
}
// 取出里面的在线离线字段
String string = sb.toString();
JSONObject jsonObject = JSONObject.parseObject(string);
String data = jsonObject.getString("data");
JSONArray jsonArray = JSONArray.parseArray(data);
if (jsonArray.size() == 0) {
return null;
}
return jsonArray.getJSONObject(0).getString("connected");
}
} catch (IOException e) {
throw DataHandleException.of(Result.failure(ResultCode.UNAUTHORIZED, "客户端未通过服务端认证,您使用了无效的身份验证凭据"));
}
return null;
}