文章目录
-
- 在当今电商蓬勃发展的时代,一个典型的WordPress电商网站可能管理着数万甚至数十万种商品数据。当这些数据需要频繁访问时,数据库查询会成为系统性能的主要瓶颈。根据我们的性能测试,一个拥有10万商品数据的WordPress网站在高并发访问下,未经优化的数据库查询可能导致页面加载时间超过5秒,严重影响用户体验和转化率。 WordPress作为全球最流行的内容管理系统,其灵活的架构为我们提供了多种缓存解决方案。本文将深入探讨基于WordPress开发环境下,处理海量商品数据缓存的四个高效秘诀,帮助开发者和行业新人构建高性能的电商平台。
-
- 在WordPress中,有效的缓存策略应该包含多个层级: 对象缓存层:存储PHP对象,避免重复查询 页面片段缓存层:缓存页面中的动态部分 全页面缓存层:缓存完整HTML输出 CDN缓存层:分布式边缘缓存
- WordPress内置了对象缓存系统,我们可以通过WP_Object_Cache类进行扩展。以下是一个商品数据对象缓存的完整实现示例: /** * 商品数据缓存管理器 */ class Product_Cache_Manager { private $cache_group = 'products'; private $cache_expiration = 3600; // 1小时 /** * 获取商品数据(带缓存) */ public function get_product($product_id) { $cache_key = 'product_' . $product_id; $product = wp_cache_get($cache_key, $this->cache_group); if (false === $product) { // 缓存未命中,从数据库获取 $product = $this->fetch_product_from_db($product_id); if ($product) { // 将数据存入缓存 wp_cache_set($cache_key, $product, $this->cache_group, $this->cache_expiration); // 同时缓存商品ID到列表的映射 $this->cache_product_references($product); } } return $product; } /** * 批量获取商品数据(优化版本) */ public function get_products_batch($product_ids) { $products = []; $uncached_ids = []; // 第一步:尝试从缓存获取所有商品 foreach ($product_ids as $id) { $cache_key = 'product_' . $id; $product = wp_cache_get($cache_key, $this->cache_group); if (false !== $product) { $products[$id] = $product; } else { $uncached_ids[] = $id; } } // 第二步:批量查询未缓存的数据 if (!empty($uncached_ids)) { $uncached_products = $this->fetch_products_batch_from_db($uncached_ids); foreach ($uncached_products as $product) { $cache_key = 'product_' . $product->ID; wp_cache_set($cache_key, $product, $this->cache_group, $this->cache_expiration); $products[$product->ID] = $product; // 缓存引用关系 $this->cache_product_references($product); } } return $products; } /** * 缓存商品引用关系(用于分类、标签等查询) */ private function cache_product_references($product) { // 缓存商品分类关系 $categories = wp_get_post_terms($product->ID, 'product_cat', ['fields' => 'ids']); foreach ($categories as $cat_id) { $cat_cache_key = 'category_products_' . $cat_id; $cat_products = wp_cache_get($cat_cache_key, $this->cache_group); if (false === $cat_products) { $cat_products = []; } if (!in_array($product->ID, $cat_products)) { $cat_products[] = $product->ID; wp_cache_set($cat_cache_key, $cat_products, $this->cache_group, $this->cache_expiration); } } } /** * 清除商品缓存 */ public function clear_product_cache($product_id) { $cache_key = 'product_' . $product_id; wp_cache_delete($cache_key, $this->cache_group); // 清除相关分类缓存 $categories = wp_get_post_terms($product_id, 'product_cat', ['fields' => 'ids']); foreach ($categories as $cat_id) { wp_cache_delete('category_products_' . $cat_id, $this->cache_group); } // 清除标签缓存 $tags = wp_get_post_terms($product_id, 'product_tag', ['fields' => 'ids']); foreach ($tags as $tag_id) { wp_cache_delete('tag_products_' . $tag_id, $this->cache_group); } } }
- 对于海量商品数据,合理的缓存分组可以显著提高缓存效率: /** * 高级缓存分组策略 */ class Advanced_Cache_Strategy { // 按商品类型分组 const GROUP_SIMPLE = 'products_simple'; const GROUP_VARIABLE = 'products_variable'; const GROUP_GROUPED = 'products_grouped'; // 按业务场景分组 const GROUP_FEATURED = 'products_featured'; const GROUP_ON_SALE = 'products_onsale'; const GROUP_NEW_ARRIVALS = 'products_new'; /** * 根据商品类型获取缓存组 */ public function get_cache_group_by_product_type($product_type) { $group_map = [ 'simple' => self::GROUP_SIMPLE, 'variable' => self::GROUP_VARIABLE, 'grouped' => self::GROUP_GROUPED, 'external' => 'products_external', ]; return $group_map[$product_type] ?? 'products_default'; } /** * 智能缓存过期策略 */ public function get_cache_expiration($product_type, $product_status) { // 热门商品缓存时间更长 if ($this->is_hot_product($product_id)) { return 7200; // 2小时 } // 普通商品 if ('publish' === $product_status) { return 3600; // 1小时 } // 草稿或待审核商品 return 600; // 10分钟 } }
-
- 对于需要处理海量数据的电商网站,内存缓存比文件缓存更高效。Redis是理想的选择: /** * Redis缓存集成 */ class Redis_Cache_Integration { private $redis; private $prefix = 'wp_product_'; public function __construct() { if (class_exists('Redis')) { $this->redis = new Redis(); try { $this->redis->connect('127.0.0.1', 6379, 2.5); $this->redis->setOption(Redis::OPT_PREFIX, $this->prefix); // 启用压缩以节省内存 $this->redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF); } catch (Exception $e) { error_log('Redis连接失败: ' . $e->getMessage()); $this->redis = null; } } } /** * 存储商品数据到Redis */ public function cache_product($product_id, $product_data, $expire = 3600) { if (!$this->redis) return false; $key = 'product:' . $product_id; // 序列化数据 $serialized_data = serialize($product_data); // 使用管道提高批量操作性能 $pipe = $this->redis->pipeline(); $pipe->set($key, $serialized_data); $pipe->expire($key, $expire); // 添加到商品ID索引 $pipe->sAdd('product_index', $product_id); $responses = $pipe->exec(); return $responses[0]; } /** * 批量缓存商品数据 */ public function cache_products_batch($products) { if (!$this->redis || empty($products)) return false; $pipe = $this->redis->pipeline(); foreach ($products as $product) { $key = 'product:' . $product['id']; $serialized_data = serialize($product); $pipe->set($key, $serialized_data); $pipe->expire($key, 3600); $pipe->sAdd('product_index', $product['id']); } return $pipe->exec(); } /** * 获取商品数据 */ public function get_product($product_id) { if (!$this->redis) return false; $key = 'product:' . $product_id; $data = $this->redis->get($key); if ($data) { return unserialize($data); } return false; } /** * 搜索商品(使用Redis集合操作) */ public function search_products($category_id = null, $tag_id = null, $limit = 50) { if (!$this->redis) return []; $result_key = 'search_result:' . md5(serialize(func_get_args())); // 检查是否有缓存结果 $cached_result = $this->redis->get($result_key); if ($cached_result) { return unserialize($cached_result); } // 构建搜索键 $search_keys = ['product_index']; if ($category_id) { $search_keys[] = 'category:' . $category_id; } if ($tag_id) { $search_keys[] = 'tag:' . $tag_id; } // 使用SINTER进行集合交集运算 if (count($search_keys) > 1) { $product_ids = $this->redis->sInter(...$search_keys); } else { $product_ids = $this->redis->sMembers('product_index'); } // 限制结果数量 $product_ids = array_slice($product_ids, 0, $limit); // 批量获取商品数据 $products = []; if (!empty($product_ids)) { $pipe = $this->redis->pipeline(); foreach ($product_ids as $id) { $pipe->get('product:' . $id); } $product_data = $pipe->exec(); foreach ($product_data as $data) { if ($data) { $products[] = unserialize($data); } } } // 缓存搜索结果(短期缓存) $this->redis->setex($result_key, 300, serialize($products)); return $products; } }
- /** * Redis内存优化配置 */ class Redis_Memory_Optimizer { /** * 配置Redis内存优化 */ public function configure_memory_optimization() { $config = [ // 启用内存淘汰策略 'maxmemory' => '2gb', 'maxmemory-policy' => 'allkeys-lru', // 哈希数据结构优化 'hash-max-ziplist-entries' => 512, 'hash-max-ziplist-value' => 64, // 列表优化 'list-max-ziplist-size' => -2, // 集合优化 'set-max-intset-entries' => 512, ]; return $config; } /** * 商品数据结构优化 */ public function optimize_product_structure($product_data) { // 移除不需要缓存的字段 unset( $product_data['post_content'], $product_data['post_excerpt'], $product_data['to_ping'], $product_data['pinged'] ); // 压缩长文本字段 if (isset($product_data['description'])) { $product_data['description'] = $this->compress_text($product_data['description']); } // 将数组转换为更紧凑的结构 if (isset($product_data['attributes']) && is_array($product_data['attributes'])) { $product_data['attributes'] = $this->flatten_attributes($product_data['attributes']); } return $product_data; } /** * 监控Redis内存使用 */ public function monitor_memory_usage() { $redis = new Redis(); $redis->connect('127.0.0.1', 6379); $info = $redis->info('memory'); $memory_usage = [ 'used_memory' => $info['used_memory_human'] ?? 'N/A', 'used_memory_peak' => $info['used_memory_peak_human'] ?? 'N/A', 'memory_fragmentation_ratio' => $info['mem_fragmentation_ratio'] ?? 'N/A', 'keys_count' => $redis->dbSize(), ]; // 记录到监控系统 $this->log_memory_metrics($memory_usage); // 如果内存使用率超过80%,触发清理 if ($this->get_memory_usage_percentage() > 80) { $this->trigger_cache_cleanup(); } return $memory_usage; } }
-
- /** * 缓存预热管理器 */ class Cache_Warmup_Manager { private $batch_size = 100; /** * 预缓存热门商品 */ public function warmup_popular_products($limit = 1000) { global $wpdb; // 获取热门商品ID(基于销售数据) $popular_ids = $wpdb->get_col(" SELECT post_id FROM {$wpdb->prefix}wc_order_product_lookup WHERE date_created >= DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY post_id ORDER BY SUM(product_qty) DESC LIMIT {$limit} "); if (empty($popular_ids)) { // 如果没有销售数据,使用最近发布的商品 $popular_ids = $wpdb->get_col(" SELECT ID FROM {$wpdb->posts} WHERE post_type = 'product' AND post_status = 'publish' ORDER BY post_date DESC LIMIT {$limit} "); } // 分批预热缓存 $chunks = array_chunk($popular_ids, $this->batch_size); $results = []; foreach ($chunks as $chunk) { $results[] = $this->warmup_product_batch($chunk); } return $results; } /** * 预缓存分类页面 */ public function warmup_category_pages() { $categories = get_terms([ 'taxonomy' => 'product_cat', 'hide_empty' => true, 'number' => 50, // 限制数量,避免过度预热 ]); foreach ($categories as $category) { $this->warmup_category_products($category->term_id); } } /** * 定时预热任务 */ public function schedule_warmup_tasks() { if (!wp_next_scheduled('product_cache_warmup')) { wp_schedule_event(time(), 'hourly', 'product_cache_warmup'); } add_action('product_cache_warmup', [$this, 'run_scheduled_warmup']); } /** * 执行定时预热 */ public function run_scheduled_warmup() { // 预热前1000个热门商品 $this->warmup_popular_products(1000); // 预热主要分类 $this->warmup_category_pages(); // 预热首页和重要页面 $this->warmup_critical_pages(); } /** * 智能缓存更新策略 */ public function smart_cache_refresh($product_id, $change_type) { $product = wc_get_product($product_id); if (!$product) { return; } // 根据变更类型决定缓存策略 $refresh_strategies = [ 'price_change' => [ 'action' => 'update', 'priority' => 'high', 'delay' => 0, // 立即更新 ], 'stock_change' => [ 'action' => 'update', 'priority' => 'high', 'delay' => 0, ], 'description_update' => [ 'action' => 'update', 'priority' => 'medium', 'delay' => 300, // 5分钟后更新 ], 'seo_update' => [ 'action' => 'update', 'priority' => 'low', 'delay' => 1800, // 30分钟后更新 ], ]; $strategy = $refresh_strategies[$change_type] ?? $refresh_strategies['description_update']; if ($strategy['delay'] > 0) { // 延迟更新 wp_schedule_single_event( time() + $strategy['delay'], 'delayed_cache_refresh', [$product_id, $change_type] ); } else { // 立即更新 $this->refresh_product_cache($product_id); } } }
- /** * 用户行为感知的缓存策略 */ Behavior_Aware_Cache { private $user_segments = []; private $cache_variations = []; /** * 根据用户行为动态调整缓存策略 */ public function __construct() { $this->identify_user_segment(); $this->initialize_cache_variations(); } /** * 识别用户分群 */ private function identify_user_segment() { // 基于用户行为数据分群 $user_id = get_current_user_id(); if ($user_id === 0) { $this->user_segments = ['guest', 'new_visitor']; return; } // 获取用户历史行为 $purchase_count = $this->get_user_purchase_count($user_id); $browse_history = $this->get_user_browse_history($user_id); $last_visit = $this->get_user_last_visit($user_id); // 定义用户分群 $segments = []; if ($purchase_count > 5) { $segments[] = 'frequent_buyer'; } elseif ($purchase_count > 0) { $segments[] = 'occasional_buyer'; } else { $segments[] = 'window_shopper'; } // 基于浏览历史 if (count($browse_history) > 20) { $segments[] = 'heavy_browser'; } // 基于最近访问 $days_since_last_visit = (time() - $last_visit) / DAY_IN_SECONDS; if ($days_since_last_visit < 1) { $segments[] = 'active_today'; } elseif ($days_since_last_visit < 7) { $segments[] = 'active_week'; } $this->user_segments = array_unique($segments); } /** * 初始化缓存变体 */ private function initialize_cache_variations() { $this->cache_variations = [ 'guest' => [ 'cache_ttl' => 300, // 5分钟 'personalized' => false, 'show_prices' => true, 'show_recommendations' => true, ], 'frequent_buyer' => [ 'cache_ttl' => 1800, // 30分钟 'personalized' => true, 'show_prices' => true, 'show_recommendations' => true, 'show_exclusive_offers' => true, ], 'window_shopper' => [ 'cache_ttl' => 900, // 15分钟 'personalized' => false, 'show_prices' => true, 'show_recommendations' => false, ], 'heavy_browser' => [ 'cache_ttl' => 600, // 10分钟 'personalized' => true, 'show_prices' => true, 'show_recommendations' => true, 'cache_individual_components' => true, ], ]; } /** * 获取用户特定的缓存键 */ public function get_user_specific_cache_key($base_key) { $user_segment_key = implode('_', $this->user_segments); $user_id = get_current_user_id(); if ($user_id > 0) { return sprintf('%s_user%d_segment%s', $base_key, $user_id, md5($user_segment_key)); } return sprintf('%s_guest_%s', $base_key, md5($user_segment_key)); } /** * 获取用户特定的缓存TTL */ public function get_user_specific_ttl($default_ttl = 3600) { foreach ($this->user_segments as $segment) { if (isset($this->cache_variations[$segment]['cache_ttl'])) { return $this->cache_variations[$segment]['cache_ttl']; } } return $default_ttl; } /** * 渲染个性化商品列表 */ public function render_personalized_product_list($args = []) { $cache_key = $this->get_user_specific_cache_key('personalized_products'); $cached_data = wp_cache_get($cache_key, 'user_products'); if (false !== $cached_data) { return $cached_data; } // 根据用户分群获取个性化商品 $products = $this->fetch_personalized_products($args); // 缓存结果 $ttl = $this->get_user_specific_ttl(); wp_cache_set($cache_key, $products, 'user_products', $ttl); return $products; } /** * 获取个性化商品数据 */ private function fetch_personalized_products($args) { $user_id = get_current_user_id(); $products = []; // 根据用户分群应用不同策略 if (in_array('frequent_buyer', $this->user_segments)) { // 频繁购买者:显示互补商品和升级选项 $products = $this->get_complementary_products($user_id); } elseif (in_array('window_shopper', $this->user_segments)) { // 浏览者:显示热门和促销商品 $products = $this->get_popular_and_on_sale_products(); } else { // 默认:显示精选商品 $products = $this->get_featured_products(); } // 应用用户特定的过滤 $products = $this->apply_user_filters($products); return $products; } }
-
- /** * 缓存性能监控器 */ class Cache_Performance_Monitor { private $metrics = []; private $alert_thresholds = []; public function __construct() { $this->initialize_metrics(); $this->set_alert_thresholds(); } /** * 初始化监控指标 */ private function initialize_metrics() { $this->metrics = [ 'hit_rate' => [ 'current' => 0, 'history' => [], 'max_samples' => 100, ], 'response_time' => [ 'current' => 0, 'history' => [], 'max_samples' => 100, ], 'memory_usage' => [ 'current' => 0, 'history' => [], 'max_samples' => 100, ], 'cache_size' => [ 'current' => 0, 'history' => [], 'max_samples' => 100, ], ]; } /** * 设置告警阈值 */ private function set_alert_thresholds() { $this->alert_thresholds = [ 'hit_rate' => [ 'warning' => 0.7, // 命中率低于70%警告 'critical' => 0.5, // 命中率低于50%严重 ], 'response_time' => [ 'warning' => 100, // 响应时间超过100ms警告 'critical' => 500, // 响应时间超过500ms严重 ], 'memory_usage' => [ 'warning' => 0.8, // 内存使用超过80%警告 'critical' => 0.9, // 内存使用超过90%严重 ], ]; } /** * 记录缓存操作 */ public function log_cache_operation($operation, $key, $hit, $response_time) { $timestamp = microtime(true); // 更新命中率统计 $this->update_hit_rate($hit); // 记录响应时间 $this->record_response_time($response_time); // 记录操作详情 $log_entry = [ 'timestamp' => $timestamp, 'operation' => $operation, 'key' => $key, 'hit' => $hit, 'response_time' => $response_time, ]; $this->save_operation_log($log_entry); // 检查是否需要告警 $this->check_alerts(); } /** * 更新命中率统计 */ private function update_hit_rate($hit) { $metric = &$this->metrics['hit_rate']; // 简化计算:维护最近100次操作的命中率 $metric['history'][] = $hit ? 1 : 0; if (count($metric['history']) > $metric['max_samples']) { array_shift($metric['history']); } $hit_count = array_sum($metric['history']); $total_count = count($metric['history']); $metric['current'] = $total_count > 0 ? $hit_count / $total_count : 0; } /** * 生成性能报告 */ public function generate_performance_report() { $report = [ 'summary' => [ 'hit_rate' => round($this->metrics['hit_rate']['current'] * 100, 2) . '%', 'avg_response_time' => round(array_sum($this->metrics['response_time']['history']) / max(1, count($this->metrics['response_time']['history'])), 2) . 'ms', 'current_memory_usage' => $this->format_bytes($this->metrics['memory_usage']['current']), ], 'detailed_metrics' => $this->metrics, 'recommendations' => $this->generate_recommendations(), 'timestamp' => current_time('mysql'), ]; // 保存报告 $this->save_performance_report($report); return $report; } /** * 生成优化建议 */ private function generate_recommendations() { $recommendations = []; // 基于命中率的建议 $hit_rate = $this->metrics['hit_rate']['current']; if ($hit_rate < 0.5) { $recommendations[] = [ 'priority' => 'high', 'category' => 'hit_rate', 'message' => '缓存命中率过低,建议增加缓存容量或优化缓存键设计', 'action' => 'review_cache_keys_and_expiration', ]; } elseif ($hit_rate < 0.7) { $recommendations[] = [ 'priority' => 'medium', 'category' => 'hit_rate', 'message' => '缓存命中率偏低,考虑预热热门数据', 'action' => 'implement_cache_warmup', ]; } // 基于响应时间的建议 $avg_response_time = array_sum($this->metrics['response_time']['history']) / max(1, count($this->metrics['response_time']['history'])); if ($avg_response_time > 500) { $recommendations[] = [ 'priority' => 'high', 'category' => 'performance', 'message' => '缓存响应时间过长,建议检查Redis连接或考虑分片', 'action' => 'optimize_redis_configuration', ]; } return $recommendations; } /** * 自动化缓存清理 */ public function automated_cache_cleanup() { $stats = $this->get_cache_stats(); // 如果缓存大小超过阈值,执行清理 if ($stats['memory_usage_ratio'] > 0.8) { $this->execute_intelligent_cleanup(); } // 清理过期缓存 $this->clean_expired_entries(); // 清理低价值缓存 $this->clean_low_value_entries(); } /** * 智能缓存清理策略 */ private function execute_intelligent_cleanup() { global $wpdb; // 获取缓存访问频率数据 $low_access_keys = $wpdb->get_col(" SELECT cache_key FROM {$wpdb->prefix}cache_metrics WHERE last_access < DATE_SUB(NOW(), INTERVAL 7 DAY) AND access_count < 10 ORDER BY last_access ASC LIMIT 1000 "); // 清理低访问频率的缓存 foreach ($low_access_keys as $key) { wp_cache_delete($key, 'default'); } // 记录清理操作 $this->log_cleanup_operation(count($low_access_keys)); } }
- /** * 缓存健康检查系统 */ class Cache_Health_Checker { private $check_interval = 300; // 5分钟 private $last_check_time = 0; /** * 执行健康检查 */ public function perform_health_check() { $current_time = time(); // 检查执行频率 if (($current_time - $this->last_check_time) < $this->check_interval) { return; } $this->last_check_time = $current_time; $health_status = [ 'timestamp' => $current_time, 'checks' => [], 'overall_status' => 'healthy', ]; // 执行各项检查 $checks = [ 'redis_connection' => $this->check_redis_connection(), 'memory_usage' => $this->check_memory_usage(), 'hit_rate' => $this->check_hit_rate(), 'response_time' => $this->check_response_time(), 'cache_integrity' => $this->check_cache_integrity(), ]; foreach ($checks as $check_name => $result) { $health_status['checks'][$check_name] = $result; if ($result['status'] === 'critical') { $health_status['overall_status'] = 'critical'; } elseif ($result['status'] === 'warning' && $health_status['overall_status'] === 'healthy') { $health_status['overall_status'] = 'warning'; } } // 发送告警(如果需要) if ($health_status['overall_status'] !== 'healthy') { $this->send_health_alert($health_status); } // 记录健康状态 $this->log_health_status($health_status); return $health_status; } /** * 检查Redis连接 */ private function check_redis_connection() { try { $redis = new Redis(); $connected = $redis->connect('127.0.0.1', 6379, 1); if ($connected) { $ping = $redis->ping(); $redis->close(); return [ 'status' => 'healthy', 'message' => 'Redis连接正常', 'details' => ['ping_response' => $ping], ]; } } catch (Exception $e) { return [ 'status' => 'critical', 'message' => 'Redis连接失败', 'details' => ['error' => $e->getMessage()], ]; } return [ 'status' => 'critical', 'message' => '无法连接到Redis', 'details' => [], ]; } /** * 检查缓存命中率 */ private function check_hit_rate() { global $wpdb; $hit_rate = $wpdb->get_var(" SELECT SUM(CASE WHEN hit = 1 THEN 1 ELSE 0 END) / COUNT(*) as hit_rate FROM {$wpdb->prefix}cache_metrics WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 HOUR) "); if ($hit_rate === null) { $hit_rate = 0; } if ($hit_rate < 0.5) { $status = 'critical'; $message = '缓存命中率过低'; } elseif ($hit_rate < 0.7) { $status = 'warning'; $message = '缓存命中率偏低'; } else { $status = 'healthy'; $message = '缓存命中率正常'; } return [ 'status' => $status, 'message' => $message, 'details' => ['hit_rate' => round($hit_rate * 100, 2) . '%'], ]; } /** * 检查缓存完整性 */ private function check_cache_integrity() { // 抽样检查缓存数据的完整性 $sample_keys = $this->get_cache_sample_keys(50); $corrupted_count = 0; foreach ($sample_keys as $key) { $data = wp_cache_get($key, 'default'); if ($data !== false) { // 验证数据完整性 if (!$this->validate_cache_data($data)) { $corrupted_count++; // 自动修复损坏的缓存 wp_cache_delete($key, 'default'); } } } $corruption_rate = count($sample_keys) > 0 ? $corrupted_count / count($sample_keys) : 0; if ($corruption_rate > 0.1) { $status = 'critical'; $message = '缓存数据损坏率过高'; } elseif ($corruption_rate > 0.01) { $status = 'warning'; $message = '发现缓存数据损坏'; } else { $status = 'healthy'; $message = '缓存数据完整性良好'; } return [ 'status' => $status, 'message' => $message, 'details' => [ 'sample_size' => count($sample_keys), 'corrupted_count' => $corrupted_count, 'corruption_rate' => round($corruption_rate * 100, 2) . '%', ], ]; } /** * 发送健康告警 */
在当今电商蓬勃发展的时代,一个典型的WordPress电商网站可能管理着数万甚至数十万种商品数据。当这些数据需要频繁访问时,数据库查询会成为系统性能的主要瓶颈。根据我们的性能测试,一个拥有10万商品数据的WordPress网站在高并发访问下,未经优化的数据库查询可能导致页面加载时间超过5秒,严重影响用户体验和转化率。
WordPress作为全球最流行的内容管理系统,其灵活的架构为我们提供了多种缓存解决方案。本文将深入探讨基于WordPress开发环境下,处理海量商品数据缓存的四个高效秘诀,帮助开发者和行业新人构建高性能的电商平台。
在WordPress中,有效的缓存策略应该包含多个层级:
- 对象缓存层:存储PHP对象,避免重复查询
- 页面片段缓存层:缓存页面中的动态部分
- 全页面缓存层:缓存完整HTML输出
- CDN缓存层:分布式边缘缓存
WordPress内置了对象缓存系统,我们可以通过WP_Object_Cache类进行扩展。以下是一个商品数据对象缓存的完整实现示例:
/**
* 商品数据缓存管理器
*/
class Product_Cache_Manager {
private $cache_group = 'products';
private $cache_expiration = 3600; // 1小时
/**
* 获取商品数据(带缓存)
*/
public function get_product($product_id) {
$cache_key = 'product_' . $product_id;
$product = wp_cache_get($cache_key, $this->cache_group);
if (false === $product) {
// 缓存未命中,从数据库获取
$product = $this->fetch_product_from_db($product_id);
if ($product) {
// 将数据存入缓存
wp_cache_set($cache_key, $product, $this->cache_group, $this->cache_expiration);
// 同时缓存商品ID到列表的映射
$this->cache_product_references($product);
}
}
return $product;
}
/**
* 批量获取商品数据(优化版本)
*/
public function get_products_batch($product_ids) {
$products = [];
$uncached_ids = [];
// 第一步:尝试从缓存获取所有商品
foreach ($product_ids as $id) {
$cache_key = 'product_' . $id;
$product = wp_cache_get($cache_key, $this->cache_group);
if (false !== $product) {
$products[$id] = $product;
} else {
$uncached_ids[] = $id;
}
}
// 第二步:批量查询未缓存的数据
if (!empty($uncached_ids)) {
$uncached_products = $this->fetch_products_batch_from_db($uncached_ids);
foreach ($uncached_products as $product) {
$cache_key = 'product_' . $product->ID;
wp_cache_set($cache_key, $product, $this->cache_group, $this->cache_expiration);
$products[$product->ID] = $product;
// 缓存引用关系
$this->cache_product_references($product);
}
}
return $products;
}
/**
* 缓存商品引用关系(用于分类、标签等查询)
*/
private function cache_product_references($product) {
// 缓存商品分类关系
$categories = wp_get_post_terms($product->ID, 'product_cat', ['fields' => 'ids']);
foreach ($categories as $cat_id) {
$cat_cache_key = 'category_products_' . $cat_id;
$cat_products = wp_cache_get($cat_cache_key, $this->cache_group);
if (false === $cat_products) {
$cat_products = [];
}
if (!in_array($product->ID, $cat_products)) {
$cat_products[] = $product->ID;
wp_cache_set($cat_cache_key, $cat_products, $this->cache_group, $this->cache_expiration);
}
}
}
/**
* 清除商品缓存
*/
public function clear_product_cache($product_id) {
$cache_key = 'product_' . $product_id;
wp_cache_delete($cache_key, $this->cache_group);
// 清除相关分类缓存
$categories = wp_get_post_terms($product_id, 'product_cat', ['fields' => 'ids']);
foreach ($categories as $cat_id) {
wp_cache_delete('category_products_' . $cat_id, $this->cache_group);
}
// 清除标签缓存
$tags = wp_get_post_terms($product_id, 'product_tag', ['fields' => 'ids']);
foreach ($tags as $tag_id) {
wp_cache_delete('tag_products_' . $tag_id, $this->cache_group);
}
}
}
对于海量商品数据,合理的缓存分组可以显著提高缓存效率:
/**
* 高级缓存分组策略
*/
class Advanced_Cache_Strategy {
// 按商品类型分组
const GROUP_SIMPLE = 'products_simple';
const GROUP_VARIABLE = 'products_variable';
const GROUP_GROUPED = 'products_grouped';
// 按业务场景分组
const GROUP_FEATURED = 'products_featured';
const GROUP_ON_SALE = 'products_onsale';
const GROUP_NEW_ARRIVALS = 'products_new';
/**
* 根据商品类型获取缓存组
*/
public function get_cache_group_by_product_type($product_type) {
$group_map = [
'simple' => self::GROUP_SIMPLE,
'variable' => self::GROUP_VARIABLE,
'grouped' => self::GROUP_GROUPED,
'external' => 'products_external',
];
return $group_map[$product_type] ?? 'products_default';
}
/**
* 智能缓存过期策略
*/
public function get_cache_expiration($product_type, $product_status) {
// 热门商品缓存时间更长
if ($this->is_hot_product($product_id)) {
return 7200; // 2小时
}
// 普通商品
if ('publish' === $product_status) {
return 3600; // 1小时
}
// 草稿或待审核商品
return 600; // 10分钟
}
}
对于需要处理海量数据的电商网站,内存缓存比文件缓存更高效。Redis是理想的选择:
/**
* Redis缓存集成
*/
class Redis_Cache_Integration {
private $redis;
private $prefix = 'wp_product_';
public function __construct() {
if (class_exists('Redis')) {
$this->redis = new Redis();
try {
$this->redis->connect('127.0.0.1', 6379, 2.5);
$this->redis->setOption(Redis::OPT_PREFIX, $this->prefix);
// 启用压缩以节省内存
$this->redis->setOption(Redis::OPT_COMPRESSION, Redis::COMPRESSION_LZF);
} catch (Exception $e) {
error_log('Redis连接失败: ' . $e->getMessage());
$this->redis = null;
}
}
}
/**
* 存储商品数据到Redis
*/
public function cache_product($product_id, $product_data, $expire = 3600) {
if (!$this->redis) return false;
$key = 'product:' . $product_id;
// 序列化数据
$serialized_data = serialize($product_data);
// 使用管道提高批量操作性能
$pipe = $this->redis->pipeline();
$pipe->set($key, $serialized_data);
$pipe->expire($key, $expire);
// 添加到商品ID索引
$pipe->sAdd('product_index', $product_id);
$responses = $pipe->exec();
return $responses[0];
}
/**
* 批量缓存商品数据
*/
public function cache_products_batch($products) {
if (!$this->redis || empty($products)) return false;
$pipe = $this->redis->pipeline();
foreach ($products as $product) {
$key = 'product:' . $product['id'];
$serialized_data = serialize($product);
$pipe->set($key, $serialized_data);
$pipe->expire($key, 3600);
$pipe->sAdd('product_index', $product['id']);
}
return $pipe->exec();
}
/**
* 获取商品数据
*/
public function get_product($product_id) {
if (!$this->redis) return false;
$key = 'product:' . $product_id;
$data = $this->redis->get($key);
if ($data) {
return unserialize($data);
}
return false;
}
/**
* 搜索商品(使用Redis集合操作)
*/
public function search_products($category_id = null, $tag_id = null, $limit = 50) {
if (!$this->redis) return [];
$result_key = 'search_result:' . md5(serialize(func_get_args()));
// 检查是否有缓存结果
$cached_result = $this->redis->get($result_key);
if ($cached_result) {
return unserialize($cached_result);
}
// 构建搜索键
$search_keys = ['product_index'];
if ($category_id) {
$search_keys[] = 'category:' . $category_id;
}
if ($tag_id) {
$search_keys[] = 'tag:' . $tag_id;
}
// 使用SINTER进行集合交集运算
if (count($search_keys) > 1) {
$product_ids = $this->redis->sInter(...$search_keys);
} else {
$product_ids = $this->redis->sMembers('product_index');
}
// 限制结果数量
$product_ids = array_slice($product_ids, 0, $limit);
// 批量获取商品数据
$products = [];
if (!empty($product_ids)) {
$pipe = $this->redis->pipeline();
foreach ($product_ids as $id) {
$pipe->get('product:' . $id);
}
$product_data = $pipe->exec();
foreach ($product_data as $data) {
if ($data) {
$products[] = unserialize($data);
}
}
}
// 缓存搜索结果(短期缓存)
$this->redis->setex($result_key, 300, serialize($products));
return $products;
}
}
/**
* Redis内存优化配置
*/
class Redis_Memory_Optimizer {
/**
* 配置Redis内存优化
*/
public function configure_memory_optimization() {
$config = [
// 启用内存淘汰策略
'maxmemory' => '2gb',
'maxmemory-policy' => 'allkeys-lru',
// 哈希数据结构优化
'hash-max-ziplist-entries' => 512,
'hash-max-ziplist-value' => 64,
// 列表优化
'list-max-ziplist-size' => -2,
// 集合优化
'set-max-intset-entries' => 512,
];
return $config;
}
/**
* 商品数据结构优化
*/
public function optimize_product_structure($product_data) {
// 移除不需要缓存的字段
unset(
$product_data['post_content'],
$product_data['post_excerpt'],
$product_data['to_ping'],
$product_data['pinged']
);
// 压缩长文本字段
if (isset($product_data['description'])) {
$product_data['description'] = $this->compress_text($product_data['description']);
}
// 将数组转换为更紧凑的结构
if (isset($product_data['attributes']) && is_array($product_data['attributes'])) {
$product_data['attributes'] = $this->flatten_attributes($product_data['attributes']);
}
return $product_data;
}
/**
* 监控Redis内存使用
*/
public function monitor_memory_usage() {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$info = $redis->info('memory');
$memory_usage = [
'used_memory' => $info['used_memory_human'] ?? 'N/A',
'used_memory_peak' => $info['used_memory_peak_human'] ?? 'N/A',
'memory_fragmentation_ratio' => $info['mem_fragmentation_ratio'] ?? 'N/A',
'keys_count' => $redis->dbSize(),
];
// 记录到监控系统
$this->log_memory_metrics($memory_usage);
// 如果内存使用率超过80%,触发清理
if ($this->get_memory_usage_percentage() > 80) {
$this->trigger_cache_cleanup();
}
return $memory_usage;
}
}
/**
* Redis内存优化配置
*/
class Redis_Memory_Optimizer {
/**
* 配置Redis内存优化
*/
public function configure_memory_optimization() {
$config = [
// 启用内存淘汰策略
'maxmemory' => '2gb',
'maxmemory-policy' => 'allkeys-lru',
// 哈希数据结构优化
'hash-max-ziplist-entries' => 512,
'hash-max-ziplist-value' => 64,
// 列表优化
'list-max-ziplist-size' => -2,
// 集合优化
'set-max-intset-entries' => 512,
];
return $config;
}
/**
* 商品数据结构优化
*/
public function optimize_product_structure($product_data) {
// 移除不需要缓存的字段
unset(
$product_data['post_content'],
$product_data['post_excerpt'],
$product_data['to_ping'],
$product_data['pinged']
);
// 压缩长文本字段
if (isset($product_data['description'])) {
$product_data['description'] = $this->compress_text($product_data['description']);
}
// 将数组转换为更紧凑的结构
if (isset($product_data['attributes']) && is_array($product_data['attributes'])) {
$product_data['attributes'] = $this->flatten_attributes($product_data['attributes']);
}
return $product_data;
}
/**
* 监控Redis内存使用
*/
public function monitor_memory_usage() {
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$info = $redis->info('memory');
$memory_usage = [
'used_memory' => $info['used_memory_human'] ?? 'N/A',
'used_memory_peak' => $info['used_memory_peak_human'] ?? 'N/A',
'memory_fragmentation_ratio' => $info['mem_fragmentation_ratio'] ?? 'N/A',
'keys_count' => $redis->dbSize(),
];
// 记录到监控系统
$this->log_memory_metrics($memory_usage);
// 如果内存使用率超过80%,触发清理
if ($this->get_memory_usage_percentage() > 80) {
$this->trigger_cache_cleanup();
}
return $memory_usage;
}
}
/**
* 缓存预热管理器
*/
class Cache_Warmup_Manager {
private $batch_size = 100;
/**
* 预缓存热门商品
*/
public function warmup_popular_products($limit = 1000) {
global $wpdb;
// 获取热门商品ID(基于销售数据)
$popular_ids = $wpdb->get_col("
SELECT post_id
FROM {$wpdb->prefix}wc_order_product_lookup
WHERE date_created >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY post_id
ORDER BY SUM(product_qty) DESC
LIMIT {$limit}
");
if (empty($popular_ids)) {
// 如果没有销售数据,使用最近发布的商品
$popular_ids = $wpdb->get_col("
SELECT ID
FROM {$wpdb->posts}
WHERE post_type = 'product'
AND post_status = 'publish'
ORDER BY post_date DESC
LIMIT {$limit}
");
}
// 分批预热缓存
$chunks = array_chunk($popular_ids, $this->batch_size);
$results = [];
foreach ($chunks as $chunk) {
$results[] = $this->warmup_product_batch($chunk);
}
return $results;
}
/**
* 预缓存分类页面
*/
public function warmup_category_pages() {
$categories = get_terms([
'taxonomy' => 'product_cat',
'hide_empty' => true,
'number' => 50, // 限制数量,避免过度预热
]);
foreach ($categories as $category) {
$this->warmup_category_products($category->term_id);
}
}
/**
* 定时预热任务
*/
public function schedule_warmup_tasks() {
if (!wp_next_scheduled('product_cache_warmup')) {
wp_schedule_event(time(), 'hourly', 'product_cache_warmup');
}
add_action('product_cache_warmup', [$this, 'run_scheduled_warmup']);
}
/**
* 执行定时预热
*/
public function run_scheduled_warmup() {
// 预热前1000个热门商品
$this->warmup_popular_products(1000);
// 预热主要分类
$this->warmup_category_pages();
// 预热首页和重要页面
$this->warmup_critical_pages();
}
/**
* 智能缓存更新策略
*/
public function smart_cache_refresh($product_id, $change_type) {
$product = wc_get_product($product_id);
if (!$product) {
return;
}
// 根据变更类型决定缓存策略
$refresh_strategies = [
'price_change' => [
'action' => 'update',
'priority' => 'high',
'delay' => 0, // 立即更新
],
'stock_change' => [
'action' => 'update',
'priority' => 'high',
'delay' => 0,
],
'description_update' => [
'action' => 'update',
'priority' => 'medium',
'delay' => 300, // 5分钟后更新
],
'seo_update' => [
'action' => 'update',
'priority' => 'low',
'delay' => 1800, // 30分钟后更新
],
];
$strategy = $refresh_strategies[$change_type] ?? $refresh_strategies['description_update'];
if ($strategy['delay'] > 0) {
// 延迟更新
wp_schedule_single_event(
time() + $strategy['delay'],
'delayed_cache_refresh',
[$product_id, $change_type]
);
} else {
// 立即更新
$this->refresh_product_cache($product_id);
}
}
}
/**
* 缓存预热管理器
*/
class Cache_Warmup_Manager {
private $batch_size = 100;
/**
* 预缓存热门商品
*/
public function warmup_popular_products($limit = 1000) {
global $wpdb;
// 获取热门商品ID(基于销售数据)
$popular_ids = $wpdb->get_col("
SELECT post_id
FROM {$wpdb->prefix}wc_order_product_lookup
WHERE date_created >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY post_id
ORDER BY SUM(product_qty) DESC
LIMIT {$limit}
");
if (empty($popular_ids)) {
// 如果没有销售数据,使用最近发布的商品
$popular_ids = $wpdb->get_col("
SELECT ID
FROM {$wpdb->posts}
WHERE post_type = 'product'
AND post_status = 'publish'
ORDER BY post_date DESC
LIMIT {$limit}
");
}
// 分批预热缓存
$chunks = array_chunk($popular_ids, $this->batch_size);
$results = [];
foreach ($chunks as $chunk) {
$results[] = $this->warmup_product_batch($chunk);
}
return $results;
}
/**
* 预缓存分类页面
*/
public function warmup_category_pages() {
$categories = get_terms([
'taxonomy' => 'product_cat',
'hide_empty' => true,
'number' => 50, // 限制数量,避免过度预热
]);
foreach ($categories as $category) {
$this->warmup_category_products($category->term_id);
}
}
/**
* 定时预热任务
*/
public function schedule_warmup_tasks() {
if (!wp_next_scheduled('product_cache_warmup')) {
wp_schedule_event(time(), 'hourly', 'product_cache_warmup');
}
add_action('product_cache_warmup', [$this, 'run_scheduled_warmup']);
}
/**
* 执行定时预热
*/
public function run_scheduled_warmup() {
// 预热前1000个热门商品
$this->warmup_popular_products(1000);
// 预热主要分类
$this->warmup_category_pages();
// 预热首页和重要页面
$this->warmup_critical_pages();
}
/**
* 智能缓存更新策略
*/
public function smart_cache_refresh($product_id, $change_type) {
$product = wc_get_product($product_id);
if (!$product) {
return;
}
// 根据变更类型决定缓存策略
$refresh_strategies = [
'price_change' => [
'action' => 'update',
'priority' => 'high',
'delay' => 0, // 立即更新
],
'stock_change' => [
'action' => 'update',
'priority' => 'high',
'delay' => 0,
],
'description_update' => [
'action' => 'update',
'priority' => 'medium',
'delay' => 300, // 5分钟后更新
],
'seo_update' => [
'action' => 'update',
'priority' => 'low',
'delay' => 1800, // 30分钟后更新
],
];
$strategy = $refresh_strategies[$change_type] ?? $refresh_strategies['description_update'];
if ($strategy['delay'] > 0) {
// 延迟更新
wp_schedule_single_event(
time() + $strategy['delay'],
'delayed_cache_refresh',
[$product_id, $change_type]
);
} else {
// 立即更新
$this->refresh_product_cache($product_id);
}
}
}
/**
* 用户行为感知的缓存策略
*/
/**
* 用户行为感知的缓存策略
*/
Behavior_Aware_Cache {
private $user_segments = [];
private $cache_variations = [];
/**
* 根据用户行为动态调整缓存策略
*/
public function __construct() {
$this->identify_user_segment();
$this->initialize_cache_variations();
}
/**
* 识别用户分群
*/
private function identify_user_segment() {
// 基于用户行为数据分群
$user_id = get_current_user_id();
if ($user_id === 0) {
$this->user_segments = ['guest', 'new_visitor'];
return;
}
// 获取用户历史行为
$purchase_count = $this->get_user_purchase_count($user_id);
$browse_history = $this->get_user_browse_history($user_id);
$last_visit = $this->get_user_last_visit($user_id);
// 定义用户分群
$segments = [];
if ($purchase_count > 5) {
$segments[] = 'frequent_buyer';
} elseif ($purchase_count > 0) {
$segments[] = 'occasional_buyer';
} else {
$segments[] = 'window_shopper';
}
// 基于浏览历史
if (count($browse_history) > 20) {
$segments[] = 'heavy_browser';
}
// 基于最近访问
$days_since_last_visit = (time() - $last_visit) / DAY_IN_SECONDS;
if ($days_since_last_visit < 1) {
$segments[] = 'active_today';
} elseif ($days_since_last_visit < 7) {
$segments[] = 'active_week';
}
$this->user_segments = array_unique($segments);
}
/**
* 初始化缓存变体
*/
private function initialize_cache_variations() {
$this->cache_variations = [
'guest' => [
'cache_ttl' => 300, // 5分钟
'personalized' => false,
'show_prices' => true,
'show_recommendations' => true,
],
'frequent_buyer' => [
'cache_ttl' => 1800, // 30分钟
'personalized' => true,
'show_prices' => true,
'show_recommendations' => true,
'show_exclusive_offers' => true,
],
'window_shopper' => [
'cache_ttl' => 900, // 15分钟
'personalized' => false,
'show_prices' => true,
'show_recommendations' => false,
],
'heavy_browser' => [
'cache_ttl' => 600, // 10分钟
'personalized' => true,
'show_prices' => true,
'show_recommendations' => true,
'cache_individual_components' => true,
],
];
}
/**
* 获取用户特定的缓存键
*/
public function get_user_specific_cache_key($base_key) {
$user_segment_key = implode('_', $this->user_segments);
$user_id = get_current_user_id();
if ($user_id > 0) {
return sprintf('%s_user%d_segment%s', $base_key, $user_id, md5($user_segment_key));
}
return sprintf('%s_guest_%s', $base_key, md5($user_segment_key));
}
/**
* 获取用户特定的缓存TTL
*/
public function get_user_specific_ttl($default_ttl = 3600) {
foreach ($this->user_segments as $segment) {
if (isset($this->cache_variations[$segment]['cache_ttl'])) {
return $this->cache_variations[$segment]['cache_ttl'];
}
}
return $default_ttl;
}
/**
* 渲染个性化商品列表
*/
public function render_personalized_product_list($args = []) {
$cache_key = $this->get_user_specific_cache_key('personalized_products');
$cached_data = wp_cache_get($cache_key, 'user_products');
if (false !== $cached_data) {
return $cached_data;
}
// 根据用户分群获取个性化商品
$products = $this->fetch_personalized_products($args);
// 缓存结果
$ttl = $this->get_user_specific_ttl();
wp_cache_set($cache_key, $products, 'user_products', $ttl);
return $products;
}
/**
* 获取个性化商品数据
*/
private function fetch_personalized_products($args) {
$user_id = get_current_user_id();
$products = [];
// 根据用户分群应用不同策略
if (in_array('frequent_buyer', $this->user_segments)) {
// 频繁购买者:显示互补商品和升级选项
$products = $this->get_complementary_products($user_id);
} elseif (in_array('window_shopper', $this->user_segments)) {
// 浏览者:显示热门和促销商品
$products = $this->get_popular_and_on_sale_products();
} else {
// 默认:显示精选商品
$products = $this->get_featured_products();
}
// 应用用户特定的过滤
$products = $this->apply_user_filters($products);
return $products;
}
}
/**
* 缓存性能监控器
*/
class Cache_Performance_Monitor {
private $metrics = [];
private $alert_thresholds = [];
public function __construct() {
$this->initialize_metrics();
$this->set_alert_thresholds();
}
/**
* 初始化监控指标
*/
private function initialize_metrics() {
$this->metrics = [
'hit_rate' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
'response_time' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
'memory_usage' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
'cache_size' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
];
}
/**
* 设置告警阈值
*/
private function set_alert_thresholds() {
$this->alert_thresholds = [
'hit_rate' => [
'warning' => 0.7, // 命中率低于70%警告
'critical' => 0.5, // 命中率低于50%严重
],
'response_time' => [
'warning' => 100, // 响应时间超过100ms警告
'critical' => 500, // 响应时间超过500ms严重
],
'memory_usage' => [
'warning' => 0.8, // 内存使用超过80%警告
'critical' => 0.9, // 内存使用超过90%严重
],
];
}
/**
* 记录缓存操作
*/
public function log_cache_operation($operation, $key, $hit, $response_time) {
$timestamp = microtime(true);
// 更新命中率统计
$this->update_hit_rate($hit);
// 记录响应时间
$this->record_response_time($response_time);
// 记录操作详情
$log_entry = [
'timestamp' => $timestamp,
'operation' => $operation,
'key' => $key,
'hit' => $hit,
'response_time' => $response_time,
];
$this->save_operation_log($log_entry);
// 检查是否需要告警
$this->check_alerts();
}
/**
* 更新命中率统计
*/
private function update_hit_rate($hit) {
$metric = &$this->metrics['hit_rate'];
// 简化计算:维护最近100次操作的命中率
$metric['history'][] = $hit ? 1 : 0;
if (count($metric['history']) > $metric['max_samples']) {
array_shift($metric['history']);
}
$hit_count = array_sum($metric['history']);
$total_count = count($metric['history']);
$metric['current'] = $total_count > 0 ? $hit_count / $total_count : 0;
}
/**
* 生成性能报告
*/
public function generate_performance_report() {
$report = [
'summary' => [
'hit_rate' => round($this->metrics['hit_rate']['current'] * 100, 2) . '%',
'avg_response_time' => round(array_sum($this->metrics['response_time']['history']) /
max(1, count($this->metrics['response_time']['history'])), 2) . 'ms',
'current_memory_usage' => $this->format_bytes($this->metrics['memory_usage']['current']),
],
'detailed_metrics' => $this->metrics,
'recommendations' => $this->generate_recommendations(),
'timestamp' => current_time('mysql'),
];
// 保存报告
$this->save_performance_report($report);
return $report;
}
/**
* 生成优化建议
*/
private function generate_recommendations() {
$recommendations = [];
// 基于命中率的建议
$hit_rate = $this->metrics['hit_rate']['current'];
if ($hit_rate < 0.5) {
$recommendations[] = [
'priority' => 'high',
'category' => 'hit_rate',
'message' => '缓存命中率过低,建议增加缓存容量或优化缓存键设计',
'action' => 'review_cache_keys_and_expiration',
];
} elseif ($hit_rate < 0.7) {
$recommendations[] = [
'priority' => 'medium',
'category' => 'hit_rate',
'message' => '缓存命中率偏低,考虑预热热门数据',
'action' => 'implement_cache_warmup',
];
}
// 基于响应时间的建议
$avg_response_time = array_sum($this->metrics['response_time']['history']) /
max(1, count($this->metrics['response_time']['history']));
if ($avg_response_time > 500) {
$recommendations[] = [
'priority' => 'high',
'category' => 'performance',
'message' => '缓存响应时间过长,建议检查Redis连接或考虑分片',
'action' => 'optimize_redis_configuration',
];
}
return $recommendations;
}
/**
* 自动化缓存清理
*/
public function automated_cache_cleanup() {
$stats = $this->get_cache_stats();
// 如果缓存大小超过阈值,执行清理
if ($stats['memory_usage_ratio'] > 0.8) {
$this->execute_intelligent_cleanup();
}
// 清理过期缓存
$this->clean_expired_entries();
// 清理低价值缓存
$this->clean_low_value_entries();
}
/**
* 智能缓存清理策略
*/
private function execute_intelligent_cleanup() {
global $wpdb;
// 获取缓存访问频率数据
$low_access_keys = $wpdb->get_col("
SELECT cache_key
FROM {$wpdb->prefix}cache_metrics
WHERE last_access < DATE_SUB(NOW(), INTERVAL 7 DAY)
AND access_count < 10
ORDER BY last_access ASC
LIMIT 1000
");
// 清理低访问频率的缓存
foreach ($low_access_keys as $key) {
wp_cache_delete($key, 'default');
}
// 记录清理操作
$this->log_cleanup_operation(count($low_access_keys));
}
}
/**
* 缓存性能监控器
*/
class Cache_Performance_Monitor {
private $metrics = [];
private $alert_thresholds = [];
public function __construct() {
$this->initialize_metrics();
$this->set_alert_thresholds();
}
/**
* 初始化监控指标
*/
private function initialize_metrics() {
$this->metrics = [
'hit_rate' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
'response_time' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
'memory_usage' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
'cache_size' => [
'current' => 0,
'history' => [],
'max_samples' => 100,
],
];
}
/**
* 设置告警阈值
*/
private function set_alert_thresholds() {
$this->alert_thresholds = [
'hit_rate' => [
'warning' => 0.7, // 命中率低于70%警告
'critical' => 0.5, // 命中率低于50%严重
],
'response_time' => [
'warning' => 100, // 响应时间超过100ms警告
'critical' => 500, // 响应时间超过500ms严重
],
'memory_usage' => [
'warning' => 0.8, // 内存使用超过80%警告
'critical' => 0.9, // 内存使用超过90%严重
],
];
}
/**
* 记录缓存操作
*/
public function log_cache_operation($operation, $key, $hit, $response_time) {
$timestamp = microtime(true);
// 更新命中率统计
$this->update_hit_rate($hit);
// 记录响应时间
$this->record_response_time($response_time);
// 记录操作详情
$log_entry = [
'timestamp' => $timestamp,
'operation' => $operation,
'key' => $key,
'hit' => $hit,
'response_time' => $response_time,
];
$this->save_operation_log($log_entry);
// 检查是否需要告警
$this->check_alerts();
}
/**
* 更新命中率统计
*/
private function update_hit_rate($hit) {
$metric = &$this->metrics['hit_rate'];
// 简化计算:维护最近100次操作的命中率
$metric['history'][] = $hit ? 1 : 0;
if (count($metric['history']) > $metric['max_samples']) {
array_shift($metric['history']);
}
$hit_count = array_sum($metric['history']);
$total_count = count($metric['history']);
$metric['current'] = $total_count > 0 ? $hit_count / $total_count : 0;
}
/**
* 生成性能报告
*/
public function generate_performance_report() {
$report = [
'summary' => [
'hit_rate' => round($this->metrics['hit_rate']['current'] * 100, 2) . '%',
'avg_response_time' => round(array_sum($this->metrics['response_time']['history']) /
max(1, count($this->metrics['response_time']['history'])), 2) . 'ms',
'current_memory_usage' => $this->format_bytes($this->metrics['memory_usage']['current']),
],
'detailed_metrics' => $this->metrics,
'recommendations' => $this->generate_recommendations(),
'timestamp' => current_time('mysql'),
];
// 保存报告
$this->save_performance_report($report);
return $report;
}
/**
* 生成优化建议
*/
private function generate_recommendations() {
$recommendations = [];
// 基于命中率的建议
$hit_rate = $this->metrics['hit_rate']['current'];
if ($hit_rate < 0.5) {
$recommendations[] = [
'priority' => 'high',
'category' => 'hit_rate',
'message' => '缓存命中率过低,建议增加缓存容量或优化缓存键设计',
'action' => 'review_cache_keys_and_expiration',
];
} elseif ($hit_rate < 0.7) {
$recommendations[] = [
'priority' => 'medium',
'category' => 'hit_rate',
'message' => '缓存命中率偏低,考虑预热热门数据',
'action' => 'implement_cache_warmup',
];
}
// 基于响应时间的建议
$avg_response_time = array_sum($this->metrics['response_time']['history']) /
max(1, count($this->metrics['response_time']['history']));
if ($avg_response_time > 500) {
$recommendations[] = [
'priority' => 'high',
'category' => 'performance',
'message' => '缓存响应时间过长,建议检查Redis连接或考虑分片',
'action' => 'optimize_redis_configuration',
];
}
return $recommendations;
}
/**
* 自动化缓存清理
*/
public function automated_cache_cleanup() {
$stats = $this->get_cache_stats();
// 如果缓存大小超过阈值,执行清理
if ($stats['memory_usage_ratio'] > 0.8) {
$this->execute_intelligent_cleanup();
}
// 清理过期缓存
$this->clean_expired_entries();
// 清理低价值缓存
$this->clean_low_value_entries();
}
/**
* 智能缓存清理策略
*/
private function execute_intelligent_cleanup() {
global $wpdb;
// 获取缓存访问频率数据
$low_access_keys = $wpdb->get_col("
SELECT cache_key
FROM {$wpdb->prefix}cache_metrics
WHERE last_access < DATE_SUB(NOW(), INTERVAL 7 DAY)
AND access_count < 10
ORDER BY last_access ASC
LIMIT 1000
");
// 清理低访问频率的缓存
foreach ($low_access_keys as $key) {
wp_cache_delete($key, 'default');
}
// 记录清理操作
$this->log_cleanup_operation(count($low_access_keys));
}
}
/**
* 缓存健康检查系统
*/
class Cache_Health_Checker {
private $check_interval = 300; // 5分钟
private $last_check_time = 0;
/**
* 执行健康检查
*/
public function perform_health_check() {
$current_time = time();
// 检查执行频率
if (($current_time - $this->last_check_time) < $this->check_interval) {
return;
}
$this->last_check_time = $current_time;
$health_status = [
'timestamp' => $current_time,
'checks' => [],
'overall_status' => 'healthy',
];
// 执行各项检查
$checks = [
'redis_connection' => $this->check_redis_connection(),
'memory_usage' => $this->check_memory_usage(),
'hit_rate' => $this->check_hit_rate(),
'response_time' => $this->check_response_time(),
'cache_integrity' => $this->check_cache_integrity(),
];
foreach ($checks as $check_name => $result) {
$health_status['checks'][$check_name] = $result;
if ($result['status'] === 'critical') {
$health_status['overall_status'] = 'critical';
} elseif ($result['status'] === 'warning' && $health_status['overall_status'] === 'healthy') {
$health_status['overall_status'] = 'warning';
}
}
// 发送告警(如果需要)
if ($health_status['overall_status'] !== 'healthy') {
$this->send_health_alert($health_status);
}
// 记录健康状态
$this->log_health_status($health_status);
return $health_status;
}
/**
* 检查Redis连接
*/
private function check_redis_connection() {
try {
$redis = new Redis();
$connected = $redis->connect('127.0.0.1', 6379, 1);
if ($connected) {
$ping = $redis->ping();
$redis->close();
return [
'status' => 'healthy',
'message' => 'Redis连接正常',
'details' => ['ping_response' => $ping],
];
}
} catch (Exception $e) {
return [
'status' => 'critical',
'message' => 'Redis连接失败',
'details' => ['error' => $e->getMessage()],
];
}
return [
'status' => 'critical',
'message' => '无法连接到Redis',
'details' => [],
];
}
/**
* 检查缓存命中率
*/
private function check_hit_rate() {
global $wpdb;
$hit_rate = $wpdb->get_var("
SELECT
SUM(CASE WHEN hit = 1 THEN 1 ELSE 0 END) / COUNT(*) as hit_rate
FROM {$wpdb->prefix}cache_metrics
WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 HOUR)
");
if ($hit_rate === null) {
$hit_rate = 0;
}
if ($hit_rate < 0.5) {
$status = 'critical';
$message = '缓存命中率过低';
} elseif ($hit_rate < 0.7) {
$status = 'warning';
$message = '缓存命中率偏低';
} else {
$status = 'healthy';
$message = '缓存命中率正常';
}
return [
'status' => $status,
'message' => $message,
'details' => ['hit_rate' => round($hit_rate * 100, 2) . '%'],
];
}
/**
* 检查缓存完整性
*/
private function check_cache_integrity() {
// 抽样检查缓存数据的完整性
$sample_keys = $this->get_cache_sample_keys(50);
$corrupted_count = 0;
foreach ($sample_keys as $key) {
$data = wp_cache_get($key, 'default');
if ($data !== false) {
// 验证数据完整性
if (!$this->validate_cache_data($data)) {
$corrupted_count++;
// 自动修复损坏的缓存
wp_cache_delete($key, 'default');
}
}
}
$corruption_rate = count($sample_keys) > 0 ? $corrupted_count / count($sample_keys) : 0;
if ($corruption_rate > 0.1) {
$status = 'critical';
$message = '缓存数据损坏率过高';
} elseif ($corruption_rate > 0.01) {
$status = 'warning';
$message = '发现缓存数据损坏';
} else {
$status = 'healthy';
$message = '缓存数据完整性良好';
}
return [
'status' => $status,
'message' => $message,
'details' => [
'sample_size' => count($sample_keys),
'corrupted_count' => $corrupted_count,
'corruption_rate' => round($corruption_rate * 100, 2) . '%',
],
];
}
/**
* 发送健康告警
*/
/**
* 缓存健康检查系统
*/
class Cache_Health_Checker {
private $check_interval = 300; // 5分钟
private $last_check_time = 0;
/**
* 执行健康检查
*/
public function perform_health_check() {
$current_time = time();
// 检查执行频率
if (($current_time - $this->last_check_time) < $this->check_interval) {
return;
}
$this->last_check_time = $current_time;
$health_status = [
'timestamp' => $current_time,
'checks' => [],
'overall_status' => 'healthy',
];
// 执行各项检查
$checks = [
'redis_connection' => $this->check_redis_connection(),
'memory_usage' => $this->check_memory_usage(),
'hit_rate' => $this->check_hit_rate(),
'response_time' => $this->check_response_time(),
'cache_integrity' => $this->check_cache_integrity(),
];
foreach ($checks as $check_name => $result) {
$health_status['checks'][$check_name] = $result;
if ($result['status'] === 'critical') {
$health_status['overall_status'] = 'critical';
} elseif ($result['status'] === 'warning' && $health_status['overall_status'] === 'healthy') {
$health_status['overall_status'] = 'warning';
}
}
// 发送告警(如果需要)
if ($health_status['overall_status'] !== 'healthy') {
$this->send_health_alert($health_status);
}
// 记录健康状态
$this->log_health_status($health_status);
return $health_status;
}
/**
* 检查Redis连接
*/
private function check_redis_connection() {
try {
$redis = new Redis();
$connected = $redis->connect('127.0.0.1', 6379, 1);
if ($connected) {
$ping = $redis->ping();
$redis->close();
return [
'status' => 'healthy',
'message' => 'Redis连接正常',
'details' => ['ping_response' => $ping],
];
}
} catch (Exception $e) {
return [
'status' => 'critical',
'message' => 'Redis连接失败',
'details' => ['error' => $e->getMessage()],
];
}
return [
'status' => 'critical',
'message' => '无法连接到Redis',
'details' => [],
];
}
/**
* 检查缓存命中率
*/
private function check_hit_rate() {
global $wpdb;
$hit_rate = $wpdb->get_var("
SELECT
SUM(CASE WHEN hit = 1 THEN 1 ELSE 0 END) / COUNT(*) as hit_rate
FROM {$wpdb->prefix}cache_metrics
WHERE timestamp > DATE_SUB(NOW(), INTERVAL 1 HOUR)
");
if ($hit_rate === null) {
$hit_rate = 0;
}
if ($hit_rate < 0.5) {
$status = 'critical';
$message = '缓存命中率过低';
} elseif ($hit_rate < 0.7) {
$status = 'warning';
$message = '缓存命中率偏低';
} else {
$status = 'healthy';
$message = '缓存命中率正常';
}
return [
'status' => $status,
'message' => $message,
'details' => ['hit_rate' => round($hit_rate * 100, 2) . '%'],
];
}
/**
* 检查缓存完整性
*/
private function check_cache_integrity() {
// 抽样检查缓存数据的完整性
$sample_keys = $this->get_cache_sample_keys(50);
$corrupted_count = 0;
foreach ($sample_keys as $key) {
$data = wp_cache_get($key, 'default');
if ($data !== false) {
// 验证数据完整性
if (!$this->validate_cache_data($data)) {
$corrupted_count++;
// 自动修复损坏的缓存
wp_cache_delete($key, 'default');
}
}
}
$corruption_rate = count($sample_keys) > 0 ? $corrupted_count / count($sample_keys) : 0;
if ($corruption_rate > 0.1) {
$status = 'critical';
$message = '缓存数据损坏率过高';
} elseif ($corruption_rate > 0.01) {
$status = 'warning';
$message = '发现缓存数据损坏';
} else {
$status = 'healthy';
$message = '缓存数据完整性良好';
}
return [
'status' => $status,
'message' => $message,
'details' => [
'sample_size' => count($sample_keys),
'corrupted_count' => $corrupted_count,
'corruption_rate' => round($corruption_rate * 100, 2) . '%',
],
];
}
/**
* 发送健康告警
*/


