connect(HOST, PORT); $conn = $redis->auth(PASSWORD); $conn = $redis->select(DATABASE); // 连接成功,返回$redis对象,连接失败,返回false. return ($conn === true) ? $redis : false; } catch (Exception $e) { return false; } } else { // 这里假设PHP-FPM在处理一个请求的时间内,Redis连接都是可用的. // 所以只在PHP-CLI下检查Redis连接的状态,进行断线重连. if (php_sapi_name() === 'cli') { try { // ping用于检查当前连接的状态,成功时返回+PONG,失败时抛出一个RedisException对象. // ping失败时警告: // Warning: Redis::ping(): connect() failed: Connection refused // var_dump('AAAAAAAAA', $redis); // echo 'Redis 连接状态' . $redis->ping() . PHP_EOL; @$redis->ping(); if (!$redis->ping()) { goto connect; //跳转到标签出继续执行连接操作 } } catch (Exception $e) { // 信息如 Connection lost 或 Redis server went away echo $e->getMessage(); echo 'Redis 连接失败 重新连接:' . PHP_EOL; // 断线重连 goto connect; } } return $redis; } } function sendConfig($topic,$config) { $server = '116.62.220.88'; $port = 1883; $clientId = 'local_mqtt_livestock_config_cli'; $username = 'rl517'; $password = "rlian2022"; $clean_session = false; $connectionSettings = new ConnectionSettings(); $connectionSettings = $connectionSettings ->setUsername($username) ->setPassword($password) ->setKeepAliveInterval(60) // Last Will 设置 // ->setLastWillTopic('emqx/test/last-will') // ->setLastWillMessage('client disconnect') // ->setLastWillQualityOfService(1) ; $mqtt = new MqttClient($server, $port, $clientId); $mqtt->connect($connectionSettings, $clean_session); echo 'connect OK'.PHP_EOL; echo 'topic:'.$topic.PHP_EOL; echo 'config:'.$config.PHP_EOL; $res=$mqtt->publish( $topic, $config, 1 ); echo 'publish end'.PHP_EOL; $mqtt->loop(true,true); $mqtt->disconnect(); return $res; } function updateSendResult($msgid){ // $conn = new mysqli('rm-bp1h3uqkzy66ckt8yro.mysql.rds.aliyuncs.com', 'dev', '711e7D69f9d0c3f1', 'smart_livestock'); $conn = new mysqli('127.0.0.1', 'root', 'root', 'smart_livestock'); if ($conn -> connect_errno) { printf("Connect failed: %s\n", $conn->connect_error); exit(); } $sql = "UPDATE send_config_log SET result='1' WHERE id=".$msgid; if ($conn->query($sql) === TRUE) { echo "send_config_log update success"; } else { echo "更新失败: " . $conn->error; } } while (1) { $jsonData= app_redis()->rpop("rlsta_door_black_list"); if(!$jsonData){ sleep(3); continue; } $data=json_decode($jsonData,true); var_dump($data); $topic="rlsta/door/bklist/set/".$data['device_id']; // { // "msgid": "id123", // "bkList": { // "action": "add", //add or del // "list":["lableid1","lableid2","lableid3"] // // } // "time": 1724145895 // } $config=$data['config']; $config_json=json_encode($config); // if(isset($data['msgid'])){ // updateSendResult($data['msgid']); // } // var_dump($config_json); sendConfig($topic,$config_json); }