1

我们使用 phpredis 库从我们的服务机器连接到我们的 64 节点 Redis 集群。尽管我们使用了持久连接,但由于 php 不会跨请求重用对象,每个请求都会先对 Redis 集群进行CLUSTER SLOTS调用,然后再进行数据获取。这被证明是非常昂贵的,因为这会增加 API 和 Redis 上的 CPU,并且还会增加元信息(CLUSTER SLOTS)的网络使用率,否则这些信息可能会被缓存。基本上,我们希望在同一个 php-fpm 进程中跨多个请求重用 Redis 集群连接对象。关于如何做到这一点的任何建议?

更新:我在 cluster_library.c 代码中尝试了以下差异,但这似乎导致了 php 中的随机运行时异常。

index 3e532b7..b2cbf16 100644
--- a/cluster_library.c
+++ b/cluster_library.c
@@ -7,6 +7,10 @@
 #include <zend_exceptions.h>

 extern zend_class_entry *redis_cluster_exception_ce;
+int cache_count = 0;
+//Cache the cluster slots value for every n requests/calls, n being 100 for now
+int CACHE_COUNT_VAL = 10;
+clusterReply *permSlots=NULL;

 /* Debugging methods/
 static void cluster_dump_nodes(redisCluster *c) {
@@ -939,7 +943,18 @@ PHP_REDIS_API int cluster_map_keyspace(redisCluster *c TSRMLS_DC) {
         }

         // Parse out cluster nodes.  Flag mapped if we are valid
-        slots = cluster_get_slots(seed TSRMLS_CC);
+ if (permSlots && cache_count <= CACHE_COUNT_VAL) {
+         slots = permSlots;
+         cache_count++;
+ }
+ else {
+         slots = cluster_get_slots(seed TSRMLS_CC);
+ }
+
         if (slots) {
             mapped = !cluster_map_slots(c, slots);
             // Bin anything mapped, if we failed somewhere
@@ -951,8 +966,16 @@ PHP_REDIS_API int cluster_map_keyspace(redisCluster *c TSRMLS_DC) {
         if (mapped) break;
     } ZEND_HASH_FOREACH_END();

+    if((!permSlots && mapped && slots) ||
+             cache_count >= CACHE_COUNT_VAL) {
+ permSlots = slots;
+ cache_count = 0;
+    }
+
     // Clean up slots reply if we got one
-    if(slots) cluster_free_reply(slots, 1);
+    // if(slots) cluster_free_reply(slots, 1);

     // Throw an exception if we couldn't map
     if(!mapped) {
4

1 回答 1

4

phpredis 的开发者在这里。目前这是 phpredis 的一个限制/缺陷,因为它必须为每个新请求发出一个 CLUSTER SLOTS 命令。据我所知,避免这种情况的唯一方法是将 phpredis 指向像CodisCorvis这样的代理,但我没有任何使用它们的个人经验。

话虽如此,我确实在这个分支中实现了对这个特性的实验性支持。它使用 PHPpersistent_list来跨请求缓存槽信息。

随着 Redis Cluster 的采用似乎正在增加,我将尝试尽快将其纳入主线开发分支,并可能进入下一个稳定版本!

干杯,迈克

于 2017-10-29T18:18:59.843 回答