使用PHP開發實作百度文心一言API介面的即時監控與效能最佳化
<?php $url = 'https://v1.hitokoto.cn/'; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); curl_exec($curl); $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); $time_cost = curl_getinfo($curl, CURLINFO_TOTAL_TIME); if($status_code == 200) { echo "接口正常,平均响应时间为:" . $time_cost . "秒"; } else { echo "接口异常,状态码为:" . $status_code; } curl_close($curl); ?>
<?php $redis = new Redis(); $redis->connect('127.0.0.1', 6379); if($redis->exists('hitokoto')){ $result = $redis->get('hitokoto'); echo "从缓存中获取结果:" . $result; } else { $url = 'https://v1.hitokoto.cn/'; $curl = curl_init($url); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 10); $result = curl_exec($curl); $status_code = curl_getinfo($curl, CURLINFO_HTTP_CODE); if($status_code == 200) { echo "接口正常,结果为:" . $result; $redis->setex('hitokoto', 3600, $result); // 设置缓存时间为1小时 } else { echo "接口异常,状态码为:" . $status_code; } curl_close($curl); } ?>
以上是使用PHP開發實現百度文心一言API介面的即時監控與效能最佳化的詳細內容。更多資訊請關注PHP中文網其他相關文章!