无法使用 libmemcached 连接到 memcachedb

Unable to connect to memcachedb using libmemcached

本文关键字:连接 memcachedb libmemcached      更新时间:2023-10-16

我正在编写一个小型C++应用程序,该应用程序能够使用libmemcached C++ API连接到memcachedb实例。

memcachedb实例是使用以下命令创建的:

memcachedb -m 64 -p 21201 -A 4096 -u memcachedb -l 127.0.0.1 -H /var/lib/memcachedb -f /var/lib/memcachedb/default.db -U off

我可以通过执行以下操作来检索服务器统计信息:

telnet 127.0.0.1 21201
stats
STAT pid 1972
STAT uptime 124936
STAT time 1428898165
STAT version 1.2.0
STAT pointer_size 64
STAT rusage_user 5.687019
STAT rusage_system 13.329336
STAT ibuffer_size 512
STAT curr_connections 5
STAT total_connections 12
STAT connection_structures 6
STAT cmd_get 4
STAT cmd_set 4
STAT get_hits 4
STAT get_misses 0
STAT bytes_read 236
STAT bytes_written 2171
STAT threads 4
END

为了以编程方式检索服务器 STATS,我使用以下代码:

#include <libmemcached/memcached.hpp>
#include <string>
#include <stdio.h>
#include <string.h>
using namespace std;
using namespace memcache;
int main(int argc, char **argv) {
    std::string host(argv[1]);
    int port;
    istringstream(std::string(argv[2])) >> port;
    printf("%sn", "Instantiating client");
    Memcache first_client;
    printf("Adding server host=[%s] port=[%d]n", host.c_str(), port);
    first_client.addServer(host, port);
    printf("%sn", "Getting server STATS");
    map<string, map<string, string> > my_stats;
    bool gotStats = first_client.getStats(my_stats);
    if (gotStats) {
        printf("%sn", "Got STATS");
    } else {
        printf("%sn", "Unable to get STATS");
    }
    return EXIT_SUCCESS;
}

我正在使用以下Makefile编译应用程序:

CXXFLAGS =  -O2 -g -Wall -fmessage-length=0
OBJS =      MemcachedExample.o
LIBS =      -lmemcached
TARGET =    MemcachedExample
$(TARGET):  $(OBJS)
$(CXX) -o $(TARGET) $(OBJS) $(LIBS)
all:    $(TARGET)
clean:
rm -f $(OBJS) $(TARGET)

当我使用以下命令执行应用程序时:

MemcachedExample 127.0.0.1 21201

它无法检索服务器统计信息:

Instantiating client
Adding server host=[127.0.0.1] port=[21201]
Getting server STATS
Unable to get STATS

我做错了什么?我将不胜感激任何见解。

查看@Rastmaj所指出的 tcpdump,我发现在通过我的程序连接的转储中,没有与我尝试建立的连接相关的数据包。

这让我看了一下 memcached 的 C 客户端库的 C++ 接口的代码。我发现空构造函数正在使用memcached("", 0)初始化memcached_st对象,而接收hostnameport参数的构造函数不仅使用 memcached("", 0) 初始化memcached_st对象,而且还使用 memcached_server_add 函数添加了服务器。

虽然没有明显的原因说明它在初始化memcached_st对象后添加服务器时会起作用,但由于C++方法memcache::Memcache::addServer完全相同,我发现的解决方案只是在更改:

Memcache first_client;

Memcache first_client("--SERVER=" + host + ":" + std::string(argv[2]));

这解决了我的问题,但我仍然缺乏对这种行为的解释,非常感谢进一步的见解。