#ifndef MEMCACHED_HH #define MEMCACHED_HH extern "C" { #include } #include #include #include #include namespace Answers { class MemCache { public: MemCache(); ~MemCache(); inline void set( const std::string &key, const std::string &value, const time_t expire, const u_int16_t flags ); inline bool get( const std::string &key, std::string &value ); //bool get( const std::vector &keys, std::vector &values, // std::vector &found = std::vector()); private: struct ::memcache *mc; }; //////////////////////////////////////////////////////////////////////////////// // // Implementation // //////////////////////////////////////////////////////////////////////////////// inline void MemCache::set( const std::string &key, const std::string &value, const time_t expire, const u_int16_t flags ) { if ( key.empty() ) return; /* Add a key */ int ret = ::mc_set(mc, (char *) key.c_str(), key.length(), value.c_str(), value.length(), expire, flags); if ( ret != 0 ) throw std::runtime_error( "MemCache::MemCache(): mc_put failed "+boost::lexical_cast(ret) ); } inline bool MemCache::get( const std::string &key, std::string &value ) { struct memcache_req *req = mc_req_new(); if ( ! req ) throw std::bad_alloc(); // "MemCache::get(): can't create memcache_req object with mc_req_new()" ); struct memcache_res *res = ::mc_req_add(req, (char*) key.c_str(), key.length()); ::mc_get(mc, req); if ( ! mc_res_found( res ) ) { ::mc_req_free(req); return false; } value = std::string( (char*)res->val, (char*)res->val+res->size ); ::mc_req_free(req); return true; } } #endif