All Products
Search
Document Center

ApsaraDB for Memcache:C++

Last Updated:Aug 08, 2023

Download the client

Download address

About the client

Client versions

Environment configuration

  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 command.

     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++ example code

  1. Download ocs_test.tar.gz.

  2. Run the following command.

    tar -xvf ocs_test.tar.gz 
    cd ocs_test 
    vim ocs_test_sample1.cpp
  3. Modify TARGET_HOST to the purchased Memcache address, modify USERNAME to the Memcache user name, and modify PASSWORD to the set password.

  4. Run the build.sh to generate ocs_test. Run ./ocs_test and you will see a key written to Memcache. Get the key from Memcache, and delete it from Memcache.

    The ocs_test_sample1.cpp code is as follows:

     #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;
     }

Following is a code example of using Memcache with another C++ program. Here we can see that Memcache cache and MySQL databases are used in combination. Compiling and installing a C++ client follow the same steps in the preceding example.

  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 command.

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

    Note: Modify OCS_TARGET_HOST to the address of the Memcache you have purchased, modify OCS_USERNAME to the Memcache instance name, and modify OCS_PASSWORD to the set password; MYSQL_HOST is the MySQL address, MYSQL_USERNAME is the database user name, and MYSQL_PASSWORD is the database password.

  3. Run the build.sh to generate ocs_test, and then run /ocs_test.

    The ocs_test_sample2.cpp code is as follows:

     #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;
     }