2 * An example file showing the usage of the C++ libmemcached interface.
14 #include <libmemcached/memcached.hpp>
17 using namespace memcache
;
23 inline void operator()(const T
*ptr
) const
33 static const uint32_t num_of_clients
= 10;
35 static MyCache
&singleton()
37 static MyCache instance
;
41 void set(const string
&key
,
42 const vector
<char> &value
)
46 getCache()->set(key
, value
, expiry
, flags
);
49 vector
<char> get(const string
&key
)
51 vector
<char> ret_value
;
52 getCache()->get(key
, ret_value
);
56 void remove(const string
&key
)
58 getCache()->remove(key
);
64 * pick a random element from the vector of clients. Obviously, this is
65 * not very random but suffices as an example!
67 uint32_t index
= rand() % num_of_clients
;
68 return clients
[index
];
74 * A vector of clients.
76 std::vector
<Memcache
*> clients
;
82 /* create clients and add them to the vector */
83 for (uint32_t i
= 0; i
< num_of_clients
; i
++)
85 Memcache
*client
= new Memcache("127.0.0.1:11211");
86 clients
.push_back(client
);
92 for_each(clients
.begin(), clients
.end(), DeletePtrs());
96 MyCache(const MyCache
&);
104 Product(int in_id
, double in_price
)
121 double getPrice() const
133 void setAllProducts(vector
<Product
> &products
)
135 vector
<char> raw_products(products
.size() * sizeof(Product
));
136 memcpy(&raw_products
[0], &products
[0], products
.size() * sizeof(Product
));
137 MyCache::singleton().set("AllProducts", raw_products
);
140 vector
<Product
> getAllProducts()
142 vector
<char> raw_products
= MyCache::singleton().get("AllProducts");
143 vector
<Product
> products(raw_products
.size() / sizeof(Product
));
144 memcpy(&products
[0], &raw_products
[0], raw_products
.size());
148 Product
getProduct(const string
&key
)
150 vector
<char> raw_product
= MyCache::singleton().get(key
);
152 if (! raw_product
.empty())
154 memcpy(&ret
, &raw_product
[0], sizeof(Product
));
158 /* retrieve it from the persistent store */
163 void setProduct(const string
&key
, const Product
&product
)
165 vector
<char> raw_product(sizeof(Product
));
166 memcpy(&raw_product
[0], &product
, sizeof(Product
));
167 MyCache::singleton().set(key
, raw_product
);
172 Memcache
first_client("127.0.0.1:19191");
173 map
< string
, map
<string
, string
> > my_stats
;
174 first_client
.getStats(my_stats
);
177 * Iterate through the retrieved stats.
179 map
< string
, map
<string
, string
> >::iterator it
=
181 while (it
!= my_stats
.end())
183 cout
<< "working with server: " << (*it
).first
<< endl
;
184 map
<string
, string
> serv_stats
= (*it
).second
;
185 map
<string
, string
>::iterator iter
= serv_stats
.begin();
186 while (iter
!= serv_stats
.end())
188 cout
<< (*iter
).first
<< ":" << (*iter
).second
<< endl
;