2 * An example file showing the usage of the C++ libmemcached interface.
13 #include <libmemcached/memcached.hpp>
16 using namespace memcache
;
22 inline void operator()(const T
*ptr
) const
32 static const uint32_t num_of_clients
= 10;
34 static MyCache
&singleton()
36 static MyCache instance
;
40 void set(const string
&key
,
41 const vector
<char> &value
)
45 getCache()->set(key
, value
, expiry
, flags
);
48 vector
<char> get(const string
&key
)
50 vector
<char> ret_value
;
51 getCache()->get(key
, ret_value
);
55 void remove(const string
&key
)
57 getCache()->remove(key
);
63 * pick a random element from the vector of clients. Obviously, this is
64 * not very random but suffices as an example!
66 uint32_t index
= rand() % num_of_clients
;
67 return clients
[index
];
73 * A vector of clients.
75 std::vector
<Memcache
*> clients
;
81 /* create clients and add them to the vector */
82 for (uint32_t i
= 0; i
< num_of_clients
; i
++)
84 Memcache
*client
= new Memcache("127.0.0.1:11211");
85 clients
.push_back(client
);
91 for_each(clients
.begin(), clients
.end(), DeletePtrs());
95 MyCache(const MyCache
&);
103 Product(int in_id
, double in_price
)
120 double getPrice() const
132 void setAllProducts(vector
<Product
> &products
)
134 vector
<char> raw_products(products
.size() * sizeof(Product
));
135 memcpy(&raw_products
[0], &products
[0], products
.size() * sizeof(Product
));
136 MyCache::singleton().set("AllProducts", raw_products
);
139 vector
<Product
> getAllProducts()
141 vector
<char> raw_products
= MyCache::singleton().get("AllProducts");
142 vector
<Product
> products(raw_products
.size() / sizeof(Product
));
143 memcpy(&products
[0], &raw_products
[0], raw_products
.size());
147 Product
getProduct(const string
&key
)
149 vector
<char> raw_product
= MyCache::singleton().get(key
);
151 if (! raw_product
.empty())
153 memcpy(&ret
, &raw_product
[0], sizeof(Product
));
157 /* retrieve it from the persistent store */
162 void setProduct(const string
&key
, const Product
&product
)
164 vector
<char> raw_product(sizeof(Product
));
165 memcpy(&raw_product
[0], &product
, sizeof(Product
));
166 MyCache::singleton().set(key
, raw_product
);
171 Memcache
first_client("127.0.0.1:19191");
172 map
< string
, map
<string
, string
> > my_stats
;
173 first_client
.getStats(my_stats
);
176 * Iterate through the retrieved stats.
178 map
< string
, map
<string
, string
> >::iterator it
=
180 while (it
!= my_stats
.end())
182 cout
<< "working with server: " << (*it
).first
<< endl
;
183 map
<string
, string
> serv_stats
= (*it
).second
;
184 map
<string
, string
>::iterator iter
= serv_stats
.begin();
185 while (iter
!= serv_stats
.end())
187 cout
<< (*iter
).first
<< ":" << (*iter
).second
<< endl
;