-
Notifications
You must be signed in to change notification settings - Fork 3.9k
Expand file tree
/
Copy pathJedis.java
More file actions
10641 lines (9607 loc) · 389 KB
/
Jedis.java
File metadata and controls
10641 lines (9607 loc) · 389 KB
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
package redis.clients.jedis;
import static redis.clients.jedis.Protocol.Command.*;
import static redis.clients.jedis.Protocol.Keyword.*;
import static redis.clients.jedis.Protocol.SentinelKeyword.*;
import static redis.clients.jedis.Protocol.toByteArray;
import static redis.clients.jedis.util.SafeEncoder.encode;
import java.io.Closeable;
import java.net.URI;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.Arrays;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
import redis.clients.jedis.Protocol.*;
import redis.clients.jedis.args.*;
import redis.clients.jedis.commands.*;
import redis.clients.jedis.util.CompareCondition;
import redis.clients.jedis.exceptions.InvalidURIException;
import redis.clients.jedis.exceptions.JedisConnectionException;
import redis.clients.jedis.exceptions.JedisException;
import redis.clients.jedis.params.*;
import redis.clients.jedis.resps.*;
import redis.clients.jedis.util.JedisURIHelper;
import redis.clients.jedis.util.KeyValue;
import redis.clients.jedis.util.Pool;
/**
* Jedis is a lightweight Redis client that uses a single, non-pooled connection to Redis.
* <p>
* <b>Important:</b> For most production use cases, {@link RedisClient} is the recommended and
* preferred option. {@code RedisClient} provides connection pooling, better resource management,
* and improved performance for typical applications.
* </p>
* <p>
* <b>When to use Jedis:</b>
* </p>
* <ul>
* <li><b>Short-lived scripts or utilities:</b> When you need a simple, lightweight client for
* one-off operations or command-line tools.</li>
* <li><b>Testing and development:</b> For unit tests or local development where connection pooling
* overhead is unnecessary.</li>
* <li><b>Fine-grained connection control:</b> Advanced scenarios requiring explicit control over
* individual connections, such as managing connection lifecycle manually or implementing custom
* connection strategies.</li>
* <li><b>Single-threaded applications:</b> Applications that execute Redis commands sequentially
* from a single thread and don't benefit from connection pooling.</li>
* </ul>
* <p>
* <b>When to use RedisClient instead:</b>
* </p>
* <ul>
* <li><b>Production applications:</b> Any multi-threaded or high-throughput application should use
* {@link RedisClient} for its connection pooling capabilities.</li>
* <li><b>Web applications:</b> Server applications handling concurrent requests benefit from
* connection pooling to avoid connection overhead.</li>
* <li><b>Long-running services:</b> Applications that maintain persistent connections to Redis
* should use {@link RedisClient} for better resource management.</li>
* <li><b>Default choice:</b> If you're unsure which to use, choose {@link RedisClient}.</li>
* </ul>
* <p>
* <b>Usage example:</b>
* </p>
*
* <pre>
* {
* @code
* // Simple usage for a short-lived operation
* try (Jedis jedis = new Jedis("localhost", 6379)) {
* jedis.set("key", "value");
* String value = jedis.get("key");
* }
* }
* </pre>
* <p>
* <b>Note:</b> Each {@code Jedis} instance maintains a single connection. For concurrent access
* from multiple threads, either use {@link RedisClient} with connection pooling, or create
* separate {@code Jedis} instances per thread (not recommended for production).
* </p>
*
* @see RedisClient for the recommended pooled client for production use
* @see JedisPool for legacy pooled connections (deprecated, use RedisClient instead)
*/
public class Jedis implements ServerCommands, DatabaseCommands, JedisCommands, JedisBinaryCommands,
ControlCommands, ControlBinaryCommands, ClusterCommands, ModuleCommands, GenericControlCommands,
SentinelCommands, CommandCommands, Closeable {
protected final Connection connection;
private final CommandObjects commandObjects = new CommandObjects();
private int db = 0;
private Transaction transaction = null;
private boolean isInMulti = false;
private boolean isInWatch = false;
private Pipeline pipeline = null;
protected static final byte[][] DUMMY_ARRAY = new byte[0][];
private Pool<Jedis> dataSource = null;
public Jedis() {
connection = new Connection();
}
/**
* This constructor only accepts a URI string. {@link JedisURIHelper#isValid(java.net.URI)} can be
* used before this.
* @param url
*/
public Jedis(final String url) {
this(URI.create(url));
}
public Jedis(final HostAndPort hp) {
connection = new Connection(hp);
}
public Jedis(final String host, final int port) {
connection = new Connection(host, port);
}
public Jedis(final String host, final int port, final JedisClientConfig config) {
this(new HostAndPort(host, port), config);
}
public Jedis(final HostAndPort hostPort, final JedisClientConfig config) {
connection = new Connection(hostPort, config);
RedisProtocol proto = config.getRedisProtocol();
if (proto != null) commandObjects.setProtocol(proto);
}
public Jedis(final String host, final int port, final boolean ssl) {
this(host, port, DefaultJedisClientConfig.builder().ssl(ssl).build());
}
public Jedis(final String host, final int port, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(host, port, DefaultJedisClientConfig.builder().ssl(ssl)
.sslSocketFactory(sslSocketFactory).sslParameters(sslParameters)
.hostnameVerifier(hostnameVerifier).build());
}
public Jedis(final String host, final int port, final int timeout) {
this(host, port, timeout, timeout);
}
public Jedis(final String host, final int port, final int timeout, final boolean ssl) {
this(host, port, timeout, timeout, ssl);
}
public Jedis(final String host, final int port, final int timeout, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(host, port, timeout, timeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier);
}
public Jedis(final String host, final int port, final int connectionTimeout,
final int soTimeout) {
this(host, port, DefaultJedisClientConfig.builder()
.connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).build());
}
public Jedis(final String host, final int port, final int connectionTimeout,
final int soTimeout, final int infiniteSoTimeout) {
this(host, port, DefaultJedisClientConfig.builder()
.connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout)
.blockingSocketTimeoutMillis(infiniteSoTimeout).build());
}
public Jedis(final String host, final int port, final int connectionTimeout,
final int soTimeout, final boolean ssl) {
this(host, port, DefaultJedisClientConfig.builder()
.connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl)
.build());
}
public Jedis(final String host, final int port, final int connectionTimeout,
final int soTimeout, final boolean ssl, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(host, port, DefaultJedisClientConfig.builder()
.connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl)
.sslSocketFactory(sslSocketFactory).sslParameters(sslParameters)
.hostnameVerifier(hostnameVerifier).build());
}
public Jedis(final String host, final int port, final int connectionTimeout,
final int soTimeout, final int infiniteSoTimeout, final boolean ssl,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(host, port, DefaultJedisClientConfig.builder()
.connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout)
.blockingSocketTimeoutMillis(infiniteSoTimeout).ssl(ssl)
.sslSocketFactory(sslSocketFactory).sslParameters(sslParameters)
.hostnameVerifier(hostnameVerifier).build());
}
public Jedis(URI uri) {
if (!JedisURIHelper.isValid(uri)) {
throw new InvalidURIException(String.format(
"Cannot open Redis connection due invalid URI \"%s\".", uri.toString()));
}
connection = new Connection(new HostAndPort(uri.getHost(), uri.getPort()),
DefaultJedisClientConfig.builder().user(JedisURIHelper.getUser(uri))
.password(JedisURIHelper.getPassword(uri)).database(JedisURIHelper.getDBIndex(uri))
.protocol(JedisURIHelper.getRedisProtocol(uri))
.ssl(JedisURIHelper.isRedisSSLScheme(uri)).build());
}
public Jedis(URI uri, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(uri, DefaultJedisClientConfig.builder().sslSocketFactory(sslSocketFactory)
.sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build());
}
public Jedis(final URI uri, final int timeout) {
this(uri, timeout, timeout);
}
public Jedis(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier);
}
public Jedis(final URI uri, final int connectionTimeout, final int soTimeout) {
this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout)
.socketTimeoutMillis(soTimeout).build());
}
public Jedis(final URI uri, final int connectionTimeout, final int soTimeout,
final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters,
final HostnameVerifier hostnameVerifier) {
this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout)
.socketTimeoutMillis(soTimeout).sslSocketFactory(sslSocketFactory)
.sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build());
}
public Jedis(final URI uri, final int connectionTimeout, final int soTimeout,
final int infiniteSoTimeout, final SSLSocketFactory sslSocketFactory,
final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) {
this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout)
.socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout)
.sslSocketFactory(sslSocketFactory).sslParameters(sslParameters)
.hostnameVerifier(hostnameVerifier).build());
}
/**
* Create a new Jedis with the provided URI and JedisClientConfig object. Note that all fields
* that can be parsed from the URI will be used instead of the corresponding configuration values. This includes
* the following fields: user, password, database, protocol version, and whether to use SSL.
*
* For example, if the URI is "redis://user:password@localhost:6379/1", the user and password fields will be set
* to "user" and "password" respectively, the database field will be set to 1. Those fields will be ignored
* from the JedisClientConfig object.
*
* @param uri The URI to connect to
* @param config The JedisClientConfig object to use
*/
public Jedis(final URI uri, JedisClientConfig config) {
if (!JedisURIHelper.isValid(uri)) {
throw new InvalidURIException(String.format(
"Cannot open Redis connection due invalid URI \"%s\".", uri.toString()));
}
connection = new Connection(new HostAndPort(uri.getHost(), uri.getPort()),
DefaultJedisClientConfig.builder()
.connectionTimeoutMillis(config.getConnectionTimeoutMillis())
.socketTimeoutMillis(config.getSocketTimeoutMillis())
.blockingSocketTimeoutMillis(config.getBlockingSocketTimeoutMillis())
.user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri))
.database(JedisURIHelper.getDBIndex(uri)).clientName(config.getClientName())
.protocol(JedisURIHelper.getRedisProtocol(uri))
.ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(config.getSslSocketFactory())
.sslParameters(config.getSslParameters()).hostnameVerifier(config.getHostnameVerifier())
.build());
RedisProtocol proto = config.getRedisProtocol();
if (proto != null) commandObjects.setProtocol(proto);
}
public Jedis(final JedisSocketFactory jedisSocketFactory) {
connection = new Connection(jedisSocketFactory);
}
public Jedis(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) {
connection = new Connection(jedisSocketFactory, clientConfig);
RedisProtocol proto = clientConfig.getRedisProtocol();
if (proto != null) commandObjects.setProtocol(proto);
}
public Jedis(final Connection connection) {
this.connection = connection;
}
@Override
public String toString() {
return "Jedis{" + connection + '}';
}
// Legacy
public Connection getClient() {
return getConnection();
}
public Connection getConnection() {
return connection;
}
// Legacy
public void connect() {
connection.connect();
}
/**
* Closing the socket will disconnect the server connection.
*/
public void disconnect() {
connection.disconnect();
}
public boolean isConnected() {
return connection.isConnected();
}
public boolean isBroken() {
return connection.isBroken();
}
public void resetState() {
if (isConnected()) {
if (transaction != null) {
transaction.close();
}
if (pipeline != null) {
pipeline.close();
}
// connection.resetState();
if (isInWatch) {
connection.sendCommand(UNWATCH);
connection.getStatusCodeReply();
isInWatch = false;
}
}
transaction = null;
pipeline = null;
}
protected void setDataSource(Pool<Jedis> jedisPool) {
this.dataSource = jedisPool;
}
@Override
public void close() {
if (dataSource != null) {
Pool<Jedis> pool = this.dataSource;
this.dataSource = null;
if (isBroken()) {
pool.returnBrokenResource(this);
} else {
pool.returnResource(this);
}
} else {
connection.close();
}
}
// Legacy
public Transaction multi() {
transaction = new Transaction(getConnection()) {
@Override
protected void onAfterExec() {
resetState();
}
@Override
protected void onAfterDiscard() {
resetState();
}
};
return transaction;
}
// Legacy
public Pipeline pipelined() {
pipeline = new Pipeline(this);
return pipeline;
}
// Legacy
protected void checkIsInMultiOrPipeline() {
// if (connection.isInMulti()) {
if (transaction != null) {
throw new IllegalStateException(
"Cannot use Jedis when in Multi. Please use Transaction or reset jedis state.");
} else if (pipeline != null && pipeline.hasPipelinedResponse()) {
throw new IllegalStateException(
"Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state.");
}
}
public int getDB() {
return this.db;
}
/**
* @return <code>PONG</code>
*/
@Override
public String ping() {
checkIsInMultiOrPipeline();
connection.sendCommand(Command.PING);
return connection.getStatusCodeReply();
}
/**
* Works same as {@link Jedis#ping()} but returns argument message instead of <code>PONG</code>.
* @param message
* @return message
*/
public byte[] ping(final byte[] message) {
checkIsInMultiOrPipeline();
connection.sendCommand(Command.PING, message);
return connection.getBinaryBulkReply();
}
/**
* Select the DB with having the specified zero-based numeric index. For default every new
* connection is automatically selected to DB 0.
* @param index
* @return OK
*/
@Override
public String select(final int index) {
checkIsInMultiOrPipeline();
connection.sendCommand(SELECT, toByteArray(index));
String statusCodeReply = connection.getStatusCodeReply();
this.db = index;
return statusCodeReply;
}
@Override
public String swapDB(final int index1, final int index2) {
checkIsInMultiOrPipeline();
connection.sendCommand(SWAPDB, toByteArray(index1), toByteArray(index2));
return connection.getStatusCodeReply();
}
/**
* Delete all the keys of the currently selected DB. This command never fails.
* @return OK
*/
@Override
public String flushDB() {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.flushDB());
}
/**
* Delete all the keys of the currently selected DB. This command never fails.
* @param flushMode
* @return OK
*/
@Override
public String flushDB(FlushMode flushMode) {
checkIsInMultiOrPipeline();
connection.sendCommand(FLUSHDB, flushMode.getRaw());
return connection.getStatusCodeReply();
}
/**
* Delete all the keys of all the existing databases, not just the currently selected one. This
* command never fails.
* @return OK
*/
@Override
public String flushAll() {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.flushAll());
}
/**
* Delete all the keys of all the existing databases, not just the currently selected one. This
* command never fails.
* @param flushMode
* @return OK
*/
@Override
public String flushAll(FlushMode flushMode) {
checkIsInMultiOrPipeline();
connection.sendCommand(FLUSHALL, flushMode.getRaw());
return connection.getStatusCodeReply();
}
/**
* COPY source destination [DB destination-db] [REPLACE]
*
* @param srcKey the source key.
* @param dstKey the destination key.
* @param db
* @param replace
*/
@Override
public boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.copy(srcKey, dstKey, db, replace));
}
/**
* COPY source destination [DB destination-db] [REPLACE]
*
* @param srcKey the source key.
* @param dstKey the destination key.
* @param replace
*/
@Override
public boolean copy(byte[] srcKey, byte[] dstKey, boolean replace) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.copy(srcKey, dstKey, replace));
}
/**
* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1
* GB).
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return OK
*/
@Override
public String set(final byte[] key, final byte[] value) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.set(key, value));
}
/**
* Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1
* GB).
* @param key
* @param value
* @param params NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the
* key if it already exists. EX|PX, expire time units: EX = seconds; PX = milliseconds
* @return simple-string-reply {@code OK} if {@code SET} was executed correctly, or {@code null}
* if the {@code SET} operation was not performed because the user specified the NX or XX option
* but the condition was not met.
*/
@Override
public String set(final byte[] key, final byte[] value, final SetParams params) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.set(key, value, params));
}
/**
* Get the value of the specified key. If the key does not exist the special value 'nil' is
* returned. If the value stored at key is not a string an error is returned because GET can only
* handle string values.
* <p>
* Time complexity: O(1)
* @param key
* @return Bulk reply
*/
@Override
public byte[] get(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.get(key));
}
@Override
public byte[] digestKey(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.digestKey(key));
}
@Override
public byte[] setGet(final byte[] key, final byte[] value) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.setGet(key, value));
}
@Override
public byte[] setGet(final byte[] key, final byte[] value, final SetParams params) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.setGet(key, value, params));
}
/**
* Get the value of key and delete the key. This command is similar to GET, except for the fact
* that it also deletes the key on success (if and only if the key's value type is a string).
* <p>
* Time complexity: O(1)
* @param key
* @return The value of key
*/
@Override
public byte[] getDel(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.getDel(key));
}
@Override
public byte[] getEx(final byte[] key, final GetExParams params) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.getEx(key, params));
}
/**
* Test if the specified keys exist. The command returns the number of keys exist.
* Time complexity: O(N)
* @param keys
* @return An integer greater than 0 if one or more keys exist, 0 if none of the specified keys exist
*/
@Override
public long exists(final byte[]... keys) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.exists(keys));
}
/**
* Test if the specified key exists. The command returns true if the key exists, otherwise false is
* returned. Note that even keys set with an empty string as value will return true. Time
* complexity: O(1)
* @param key
* @return {@code true} if the key exists, otherwise {@code false}
*/
@Override
public boolean exists(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.exists(key));
}
/**
* Remove the specified keys. If a given key does not exist no operation is performed for this
* key. The command returns the number of keys removed. Time complexity: O(1)
* @param keys
* @return The number of keys that were removed
*/
@Override
public long del(final byte[]... keys) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.del(keys));
}
@Override
public long delex(final byte[] key, final CompareCondition condition) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.delex(key, condition));
}
@Override
public long del(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.del(key));
}
/**
* This command is very similar to DEL: it removes the specified keys. Just like DEL a key is
* ignored if it does not exist. However, the command performs the actual memory reclaiming in a
* different thread, so it is not blocking, while DEL is. This is where the command name comes
* from: the command just unlinks the keys from the keyspace. The actual removal will happen later
* asynchronously.
* <p>
* Time complexity: O(1) for each key removed regardless of its size. Then the command does O(N)
* work in a different thread in order to reclaim memory, where N is the number of allocations the
* deleted objects where composed of.
* @param keys
* @return The number of keys that were unlinked
*/
@Override
public long unlink(final byte[]... keys) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.unlink(keys));
}
@Override
public long unlink(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.unlink(key));
}
/**
* Return the type of the value stored at key in form of a string. The type can be one of "none",
* "string", "list", "set". "none" is returned if the key does not exist. Time complexity: O(1)
* @param key
* @return "none" if the key does not exist, "string" if the key contains a String value, "list"
* if the key contains a List value, "set" if the key contains a Set value, "zset" if the key
* contains a Sorted Set value, "hash" if the key contains a Hash value
*/
@Override
public String type(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.type(key));
}
/**
* Returns all the keys matching the glob-style pattern as space separated strings. For example if
* you have in the database the keys "foo" and "foobar" the command "KEYS foo*" will return
* "foo foobar".
* <p>
* Note that while the time complexity for this operation is O(n) the constant times are pretty
* low. For example Redis running on an entry level laptop can scan a 1 million keys database in
* 40 milliseconds. <b>Still it's better to consider this one of the slow commands that may ruin
* the DB performance if not used with care.</b>
* <p>
* In other words this command is intended only for debugging and special operations like creating
* a script to change the DB schema. Don't use it in your normal code. Use Redis Sets in order to
* group together a subset of objects.
* <p>
* Glob style patterns examples:
* <ul>
* <li>h?llo will match hello hallo hhllo
* <li>h*llo will match hllo heeeello
* <li>h[ae]llo will match hello and hallo, but not hillo
* </ul>
* <p>
* Use \ to escape special chars if you want to match them verbatim.
* <p>
* Time complexity: O(n) (with n being the number of keys in the DB, and assuming keys and pattern
* of limited length)
* @param pattern
* @return Multi bulk reply
*/
@Override
public Set<byte[]> keys(final byte[] pattern) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.keys(pattern));
}
/**
* Return a randomly selected key from the currently selected DB.
* <p>
* Time complexity: O(1)
* @return The randomly selected key or an empty string is the database is empty
*/
@Override
public byte[] randomBinaryKey() {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.randomBinaryKey());
}
/**
* Atomically renames the key oldkey to newkey. If the source and destination name are the same an
* error is returned. If newkey already exists it is overwritten.
* <p>
* Time complexity: O(1)
* @param oldkey
* @param newkey
* @return OK
*/
@Override
public String rename(final byte[] oldkey, final byte[] newkey) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.rename(oldkey, newkey));
}
/**
* Rename oldkey into newkey but fails if the destination key newkey already exists.
* <p>
* Time complexity: O(1)
* @param oldkey
* @param newkey
* @return 1 if the key was renamed 0 if the target key already exist
*/
@Override
public long renamenx(final byte[] oldkey, final byte[] newkey) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.renamenx(oldkey, newkey));
}
/**
* Return the number of keys in the currently selected database.
* @return The number of keys
*/
@Override
public long dbSize() {
checkIsInMultiOrPipeline();
connection.sendCommand(DBSIZE);
return connection.getIntegerReply();
}
/**
* Set a timeout on the specified key. After the timeout the key will be automatically deleted by
* the server. A key with an associated timeout is said to be volatile in Redis terminology.
* <p>
* Volatile keys are stored on disk like the other keys, the timeout is persistent too like all
* the other aspects of the dataset. Saving a dataset containing expires and stopping the server
* does not stop the flow of time as Redis stores on disk the time when the key will no longer be
* available as Unix time, and not the remaining seconds.
* <p>
* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
* set. It is also possible to undo the expire at all turning the key into a normal key using the
* {@link Jedis#persist(byte[]) PERSIST} command.
* <p>
* Time complexity: O(1)
* @see <a href="http://redis.io/commands/expire">Expire Command</a>
* @param key
* @param seconds
* @return 1: the timeout was set. 0: the timeout was not set.
*/
@Override
public long expire(final byte[] key, final long seconds) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.expire(key, seconds));
}
@Override
public long expire(final byte[] key, final long seconds, final ExpiryOption expiryOption) {
checkIsInMultiOrPipeline();
return connection.executeCommand((commandObjects.expire(key, seconds, expiryOption)));
}
/**
* Set a timeout on the specified key. After the timeout the key will be automatically deleted by
* the server. A key with an associated timeout is said to be volatile in Redis terminology.
* <p>
* Volatile keys are stored on disk like the other keys, the timeout is persistent too like all
* the other aspects of the dataset. Saving a dataset containing expires and stopping the server
* does not stop the flow of time as Redis stores on disk the time when the key will no longer be
* available as Unix time, and not the remaining milliseconds.
* <p>
* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
* set. It is also possible to undo the expire at all turning the key into a normal key using the
* {@link Jedis#persist(byte[]) PERSIST} command.
* <p>
* Time complexity: O(1)
* @see <a href="http://redis.io/commands/pexpire">PEXPIRE Command</a>
* @param key
* @param milliseconds
* @return 1: the timeout was set. 0: the timeout was not set.
*/
@Override
public long pexpire(final byte[] key, final long milliseconds) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.pexpire(key, milliseconds));
}
@Override
public long pexpire(final byte[] key, final long milliseconds, final ExpiryOption expiryOption) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.pexpire(key, milliseconds, expiryOption));
}
@Override
public long expireTime(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand((commandObjects.expireTime(key)));
}
@Override
public long pexpireTime(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.pexpireTime(key));
}
/**
* EXPIREAT works exactly like {@link Jedis#expire(byte[], long) EXPIRE} but instead to get the
* number of seconds representing the Time To Live of the key as a second argument (that is a
* relative way of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp
* (Number of seconds elapsed since 1 Gen 1970).
* <p>
* EXPIREAT was introduced in order to implement the Append Only File persistence mode so that
* EXPIRE commands are automatically translated into EXPIREAT commands for the append only file.
* Of course EXPIREAT can also used by programmers that need a way to simply specify that a given
* key should expire at a given time in the future.
* <p>
* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire
* set. It is also possible to undo the expire at all turning the key into a normal key using the
* {@link Jedis#persist(byte[]) PERSIST} command.
* <p>
* Time complexity: O(1)
* @see <a href="http://redis.io/commands/expire">Expire Command</a>
* @param key
* @param unixTime
* @return 1: the timeout was set. 0: the timeout was not set since
* the key already has an associated timeout (this may happen only in Redis versions <
* 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist.
*/
@Override
public long expireAt(final byte[] key, final long unixTime) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.expireAt(key, unixTime));
}
@Override
public long expireAt(byte[] key, long unixTime, ExpiryOption expiryOption) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.expireAt(key, unixTime, expiryOption));
}
@Override
public long pexpireAt(final byte[] key, final long millisecondsTimestamp) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.pexpireAt(key, millisecondsTimestamp));
}
@Override
public long pexpireAt(byte[] key, long millisecondsTimestamp, ExpiryOption expiryOption) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.pexpireAt(key, millisecondsTimestamp, expiryOption));
}
/**
* The TTL command returns the remaining time to live in seconds of a key that has an
* {@link Jedis#expire(byte[], long) EXPIRE} set. This introspection capability allows a Redis
* connection to check how many seconds a given key will continue to be part of the dataset.
* @param key
* @return TTL in seconds, or a negative value in order to signal an error
*/
@Override
public long ttl(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.ttl(key));
}
/**
* Alters the last access time of a key(s). A key is ignored if it does not exist.
* Time complexity: O(N) where N is the number of keys that will be touched.
* @param keys
* @return The number of keys that were touched.
*/
@Override
public long touch(final byte[]... keys) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.touch(keys));
}
@Override
public long touch(final byte[] key) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.touch(key));
}
/**
* Move the specified key from the currently selected DB to the specified destination DB. Note
* that this command returns 1 only if the key was successfully moved, and 0 if the target key was
* already there or if the source key was not found at all, so it is possible to use MOVE as a
* locking primitive.
* @param key
* @param dbIndex
* @return 1 if the key was moved 0 if the key was not moved because
* already present on the target DB or was not found in the current DB.
*/
@Override
public long move(final byte[] key, final int dbIndex) {
checkIsInMultiOrPipeline();
connection.sendCommand(MOVE, key, toByteArray(dbIndex));
return connection.getIntegerReply();
}
/**
* GETSET is an atomic set this value and return the old value command. Set key to the string
* value and return the old value stored at key. The string can't be longer than 1073741824 bytes
* (1 GB).
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return Bulk reply
* @deprecated Use {@link Jedis#setGet(byte[], byte[])}.
*/
@Deprecated
@Override
public byte[] getSet(final byte[] key, final byte[] value) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.getSet(key, value));
}
/**
* Get the values of all the specified keys. If one or more keys don't exist or is not of type
* String, a 'nil' value is returned instead of the value of the specified key, but the operation
* never fails.
* <p>
* Time complexity: O(1) for every key
* @param keys
* @return Multi bulk reply
*/
@Override
public List<byte[]> mget(final byte[]... keys) {
checkIsInMultiOrPipeline();
return connection.executeCommand(commandObjects.mget(keys));
}
/**
* SETNX works exactly like {@link Jedis#set(byte[], byte[]) SET} with the only difference that if
* the key already exists no operation is performed. SETNX actually means "SET if Not eXists".
* <p>
* Time complexity: O(1)
* @param key
* @param value
* @return 1 if the key was set 0 if the key was not set
* @deprecated Use {@link Jedis#set(byte[], byte[], redis.clients.jedis.params.SetParams)} with {@link redis.clients.jedis.params.SetParams#nx()}.
* Deprecated in Jedis 7.3.0. Mirrors Redis deprecation since 2.6.12.
*/
@Deprecated