All Products
Search
Document Center

:C++

Last Updated:Mar 06, 2025

Download the client

Download address

About the client

Client versions

Configure the environment

  1. Download, compile, and install the C++ client.

    https://launchpad.net/libmemcached/1.0/1.0.18/+download/libmemcached-1.0.18.tar.gz

  2. Run the following commands:

     tar -xvf libmemcached-1.0.18.tar.gz
     cd libmemcached-1.0.18 
     ./configure --enable-sasl
     make 
     make install (sudo permission may be required)

C++ sample code

  1. Download ocs_test.tar.gz.

  2. Run the following commands:

    tar -xvf ocs_test.tar.gz 
    cd ocs_test 
    vim ocs_test_sample1.cpp
  3. Modify the value of TARGET_HOST to the address of the ApsaraDB for Memcache instance that you create, the value of USERNAME to the username that you use to create the instance, and the value of PASSWORD to the required password.

  4. Run build.sh to generate ocs_test. Run ./ocs_test to write and obtain a key to and from the instance. Then, you can delete the key from the instance.

    ocs_test_sample1.cpp sample code

     #include <iostream>
     #include <string>
     #include <libmemcached/memcached.h>
     using namespace std;
    
     #define TARGET_HOST  ""
     #define USERNAME ""
     #define PASSWORD ""
    
     int main(int argc, char *argv[])
     {
         memcached_st *memc = NULL;
         memcached_return rc;
         memcached_server_st *server;
         memc = memcached_create(NULL);
         server = memcached_server_list_append(NULL, TARGET_HOST, 11211,&rc);
    
         /* SASL */
         sasl_client_init(NULL);
         rc = memcached_set_sasl_auth_data(memc, USERNAME, PASSWORD);
         if(rc != MEMCACHED_SUCCESS) {
             cout<<"Set SASL err:"<< endl;
         }
         rc = memcached_behavior_set(memc,MEMCACHED_BEHAVIOR_BINARY_PROTOCOL,1);
         if(rc != MEMCACHED_SUCCESS) {
             cout<<"Binary Set err:"<<endl;
         }
         /* SASL */
    
         rc = memcached_server_push(memc,server);
         if(rc != MEMCACHED_SUCCESS) {
           cout <<"Connect Mem err:"<< rc << endl;
         }
         memcached_server_list_free(server);
    
         string key = "TestKey";
         string value = "TestValue";
         size_t value_length = value.length();
         size_t key_length = key.length();
         int expiration = 0;
         uint32_t flags = 0;
    
         //Save data
         rc = memcached_set(memc,key.c_str(),key.length(),value.c_str(),value.length(),expiration,flags);
         if (rc != MEMCACHED_SUCCESS){
           cout <<"Save data failed: " << rc << endl;
           return -1;
         }
         cout <<"Save data succeed, key: " << key << " value: " << value << endl;
    
         cout << "Start get key:" << key << endl;
    
         char* result = memcached_get(memc,key.c_str(),key_length,&value_length,&flags,&rc);
         cout << "Get value:" << result << endl;
    
         //Delete data
         cout << "Start delete key:" << key << endl;
         rc = memcached_delete(memc,key.c_str(),key_length,expiration);
         if (rc != MEMCACHED_SUCCESS) {
           cout << "Delete key failed: " << rc << endl;
         }
         cout << "Delete key succeed: " << rc << endl;
         //free
         memcached_free(memc);
         return 0;
     }

