我们使用 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) {