2 * An example file showing the usage of the C++ libmemcached interface.
12 #include <libmemcached/memcached.hpp>
15 using namespace memcache
;
21 inline void operator()(const T
*ptr
) const
31 static const uint32_t num_of_clients
= 10;
33 static MyCache
&singleton()
35 static MyCache instance
;
39 void set(const string
&key
,
40 const vector
<char> &value
)
44 getCache()->set(key
, value
, expiry
, flags
);
47 vector
<char> get(const string
&key
)
49 vector
<char> ret_value
;
50 getCache()->get(key
, ret_value
);
54 void remove(const string
&key
)
56 getCache()->remove(key
);
61 /* pick a random element from the vector of clients */
62 Memcache
*first
= clients
[0];
69 * A vector of clients.
71 std::vector
<Memcache
*> clients
;
77 /* create clients and add them to the vector */
78 for (uint32_t i
= 0; i
< num_of_clients
; i
++)
80 Memcache
*client
= new Memcache("127.0.0.1:11211");
81 clients
.push_back(client
);
87 for_each(clients
.begin(), clients
.end(), DeletePtrs());
91 MyCache(const MyCache
&);
99 Product(int in_id
, double in_price
)
116 double getPrice() const
128 void setAllProducts(vector
<Product
> &products
)
130 vector
<char> raw_products(products
.size() * sizeof(Product
));
131 memcpy(&raw_products
[0], &products
[0], products
.size() * sizeof(Product
));
132 MyCache::singleton().set("AllProducts", raw_products
);
135 vector
<Product
> getAllProducts()
137 vector
<char> raw_products
= MyCache::singleton().get("AllProducts");
138 vector
<Product
> products(raw_products
.size() / sizeof(Product
));
139 memcpy(&products
[0], &raw_products
[0], raw_products
.size());
143 Product
getProduct(const string
&key
)
145 vector
<char> raw_product
= MyCache::singleton().get(key
);
147 if (! raw_product
.empty())
149 memcpy(&ret
, &raw_product
[0], sizeof(Product
));
153 /* retrieve it from the persistent store */
158 void setProduct(const string
&key
, const Product
&product
)
160 vector
<char> raw_product(sizeof(Product
));
161 memcpy(&raw_product
[0], &product
, sizeof(Product
));
162 MyCache::singleton().set(key
, raw_product
);
168 const string
key("padraig");
169 cout
<< "Going to set an object in the cache..." << endl
;
170 setProduct(key
, pad
);
171 cout
<< "Now retrieve that key..." << endl
;
172 Product test
= getProduct(key
);
173 double price
= test
.getPrice();
174 cout
<< "Price of retrieve object: " << price
<< endl
;
175 Product
next(2, 10.0);
176 vector
<Product
> products
;
177 products
.push_back(pad
);
178 products
.push_back(next
);
179 cout
<< "going to set a vector of products..." << endl
;
180 setAllProducts(products
);
181 cout
<< "now retrieve those products..." << endl
;
182 vector
<Product
> got
= getAllProducts();
183 cout
<< "size of retrieved vector: " << got
.size() << endl
;
184 vector
<Product
>::iterator iter
= got
.begin();
185 while (iter
!= got
.end())
187 cout
<< "product " << (*iter
).getId() << " costs " << (*iter
).getPrice() << endl
;