当前位置: 首页 > 工具软件 > Tokyo Cabinet > 使用案例 >

tokyo cabinet

甄霖
2023-12-01
三、调用
1、使用memcached兼容协议
2、http调用
写 curl -X PUT http://127.0.0.1:11111/key -d "value"
读 curl http://127.0.0.1:11111/key
删 curl -X DELETE http://127.0.0.1:11111/key
3、使用C调用
1)直接写文件
例:
我使用的是hash database 所有函数带tch前缀,如果是其他数据库请参考tokyocabinet-1.4.31/doc下spex-en.html的函数接口说明

#include <tcutil.h>

#include <tchdb.h>

#include <stdlib.h>

#include <stdbool.h>

#include <stdint.h>

 

int main(int argc, char **argv)

{

TCHDB *hdb;int ecode;char *key, *value;

 

/* create the object */

hdb = tchdbnew();

 

/* open the database */

if(!tchdbopen(hdb, "casket.tch", HDBOWRITER | HDBOCREAT))

{        ecode = tchdbecode(hdb);        fprintf(stderr, "open error: %s/n", tchdberrmsg(ecode));}

 

/* store records */

if(!tchdbput2(hdb, "foo", "hop") ||!tchdbput2(hdb, "bar", "step") ||!tchdbput2(hdb, "baz", "jump"))

{        ecode = tchdbecode(hdb);        fprintf(stderr, "put error: %s/n", tchdberrmsg(ecode));}

 

/* retrieve records */

value = tchdbget2(hdb, "foo");

if(value)

{        printf("%s/n", value);        free(value);}

else

{        ecode = tchdbecode(hdb);        fprintf(stderr, "get error: %s/n", tchdberrmsg(ecode));}

 

/* traverse records */

tchdbiterinit(hdb);

 

while((key = tchdbiternext2(hdb)) != NULL)

{        value = tchdbget2(hdb, key);        if(value){                printf("%s:%s/n", key, value);        free(value);}        

          free(key);

}

 

/* close the database */

if(!tchdbclose(hdb))

{        ecode = tchdbecode(hdb);        fprintf(stderr, "close error: %s/n", tchdberrmsg(ecode));}

/* delete the object */

tchdbdel(hdb);return 0;}

 

 

2)使用网络读写例:
请参考tokyotyrant-1.1.33/doc下index.html的函数接口说明
#include <tcrdb.h>
#include <stdlib.h>
#include <stdbool.h>
#include <stdint.h>
int main(int argc, char **argv){
TCRDB *rdb;
int ecode;
char *value;
/* create the object */
rdb = tcrdbnew();
/* connect to the server */
if(!tcrdbopen(rdb, "localhost", 1978)){
        ecode = tcrdbecode(rdb);
        fprintf(stderr, "open error: %s/n", tcrdberrmsg(ecode));
}
/* store records */
if(!tcrdbput2(rdb, "foo", "hop") ||
!tcrdbput2(rdb, "bar", "step") ||
!tcrdbput2(rdb, "baz", "jump")){
        ecode = tcrdbecode(rdb);
        fprintf(stderr, "put error: %s/n", tcrdberrmsg(ecode));
}
/* retrieve records */
value = tcrdbget2(rdb, "foo");
if(value){
        printf("%s/n", value);
        free(value);
} else {
        ecode = tcrdbecode(rdb);
        fprintf(stderr, "get error: %s/n", tcrdberrmsg(ecode));
}
/* close the connection */
if(!tcrdbclose(rdb)){
        ecode = tcrdbecode(rdb);
        fprintf(stderr, "close error: %s/n", tcrdberrmsg(ecode));
}
/* delete the object */
tcrdbdel(rdb);
return 0;
}

 

 

编译C程序命令:

gcc -I/usr/local/include tt_example.c -o tt_example -L/usr/local/lib -ltokyotyrant -ltokyocabinet -lz -lbz2 /

    -lresolv -lnsl -ldl -lrt -lpthread -lm -lc

 类似资料:

相关阅读

相关文章

相关问答