public class CrossClient {
private static final String USERNAME = "admin";//用戶名
private static final String PASSWORD = "password";//密碼
public void crossSensationLink(){
//用於測試的topic
final String topic = "bvip_notify";
//接入服務器域名
String targetServer = ConfigCacheUtil.getConf("crossClient").getValue();
String broker = "tcp://" + targetServer;
String clientId = UUID.randomUUID().toString();
// String clientId = "123456789123451";
MemoryPersistence persistence = new MemoryPersistence();
try {
final MqttClient mqttClient = new MqttClient(broker,clientId,persistence);
MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
final CrossCameraService crossCameraService = (CrossCameraService) SpringUtil
.getBean("crossCameraServiceImpl");
final CrossBorderService crossBorderService = (CrossBorderService) SpringUtil
.getBean("CrossBorderServiceImpl");
//MQTT 3.1.1
mqttConnectOptions.setMqttVersion(4);
//設置是否自動重連
mqttConnectOptions.setAutomaticReconnect(true);
mqttConnectOptions.setUserName(USERNAME);
mqttConnectOptions.setPassword(PASSWORD.toCharArray());
mqttConnectOptions.setKeepAliveInterval(80);
mqttClient.connect(mqttConnectOptions);
mqttClient.setCallback(new MqttCallback() {
@Override
public void connectionLost(Throwable throwable) {
System.out.println("連接失敗,原因:" + throwable);
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
System.out.println(System.currentTimeMillis() + "接收到消息,來自Topic [" + s+ "] ,內容是:["+ new String(mqttMessage.getPayload(),"UTF-8") + "],num");
//過濾是不是json數據,是不是報警事件
String corssBorderJson = new String(mqttMessage.getPayload(), "UTF-8");
HttpServletRequest request = getRequest();
JSONObject param = null;
try {
param = JSONObject. fromObject(corssBorderJson);
try {
String taskType = param.get("TaskType").toString();
if (taskType.equals("AlarmEvent")){
crossCameraService.saveCrossCamers(param);
// String data = crossBorderService.querySound(param);
// crossBorderService.login(data, request);
}
}catch (Exception e){
System.out.println("不是報警事件數據");
}
}catch (Exception e){
System.out.println("不是json格式數據");
}
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
//如果是qos 0消息 token.resp是沒有回覆的
System.out.println("消息發送成功!"
+ ((iMqttDeliveryToken == null || iMqttDeliveryToken.getResponse() == null)? "null" : iMqttDeliveryToken.getResponse().getKey()));
}
});
mqttClient.subscribe(topic);
System.out.println(System.currentTimeMillis() + "連接成功:---");
}catch (Exception e){
e.printStackTrace();
System.out.println("連接失敗");
}
}
}