6feb26ab5e0b00baa3e7f25bfe8447dc0323e6fb
2 * An example file showing the usage of the C++ libmemcached interface.
11 #include <libmemcached/memcached.hpp>
14 using namespace memcache
;
20 static const uint32_t num_of_clients
= 10;
22 static MyCache
&singleton()
24 static MyCache instance
;
28 void set(const string
&key
,
29 const vector
<char> &value
)
33 getCache()->set(key
, value
, expiry
, flags
);
36 vector
<char> get(const string
&key
)
38 vector
<char> ret_value
;
39 getCache()->get(key
, ret_value
);
43 void remove(const string
&key
)
45 getCache()->remove(key
);
50 /* pick a random element from the vector of clients */
51 Memcache
*first
= clients
[0];
58 * A vector of clients.
60 std::vector
<Memcache
*> clients
;
66 /* create clients and add them to the vector */
67 for (uint32_t i
= 0; i
< num_of_clients
; i
++)
69 Memcache
*client
= new Memcache("127.0.0.1:11211");
70 clients
.push_back(client
);
79 MyCache(const MyCache
&);
87 Product(int in_id
, double in_price
)
104 double getPrice() const
116 void setAllProducts(vector
<Product
> &products
)
118 vector
<char> raw_products(products
.size() * sizeof(Product
));
119 memcpy(&raw_products
[0], &products
[0], products
.size() * sizeof(Product
));
120 MyCache::singleton().set("AllProducts", raw_products
);
123 vector
<Product
> getAllProducts()
125 vector
<char> raw_products
= MyCache::singleton().get("AllProducts");
126 vector
<Product
> products(raw_products
.size() / sizeof(Product
));
127 memcpy(&products
[0], &raw_products
[0], raw_products
.size());
131 Product
getProduct(const string
&key
)
133 vector
<char> raw_product
= MyCache::singleton().get(key
);
135 if (! raw_product
.empty())
137 memcpy(&ret
, &raw_product
[0], sizeof(Product
));
141 /* retrieve it from the persistent store */
146 void setProduct(const string
&key
, const Product
&product
)
148 vector
<char> raw_product(sizeof(Product
));
149 memcpy(&raw_product
[0], &product
, sizeof(Product
));
150 MyCache::singleton().set(key
, raw_product
);
156 const string
key("padraig");
157 cout
<< "Going to set an object in the cache..." << endl
;
158 setProduct(key
, pad
);
159 cout
<< "Now retrieve that key..." << endl
;
160 Product test
= getProduct(key
);
161 double price
= test
.getPrice();
162 cout
<< "Price of retrieve object: " << price
<< endl
;
163 Product
next(2, 10.0);
164 vector
<Product
> products
;
165 products
.push_back(pad
);
166 products
.push_back(next
);
167 cout
<< "going to set a vector of products..." << endl
;
168 setAllProducts(products
);
169 cout
<< "now retrieve those products..." << endl
;
170 vector
<Product
> got
= getAllProducts();
171 cout
<< "size of retrieved vector: " << got
.size() << endl
;
172 vector
<Product
>::iterator iter
= got
.begin();
173 while (iter
!= got
.end())
175 cout
<< "product " << (*iter
).getId() << " costs " << (*iter
).getPrice() << endl
;