forked from mrpi/redis-cplusplus-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
redisclient.h
3195 lines (2688 loc) · 89 KB
/
redisclient.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* redisclient.h -- a C++ client library for redis.
*
* Copyright (c) 2009, Brian Hammond <brian at fictorial dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef REDISCLIENT_H
#define REDISCLIENT_H
#include <errno.h>
#include <sys/socket.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stdexcept>
#include <ctime>
#include <sstream>
#include <boost/concept_check.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/functional/hash.hpp>
#include <boost/foreach.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/random.hpp>
#include <boost/cstdint.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include "anet.h"
#define REDIS_LBR "\r\n"
#define REDIS_STATUS_REPLY_OK "OK"
#define REDIS_PREFIX_STATUS_REPLY_ERROR "-ERR "
#define REDIS_PREFIX_STATUS_REPLY_ERR_C '-'
#define REDIS_PREFIX_STATUS_REPLY_VALUE '+'
#define REDIS_PREFIX_SINGLE_BULK_REPLY '$'
#define REDIS_PREFIX_MULTI_BULK_REPLY '*'
#define REDIS_PREFIX_INT_REPLY ':'
#define REDIS_WHITESPACE " \f\n\r\t\v"
template<class Object >
struct make;
namespace redis
{
template<typename CONSISTENT_HASHER>
class base_client;
enum reply_t
{
no_reply,
status_code_reply,
error_reply,
int_reply,
bulk_reply,
multi_bulk_reply
};
struct connection_data
{
connection_data(const std::string & host = "localhost", uint16_t port = 6379, int dbindex = 0)
: host(host), port(port), dbindex(dbindex), socket(ANET_ERR)
{
}
bool operator==(const connection_data & other) const
{
if(host != other.host)
return false;
if(port != other.port)
return false;
if(dbindex != other.dbindex)
return false;
return true;
}
std::string host;
boost::uint16_t port;
int dbindex;
private:
int socket;
template<typename CONSISTENT_HASHER>
friend class base_client;
};
enum server_role
{
role_master,
role_slave
};
// Generic error that is thrown when communicating with the redis server.
class redis_error : public std::exception
{
public:
redis_error(const std::string & err) : err_(err) {}
virtual ~redis_error() throw () {}
operator const std::string () const { return err_; }
virtual const char* what() const throw ()
{
return err_.c_str();
}
private:
std::string err_;
};
// Some socket-level I/O or general connection error.
class connection_error : public redis_error
{
public:
connection_error(const std::string & err) : redis_error(err) {}
};
// Redis gave us a reply we were not expecting.
// Possibly an internal error (here or in redis, probably here).
class protocol_error : public redis_error
{
public:
protocol_error(const std::string & err) : redis_error(err) {};
};
// A key that you expected to exist does not in fact exist.
class key_error : public redis_error
{
public:
key_error(const std::string & err) : redis_error(err) {};
};
// A operation with time limit does not deliver an result early enough.
class timeout_error : public redis_error
{
public:
timeout_error(const std::string & err) : redis_error(err) {};
};
// A value of an expected type or other semantics was found to be invalid.
class value_error : public redis_error
{
public:
value_error(const std::string & err) : redis_error(err) {};
};
struct key
{
explicit key(const std::string & name)
: name(name)
{
}
std::string name;
};
class makecmd
{
public:
explicit makecmd(const std::string & cmd_name)
{
append(cmd_name);
//if (!finalize)
// buffer_ << " ";
}
const std::string & key_name() const
{
if(!key_name_)
throw std::runtime_error("No key defined!");
return *key_name_;
}
inline makecmd & operator<<(const key & datum)
{
if(key_name_)
throw std::runtime_error("You could not add a second key");
else
key_name_ = datum.name;
append(datum.name);
return *this;
}
inline makecmd & operator<<(const std::string & datum)
{
append(datum);
return *this;
}
template <typename T>
makecmd & operator<<(T const & datum)
{
append( boost::lexical_cast<std::string>(datum) );
return *this;
}
makecmd & operator<<(const std::vector<std::string> & data)
{
lines_.insert( lines_.end(), data.begin(), data.end() );
return *this;
}
template <typename T>
makecmd & operator<<(const std::vector<T> & data)
{
size_t n = data.size();
for (size_t i = 0; i < n; ++i)
{
append( boost::lexical_cast<std::string>( data[i] ) );
//if (i < n - 1)
// buffer_ << " ";
}
return *this;
}
operator std::string () const
{
std::ostringstream oss;
size_t n = lines_.size();
oss << REDIS_PREFIX_MULTI_BULK_REPLY << n << REDIS_LBR;
for (size_t i = 0; i < n; ++i)
{
const std::string & param = lines_[i];
oss << REDIS_PREFIX_SINGLE_BULK_REPLY << param.size() << REDIS_LBR;
oss << param << REDIS_LBR;
}
return oss.str();
}
private:
void append(const std::string & param)
{
lines_.push_back(param);
}
std::vector<std::string> lines_;
boost::optional<std::string> key_name_;
};
template<typename CONSISTENT_HASHER>
class base_client;
typedef boost::variant< std::string, int, std::vector<std::string> > reply_val_t;
typedef std::pair<reply_t, reply_val_t> reply_data_t;
class command
{
private:
std::string request_;
std::string hash_key_;
reply_data_t reply_;
void check_reply_t(reply_t reply_type) const
{
if( reply_.first != reply_type )
throw std::runtime_error("invalid reply type");
}
void set_reply(const reply_data_t & reply)
{
reply_ = reply;
}
template<typename CONSISTENT_HASHER>
friend class base_client;
public:
command( const makecmd & cmd_input )
: request_(cmd_input), hash_key_(cmd_input.key_name())
{
reply_.first = no_reply;
}
reply_t reply_type() const
{
return reply_.first;
}
const std::string & get_status_code_reply() const
{
check_reply_t(status_code_reply);
return boost::get<std::string>(reply_.second);
}
const std::string & get_error_reply() const
{
check_reply_t(error_reply);
return boost::get<std::string>(reply_.second);
}
int get_int_reply() const
{
check_reply_t(int_reply);
return boost::get<int>(reply_.second);
}
const std::string & get_bulk_reply() const
{
check_reply_t(bulk_reply);
return boost::get<std::string>(reply_.second);
}
const std::vector<std::string> & get_multi_bulk_reply() const
{
check_reply_t(multi_bulk_reply);
return boost::get< std::vector<std::string> >(reply_.second);
}
};
struct server_info
{
std::string version;
bool bgsave_in_progress;
unsigned long connected_clients;
unsigned long connected_slaves;
unsigned long used_memory;
unsigned long changes_since_last_save;
unsigned long last_save_time;
unsigned long total_connections_received;
unsigned long total_commands_processed;
unsigned long uptime_in_seconds;
unsigned long uptime_in_days;
server_role role;
unsigned short arch_bits;
std::string multiplexing_api;
std::map<std::string, std::string> param_map;
};
inline ssize_t recv_or_throw(int fd, void* buf, size_t n, int flags)
{
ssize_t bytes_received;
do
bytes_received = ::recv(fd, buf, n, flags);
while(bytes_received < static_cast<ssize_t>(0) && errno == EINTR);
if( bytes_received == static_cast<ssize_t>(0) )
throw connection_error("connection was closed");
// Handle receive errors. I overlooked it totally, thanks mkx!
if( bytes_received == static_cast<ssize_t>(-1) )
throw connection_error(std::string("recv error: ") + strerror(errno));
return bytes_received;
}
// You should construct a 'client' object per connection to a redis-server.
//
// Please read the online redis command reference:
// http://code.google.com/p/redis/wiki/CommandReference
//
// No provisions for customizing the allocator on the string/bulk value type
// (std::string) are provided. If needed, you can always change the
// string_type typedef in your local version.
template<typename CONSISTENT_HASHER>
class base_client
{
private:
void init(connection_data & con)
{
char err[ANET_ERR_LEN];
con.socket = anetTcpConnect(err, const_cast<char*>(con.host.c_str()), con.port);
if (con.socket == ANET_ERR)
{
std::ostringstream os;
os << err << " (redis://" << con.host << ':' << con.port << ")";
throw connection_error( os.str() );
}
anetTcpNoDelay(NULL, con.socket);
select(con.dbindex, con);
}
public:
typedef std::string string_type;
typedef std::vector<string_type> string_vector;
typedef std::pair<string_type, string_type> string_pair;
typedef std::vector<string_pair> string_pair_vector;
typedef std::pair<string_type, double> string_score_pair;
typedef std::vector<string_score_pair> string_score_vector;
typedef std::set<string_type> string_set;
typedef long int_type;
explicit base_client(const string_type & host = "localhost",
uint16_t port = 6379, int_type dbindex = 0)
{
connection_data con;
con.host = host;
con.port = port;
con.dbindex = dbindex;
init(con);
connections_.push_back(con);
}
template<typename CON_ITERATOR>
base_client(CON_ITERATOR begin, CON_ITERATOR end)
{
while(begin != end)
{
connection_data con = *begin;
init(con);
connections_.push_back(con);
begin++;
}
if( connections_.empty() )
throw std::runtime_error("No connections given!");
}
base_client<CONSISTENT_HASHER>* clone() const
{
return new base_client<CONSISTENT_HASHER>(connections_.begin(), connections_.end());
}
inline static string_type missing_value()
{
return "**nonexistent-key**";
}
enum datatype
{
datatype_none, // key doesn't exist
datatype_string,
datatype_list,
datatype_set,
datatype_zset,
datatype_hash,
datatype_unknown
};
int_type get_list(const string_type & key, string_vector & out)
{
return lrange(key, 0, -1, out);
}
void lrem_exact(const string_type & key,
int_type count,
const string_type & value)
{
if (lrem(key, count, value) != count)
throw value_error("failed to remove exactly N elements from list");
}
enum range_specifier
{
exclude_min = 1 << 0,
exclude_max = 1 << 1
};
enum aggregate_type
{
aggregate_sum = 1 << 0,
aggregate_min = 1 << 1,
aggregate_max = 1 << 2
};
enum sort_order
{
sort_order_ascending,
sort_order_descending
};
~base_client()
{
BOOST_FOREACH(connection_data & con, connections_)
{
if (con.socket != ANET_ERR)
close(con.socket);
}
}
const std::vector<connection_data> & connections() const
{
return connections_;
}
void auth(const string_type & pass)
{
if( connections_.size() > 1 )
throw std::runtime_error("feature is not available in cluster mode");
int socket = connections_[0].socket;
send_(socket, makecmd("AUTH") << pass);
recv_ok_reply_(socket);
}
void set(const string_type & key,
const string_type & value)
{
int socket = get_socket(key);
send_(socket, makecmd("SET") << key << value);
recv_ok_reply_(socket);
}
void mset( const string_vector & keys, const string_vector & values )
{
assert( keys.size() == values.size() );
std::map< int, boost::optional<makecmd> > socket_commands;
for(size_t i=0; i < keys.size(); i++)
{
int socket = get_socket(keys);
boost::optional<makecmd> & cmd = socket_commands[socket];
if(!cmd)
cmd = makecmd("MSET");
*cmd << keys[i] << values[i];
}
typedef std::pair< int, boost::optional<makecmd> > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
send_(sp.first, *sp.second);
}
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
recv_ok_reply_(sp.first);
}
}
void mset( const string_pair_vector & key_value_pairs )
{
std::map< int, boost::optional<makecmd> > socket_commands;
for(size_t i=0; i < key_value_pairs.size(); i++)
{
const string_type & key = key_value_pairs[i].first;
const string_type & value = key_value_pairs[i].second;
int socket = get_socket(key);
boost::optional<makecmd> & cmd = socket_commands[socket];
if(!cmd)
cmd = makecmd("MSET");
*cmd << key << value;
}
typedef std::pair< int, boost::optional<makecmd> > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
send_(sp.first, *sp.second);
}
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
recv_ok_reply_(sp.first);
}
}
private:
struct msetex_data
{
boost::optional<makecmd> mset_cmd;
std::string expire_cmds;
size_t count;
};
public:
void msetex( const string_pair_vector & key_value_pairs, int_type seconds )
{
std::map< int, msetex_data > socket_commands;
for(size_t i=0; i < key_value_pairs.size(); i++)
{
const string_type & key = key_value_pairs[i].first;
const string_type & value = key_value_pairs[i].second;
int socket = get_socket(key);
msetex_data & dat = socket_commands[socket];
boost::optional<makecmd> & cmd = dat.mset_cmd;
if(!cmd)
{
cmd = makecmd("MSET");
dat.count = 0;
}
*cmd << key << value;
std::string & expire_cmds = dat.expire_cmds;
expire_cmds += makecmd("EXPIRE") << key << seconds;
dat.count++;
}
typedef std::pair< int, msetex_data > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
std::string cmds = *sp.second.mset_cmd;
cmds += sp.second.expire_cmds;
send_(sp.first, cmds);
}
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
recv_ok_reply_(sp.first);
for(size_t i= 0; i < sp.second.count; i++)
recv_int_ok_reply_(sp.first);
}
}
string_type get(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("GET") << key);
return recv_bulk_reply_(socket);
}
string_type getset(const string_type & key, const string_type & value)
{
int socket = get_socket(key);
send_(socket, makecmd("GETSET") << key << value);
return recv_bulk_reply_(socket);
}
private:
struct connection_keys
{
boost::optional<makecmd> cmd;
/// Gives the position of the value in the original array
std::vector<size_t> indices;
};
public:
void exec(command & cmd)
{
int socket = get_socket(cmd.hash_key_);
send_( socket, cmd.request_ );
cmd.set_reply( recv_generic_reply_(socket) );
}
void exec(std::vector<command> & commands)
{
std::map< int, std::string > socket_commands;
for(size_t i=0; i < commands.size(); i++)
{
int socket = get_socket( commands[i].hash_key_ );
socket_commands[socket] += commands[i].request_;
}
typedef std::pair< int, std::string > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
send_(sp.first, sp.second);
}
for(size_t i=0; i < commands.size(); i++)
{
int socket = get_socket( commands[i].hash_key_ );
commands[i].set_reply( recv_generic_reply_(socket) );
}
}
void exec_transaction(std::vector<command> & commands)
{
int cmd_socket = -1;
std::string cmd_str = makecmd("MULTI");
for(size_t i=0; i < commands.size(); i++)
{
int socket = get_socket( commands[i].hash_key_ );
if( cmd_socket == -1 )
cmd_socket = socket;
else if( cmd_socket != socket )
throw std::runtime_error("calls in transaction map to different server!");
cmd_str += commands[i].request_;
}
cmd_str += makecmd("EXEC");
send_(cmd_socket, cmd_str);
recv_ok_reply_(cmd_socket); // MULTI => +OK
for(size_t i=0; i < commands.size(); i++)
{
std::string resp = recv_single_line_reply_(cmd_socket);
if( resp != "QUEUED" )
throw std::runtime_error("invalid state (expected 'QUEUED' in transaction but got '" + resp + "')");
}
if( read_line(cmd_socket)[0] != REDIS_PREFIX_MULTI_BULK_REPLY )
throw std::runtime_error("EXEC does not return a multi bulk reply");
for(size_t i=0; i < commands.size(); i++)
{
commands[i].set_reply( recv_generic_reply_(cmd_socket) );
}
}
void mget(const string_vector & keys, string_vector & out)
{
out = string_vector( keys.size() );
std::map< int, connection_keys > socket_commands;
for(size_t i=0; i < keys.size(); i++)
{
int socket = get_socket(keys[i]);
connection_keys & con_keys = socket_commands[socket];
boost::optional<makecmd> & cmd = con_keys.cmd;
if(!cmd)
cmd = makecmd("MGET");
*cmd << keys[i];
con_keys.indices.push_back(i);
}
typedef std::pair< int, connection_keys > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
send_(sp.first, *sp.second.cmd);
}
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
const connection_keys & con_keys = sp.second;
string_vector cur_out;
recv_multi_bulk_reply_(sp.first, cur_out);
for(size_t i=0; i < cur_out.size(); i++)
out[con_keys.indices[i]] = cur_out[i];
}
}
bool setnx(const string_type & key,
const string_type & value)
{
int socket = get_socket(key);
send_(socket, makecmd("SETNX") << key << value);
return recv_int_reply_(socket) == 1;
}
bool msetnx( const string_vector & keys, const string_vector & values )
{
assert( keys.size() == values.size() );
std::map< int, boost::optional<makecmd> > socket_commands;
for(size_t i=0; i < keys.size(); i++)
{
int socket = get_socket(keys);
boost::optional<makecmd> & cmd = socket_commands[socket];
if(!cmd)
cmd = makecmd("MSETNX");
*cmd << keys[i] << values[i];
}
if( socket_commands.size() > 1 )
throw std::runtime_error("feature is not available in cluster mode");
typedef std::pair< int, boost::optional<makecmd> > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
send_(sp.first, *sp.second);
recv_ok_reply_(sp.first);
}
}
bool msetnx( const string_pair_vector & key_value_pairs )
{
std::map< int, boost::optional<makecmd> > socket_commands;
for(size_t i=0; i < key_value_pairs.size(); i++)
{
int socket = get_socket(keys);
boost::optional<makecmd> & cmd = socket_commands[socket];
if(!cmd)
cmd = makecmd("MSETNX");
*cmd << key_value_pairs[i].first << key_value_pairs[i].second;
}
if( socket_commands.size() > 1 )
throw std::runtime_error("feature is not available in cluster mode");
typedef std::pair< int, boost::optional<makecmd> > sock_pair;
BOOST_FOREACH(const sock_pair & sp, socket_commands)
{
send_(sp.first, *sp.second);
recv_ok_reply_(sp.first);
}
}
void setex(const string_type & key, const string_type & value, unsigned int secs)
{
int socket = get_socket(key);
send_(socket, makecmd("SETEX") << key << secs << value);
recv_ok_reply_(socket);
}
size_t append(const string_type & key, const string_type & value)
{
int socket = get_socket(key);
send_(socket, makecmd("APPEND") << key << value);
int res = recv_int_reply_(socket);
if(res < 0)
throw protocol_error("expected value size");
assert( static_cast<size_t>(res) >= value.size() );
return static_cast<size_t>(res);
}
string_type substr(const string_type & key, int start, int end)
{
int socket = get_socket(key);
send_(socket, makecmd("SUBSTR") << key << start << end);
return recv_bulk_reply_(socket);
}
int_type incr(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("INCR") << key);
return recv_int_reply_(socket);
}
template<typename INT_TYPE>
INT_TYPE incr(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("INCR") << key);
return recv_int_reply_<INT_TYPE>(socket);
}
int_type incrby(const string_type & key, int_type by)
{
int socket = get_socket(key);
send_(socket, makecmd("INCRBY") << key << by);
return recv_int_reply_(socket);
}
template<typename INT_TYPE>
INT_TYPE incrby(const string_type & key, INT_TYPE by)
{
int socket = get_socket(key);
send_(socket, makecmd("INCRBY") << key << by);
return recv_int_reply_<INT_TYPE>(socket);
}
int_type decr(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("DECR") << key);
return recv_int_reply_(socket);
}
template<typename INT_TYPE>
INT_TYPE decr(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("DECR") << key);
return recv_int_reply_<INT_TYPE>(socket);
}
int_type decrby(const string_type & key, int_type by)
{
int socket = get_socket(key);
send_(socket, makecmd("DECRBY") << key << by);
return recv_int_reply_(socket);
}
template<typename INT_TYPE>
INT_TYPE decrby(const string_type & key, INT_TYPE by)
{
int socket = get_socket(key);
send_(socket, makecmd("DECRBY") << key << by);
return recv_int_reply_<INT_TYPE>(socket);
}
bool exists(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("EXISTS") << key);
return recv_int_reply_(socket) == 1;
}
bool del(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("DEL") << key);
return recv_int_reply_(socket) != 0;
}
template<typename ITERATOR>
bool del(ITERATOR begin, ITERATOR end)
{
std::map<int, string_vector> sock_key_map;
while( begin != end )
{
string_type key = *begin++;
sock_key_map[ get_socket(key) ].push_back(key);
}
typedef std::pair<const int, string_vector> sock_key_pair;
BOOST_FOREACH(const sock_key_pair & p, sock_key_map)
{
send_(p.first, makecmd("DEL") << p.second);
}
int_type res = false;
BOOST_FOREACH(const sock_key_pair & p, sock_key_map)
{
res += recv_int_reply_(p.first);
}
return res;
}
datatype type(const string_type & key)
{
int socket = get_socket(key);
send_(socket, makecmd("TYPE") << key);
std::string response = recv_single_line_reply_(socket);
if(response == "none") return datatype_none;
if(response == "string") return datatype_string;
if(response == "list") return datatype_list;
if(response == "set") return datatype_set;
if(response == "zset") return datatype_zset;
if(response == "hash") return datatype_hash;
#ifndef NDEBUG
std::cerr << "Got unknown datatype name: " << response << std::endl;
#endif // NDEBUG
return datatype_unknown;
}
int_type keys(const string_type & pattern, string_vector & out)
{
BOOST_FOREACH(const connection_data & con, connections_)
{
send_(con.socket, makecmd("KEYS") << pattern);
}
int_type res = 0;
BOOST_FOREACH(const connection_data & con, connections_)
{
res += recv_multi_bulk_reply_(con.socket, out);
}
return res;
}
string_type randomkey()
{
int socket = connections_[0].socket;
if( connections_.size() > 1 )
{
/*
* Select a random server if there are more then one
*/
boost::mt19937 gen;
boost::posix_time::ptime now = boost::posix_time::microsec_clock::local_time();
boost::posix_time::ptime epoch( boost::gregorian::date(1970, 1, 1) );
gen.seed( (now-epoch).total_seconds() );
boost::uniform_int<> dist(0, connections_.size()-1);
boost::variate_generator< boost::mt19937&, boost::uniform_int<> > die(gen, dist);
socket = connections_[die()].socket;
}
send_(socket, makecmd("RANDOMKEY") );
return recv_bulk_reply_(socket);
}