The following information provides a code example of using ApsaraDB for Memcache with another C++ program. The cache of ApsaraDB for Memcache is used together with MySQL databases. For more information about how to compile and install a C++ client, see the preceding steps.

  1. Create the example database and table in the MySQL database.

    mysql -h host -uUSER -pPASSSWORD
    create database testdb;
     create table user_info (user_id int, user_name char(32) not null, password char(32) not null, is_online int, primary key(user_id) );
  2. Download ocs_test_2.tar.gz and run the following commands:

    tar -xvf ocs_test_2.tar.gz 
    cd ocs_test 
    vim ocs_test_sample2.cpp
    Note

    Modify the value of OCS_TARGET_HOST to the address of the ApsaraDB for Memcache instance that you create, the value of OCS_USERNAME to the username that you use to create the instance, and the value of OCS_PASSWORD to the required password. MYSQL_HOST indicates the address of a MySQL database, MYSQL_USERNAME indicates the database username, and MYSQL_PASSWORD indicates the database password.

  3. Run build.sh to generate ocs_test and run /ocs_test.

    ocs_test_sample2.cpp sample code

     #include <iostream>
     #include <string>
     #include <sstream>
     #include <libmemcached/memcached.h>
     #include <mysql/mysql.h>
    
     using namespace std;
    
     #define OCS_TARGET_HOST  "xxxxxxxxxx.m.yyyyyyyyy.ocs.aliyuncs.com"
     #define OCS_USERNAME "your_user_name"
     #define OCS_PASSWORD "your_password"
    
     #define MYSQL_HOST        "zzzzzzzzzz.mysql.rds.aliyuncs.com"
     #define MYSQL_USERNAME    "db_user"
     #define MYSQL_PASSWORD    "db_paswd"
     #define MYSQL_DBNAME      "testdb"
    
     #define TEST_USER_ID      "100"
    
     MYSQL *mysql = NULL;
     memcached_st *memc = NULL;
     memcached_return rc;
    
     int InitMysql()
     {
       mysql = mysql_init(0);
       if (mysql_real_connect(mysql, MYSQL_HOST, MYSQL_USERNAME, MYSQL_PASSWORD, MYSQL_DBNAME, MYSQL_PORT, NULL, CLIENT_FOUND_ROWS) == NULL )
       {
         cout << "connect mysql failure!" << endl;
         return EXIT_FAILURE;
       }
       cout << "connect mysql success!" << endl;
       return 0;
     }
    
     bool InitMemcached()
     {
       memcached_server_st *server;
       memc = memcached_create(NULL);
       server = memcached_server_list_append(NULL, OCS_TARGET_HOST, 11211,&rc);
    
       /* SASL */
       sasl_client_init(NULL);
       rc = memcached_set_sasl_auth_data(memc, OCS_USERNAME, OCS_PASSWORD);
       if (rc != MEMCACHED_SUCCESS)
       {
         cout<<"Set SASL err:"<< endl;
         return false;
       }
       rc = memcached_behavior_set(memc,MEMCACHED_BEHAVIOR_BINARY_PROTOCOL,1);
       if (rc != MEMCACHED_SUCCESS)
       {
         cout<<"Binary Set err:"<<endl;
         return false;
       }
       /* SASL */
       rc = memcached_server_push(memc,server);
       if (rc != MEMCACHED_SUCCESS)
       {
         cout <<"Connect Mem err:"<< rc << endl;
         return false;
       }
       memcached_server_list_free(server);
       return true;
     }
    
     struct UserInfo
     {
       int user_id;
       char user_name[32];
       char password[32];
       int is_online;
     };
    
     bool SaveToCache(string &key, string &value, int expiration)
     {
       size_t value_length = value.length();
       size_t key_length = key.length();
       uint32_t flags = 0;
       //Save data
       rc = memcached_set( memc,key.c_str(), key.length(), value.c_str(), value.length(), expiration, flags);
       if (rc != MEMCACHED_SUCCESS){
           cout <<"Save data to cache failed: " << rc << endl;
           return false;
       }
       cout <<"Save data to cache succeed, key: " << key << " value: " << value << endl;
       return true;
     }
    
     UserInfo *GetUserInfo(int user_id)
     {
       UserInfo *user_info = NULL;
       //get from cache
       string key;
       stringstream out;
       out << user_id;
       key = out.str();
       cout << "Start get key:" << key << endl;
       size_t value_length;
       uint32_t flags;
       char* result = memcached_get(memc, key.c_str(), key.size(), &value_length, &flags, &rc);
       if (rc != MEMCACHED_SUCCESS)
       {
         cout << "Get Cache Failed, start get from mysql."<< endl;
         int status;
         char select_sql[1024];
         memset(select_sql, 0x0, sizeof(select_sql));
         sprintf(select_sql, "select * from user_info where user_id = %d", user_id);
         status = mysql_query(mysql, select_sql);
         if (status !=0 )
         {
           cout << "query from mysql failure!" << endl;
           return NULL;
         }
         cout << "the status is :" << status << endl;
         MYSQL_RES *mysql_result = mysql_store_result(mysql);
         user_info = new UserInfo;
         MYSQL_ROW row;
         while (row = mysql_fetch_row(mysql_result))
         {
           user_info->user_id = atoi(row[0]);
           strncpy(user_info->user_name, row[1], strlen(row[1]));
           strncpy(user_info->password, row[2], strlen(row[2]));
           user_info->is_online = atoi(row[3]);
         }
         mysql_free_result(mysql_result);
         return user_info;
       }
       cout << "Get from cache succeed" << endl;
       user_info = new UserInfo;
       memcpy(user_info, result, value_length);
       return user_info;
     }
    
     bool DeleteCache(string &key, int expiration)
     {
       rc = memcached_delete(memc, key.c_str(), key.length(), expiration);
       if (rc != MEMCACHED_SUCCESS) {
         cout << "Delete key failed: " << rc << endl;
         return false;
       }
       cout << "Delete key succeed: " << rc << endl;
       return true;
     }
    
     void PrintUserInfo(UserInfo *user_info)
     {
       cout << "user_id: " << user_info->user_id << " " << " name: " << user_info->user_name << endl;
     }
    
     bool SaveMysql(UserInfo *user_info)
     {
       char insert_sql[1024];
       memset(insert_sql, 0x0, sizeof(insert_sql));
       sprintf(insert_sql, "insert into user_info(user_id, user_name, password, is_online) values(%d, '%s', '%s', %d)", user_info->user_id, user_info->user_name, user_info->password, user_info->is_online);
       int status = mysql_query(mysql, insert_sql);
       if (status != 0)
       {
         cout << "insert failed" << endl;
         return false;
       }
       cout << "insert user_info" << endl;
       //insert mysql
       return true;
     }
    
     int main(int argc, char *argv[])
     {
       if (InitMysql() != 0)
       {
         return -1;
       }
       if (!InitMemcached())
       {
         return -1;
       }
    
       //generate user_info
       UserInfo user_info;
       user_info.user_id = atoi(TEST_USER_ID);
       strcpy(user_info.user_name, "James");
       strcpy(user_info.password, "12345678");
       user_info.is_online = 1;
    
       //save to mysql
       if (!SaveMysql(&user_info))
       {
         //return -1;
       }
       string user_str;
       user_str.assign((char*)&user_info, sizeof(UserInfo));
       //save to memcached
       string key_str = TEST_USER_ID;
       SaveToCache(key_str, user_str, 10);
    
       //start get, exist in memcahced
       UserInfo *get_user_info = GetUserInfo(user_info.user_id);
       PrintUserInfo(get_user_info);
    
       //wait 10 secons
       sleep(2);
       //delete memcached or expired
       DeleteCache(key_str, 0);
    
       //start get, exist in mysql
       delete get_user_info;
       get_user_info = GetUserInfo(user_info.user_id);
    
       PrintUserInfo(get_user_info);
       delete get_user_info;
       //free
       memcached_free(memc);
       mysql_close(mysql);
       return 0;
     }