歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> libmemcached C/C++ API使用實例

libmemcached C/C++ API使用實例

日期:2017/3/1 10:37:03   编辑:Linux編程

libmemcached C/C++ API使用實例:

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <time.h>
  5. #include <unistd.h>
  6. #include <libmemcached/memcached.h>
  7. int main(int argc, char *argv[])
  8. {
  9. memcached_st *memc;
  10. memcached_return rc;
  11. memcached_server_st *servers;
  12. //connect multi server
  13. memc = memcached_create(NULL);
  14. servers = memcached_server_list_append(NULL, (char*)"localhost", 11211, &rc);
  15. servers = memcached_server_list_append(servers, (char*)"localhost", 30000, &rc);
  16. rc = memcached_server_push(memc, servers);
  17. memcached_server_free(servers);
  18. memcached_behavior_set(memc,MEMCACHED_BEHAVIOR_DISTRIBUTION,MEMCACHED_DISTRIBUTION_CONSISTENT);
  19. memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_RETRY_TIMEOUT, 20) ;
  20. // memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_REMOVE_FAILED_SERVERS, 1) ; // 同時設置MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT 和 MEMCACHED_BEHAVIOR_AUTO_EJECT_HOSTS
  21. memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_SERVER_FAILURE_LIMIT, 5) ;
  22. memcached_behavior_set(memc, MEMCACHED_BEHAVIOR_AUTO_EJECT_HOSTS, 1) ;
  23. int time_sl = 0 ;
  24. int times = 0 ;
  25. while(times++<100000)
  26. {
  27. //save data
  28. const char *keys[]= {"key1", "key2", "key3","key4"};
  29. const size_t key_length[]= {4, 4, 4, 4};
  30. char *values[] = {"This is 1 first value", "This is 2 second value", "This is 3 third value"," this is 4 forth value"};
  31. size_t val_length[]= {21, 22, 21, 22};
  32. int i = 0;
  33. for (; i < 4; i++)
  34. {
  35. rc = memcached_set(memc, keys[i], key_length[i], values[i], val_length[i], (time_t)180,(uint32_t)0); printf("key: %s rc:%s\n", keys[i], memcached_strerror(memc, rc)); // 輸出狀態
  36. }
  37. printf("time: %d\n", time_sl++) ;
  38. sleep(1) ;
  39. }
  40. //free
  41. memcached_free(memc);
  42. return 0;
  43. }
Copyright © Linux教程網 All Rights Reserved