php写memcached ,c读取乱码问题[转]
用php寫memcached,用c從memcached讀數據的時候會出現取回的value為亂碼的現象,在百度上查看到的有用php寫,用java讀出亂碼的情況,看到一篇講解說是
(原文)實現的過程中遇到一個困難:從memcached里取出來的value有時候是亂碼。經過大量的試驗,我發現了一個規律:頁面大小不超過64k的,取出來的值不存在亂碼問題。一旦超過這個值,就變成了亂碼。看來64k是個很敏感的大小。但是memcached的存放單個值的大小最大值是1M。64kb還小的很啊。於是,我試試直接用memcached的服務端命令把600kb的value存入到memcached里,結果是成功了。說明問題是在客戶端了。
(原文)我查了一下memcached的客戶端(memcached client for java),其中有個方法setCompressEnable(boolean compressEnable),意思是超過多少大小(通過這個setCompressThreshold(long compressThreshold)方法設置大小)就進行壓縮。於是我設置了一下mcc.setCompressEnable(false);再次試驗,成功!!哈哈。。
看完上面文章後我也嘗試了一下,確實php中set的value在一定位元組數之內是不會有亂碼的,我就在程序中將壓縮取消,結果真的不亂碼了。
用php寫數據到memcached的代碼如下:
$servers = array(
array('ip1, 11211, 1),
array('ip2', 11222, 1),
);
$mc = NULL;
function initMemd()
{
global $mc;
global $servers;
if(count($servers) == 0) return false;
$mc = new Memcached();
if(false === $mc->addServers($servers))
{
print_r("add mem servers error!");
return false;
}
$ret = $mc->setOption(Memcached::OPT_COMPRESSION, false);
if($ret === false)
{
print_r("set memcached compression option false error!");
return false;
}
return true;
}
function pushToMemd($items)
{
global $mc;
$mc->setMulti($items);
if ($mc->getResultCode() == Memcached::RES_NOTSTORED) {
print_r("set memcached error");
}
}
用c讀的程序如下:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "libmemcached/memcached.h"
//gcc 1.c -I/usr/local/libmemcached/include -L /usr/local/libmemcached/lib/ -L /usr/local/lib -lmemcached
int main(int argc, char *argv[])
{
memcached_st *memc;
memcached_return rc;
memcached_server_st *servers;
//connect multi server
memc = memcached_create(NULL);
servers = memcached_server_list_append(NULL, "ip1", 11211, &rc);
//servers = memcached_server_list_append(servers, "ip2", 11211, &rc);
rc = memcached_server_push(memc, servers);
memcached_server_free(servers);
//Save multi data
size_t i;
char *keys[]= {"key1", "key2", "key3"};
size_t key_length[]= {4, 4, 4};
char *values[] = {"value1", "value2", "value3"};
size_t val_length[]= {6, 6, 6};
for (i=0; i <1; i++)
{
rc = memcached_set(memc, keys[i], key_length[i], values[i], val_length[i], (time_t)180, (uint32_t)0);
if (rc == MEMCACHED_SUCCESS)
{
printf("Save key:%s data:%s success\n",keys[i], values[i]);
}
}
char return_key[10000];
size_t return_key_length;
char *return_value;
size_t return_value_length;
uint32_t flags;
rc = memcached_mget(memc, keys, key_length, 1);
while ((return_value = memcached_fetch(memc, return_key,&return_key_length, &return_value_length, &flags, &rc))) {
if (rc == MEMCACHED_SUCCESS)
{
printf("Fetch key:%s data:%s , len=%d\n", return_key, return_value, return_value_length);
}
}
//Delete multi data
for (i=0; i<3; i++)
{
rc = memcached_set(memc, keys[i], key_length[i], values[i], val_length[i], (time_t)180, (uint32_t)0);
rc = memcached_delete(memc, keys[i], key_length[i], (time_t)0);
if (rc == MEMCACHED_SUCCESS)
{
printf("Delete %s successn", keys[i], values[i]);
}
}
//free
memcached_free(memc);
return 0;
}