forked from naver/arcus-java-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemcachedClient.java
More file actions
2183 lines (2026 loc) · 78.3 KB
/
MemcachedClient.java
File metadata and controls
2183 lines (2026 loc) · 78.3 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
/*
* arcus-java-client : Arcus Java client
* Copyright 2010-2014 NAVER Corp.
* Copyright 2014-2022 JaM2in Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Copyright (c) 2006 Dustin Sallings <dustin@spy.net>
package net.spy.memcached;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.ConcurrentModificationException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.stream.Collectors;
import net.spy.memcached.compat.SpyThread;
import net.spy.memcached.internal.BroadcastFuture;
import net.spy.memcached.internal.BulkFuture;
import net.spy.memcached.internal.BulkGetFuture;
import net.spy.memcached.internal.GetFuture;
import net.spy.memcached.internal.OperationFuture;
import net.spy.memcached.internal.SingleElementInfiniteIterator;
import net.spy.memcached.internal.result.GetResult;
import net.spy.memcached.internal.result.GetResultImpl;
import net.spy.memcached.internal.result.GetsResultImpl;
import net.spy.memcached.ops.APIType;
import net.spy.memcached.ops.CASOperationStatus;
import net.spy.memcached.ops.CancelledOperationStatus;
import net.spy.memcached.ops.ConcatenationType;
import net.spy.memcached.ops.DeleteOperation;
import net.spy.memcached.ops.GetOperation;
import net.spy.memcached.ops.GetsOperation;
import net.spy.memcached.ops.Mutator;
import net.spy.memcached.ops.Operation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StatsOperation;
import net.spy.memcached.ops.StoreType;
import net.spy.memcached.transcoders.Transcoder;
/**
* Client to a memcached server.
*
* <h2>Basic usage</h2>
*
* <pre>{@code
* MemcachedClient c=new MemcachedClient(
* new InetSocketAddress("hostname", portNum));
*
* // Store a value (async) for one hour
* c.set("someKey", 3600, someObject);
* // Retrieve a value.
* Object myObject=c.get("someKey");
* }</pre>
*
* <h2>Advanced Usage</h2>
*
* <p>
* MemcachedClient may be processing a great deal of asynchronous messages or
* possibly dealing with an unreachable memcached, which may delay processing.
* If a memcached is disabled, for example, MemcachedConnection will continue
* to attempt to reconnect and replay pending operations until it comes back
* up. To prevent this from causing your application to hang, you can use
* one of the asynchronous mechanisms to time out a request and cancel the
* operation to the server.
* </p>
*
* <pre>{@code
* // Get a memcached client connected to several servers
* // over the binary protocol
* MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(),
* AddrUtil.getAddresses("server1:11211 server2:11211"));
*
* // Try to get a value, for up to 5 seconds, and cancel if it
* // doesn't return
* Object myObj = null;
* Future<Object> f = c.asyncGet("someKey");
* try {
* myObj = f.get(5, TimeUnit.SECONDS);
* // throws expecting InterruptedException, ExecutionException
* // or TimeoutException
* } catch (Exception e) { /* /
* // Since we don't need this, go ahead and cancel the operation.
* // This is not strictly necessary, but it'll save some work on
* // the server. It is okay to cancel it if running.
* f.cancel(true);
* // Do other timeout related stuff
* }
* }</pre>
*/
public class MemcachedClient extends SpyThread
implements MemcachedClientIF {
private volatile boolean running = true;
private volatile boolean shuttingDown = false;
protected final long operationTimeout;
private final MemcachedConnection conn;
protected final OperationFactory opFact;
protected final Transcoder<Object> transcoder;
protected final KeyValidator keyValidator;
private static final String DEFAULT_MEMCACHED_CLIENT_NAME = "MemcachedClient";
public static final int GET_BULK_CHUNK_SIZE = 200;
/**
* Get a memcached client operating on the specified memcached locations.
*
* @param name client name
* @param ia the memcached locations
* @throws IOException if connections cannot be established
*/
public MemcachedClient(String name, InetSocketAddress... ia) throws IOException {
this(new DefaultConnectionFactory(), name, Arrays.asList(ia));
}
/**
* Get a memcached client operating on the specified memcached locations.
*
* @param ia the memcached locations
* @throws IOException if connections cannot be established
*/
public MemcachedClient(InetSocketAddress... ia) throws IOException {
this(new DefaultConnectionFactory(), DEFAULT_MEMCACHED_CLIENT_NAME, Arrays.asList(ia));
}
/**
* Get a memcached client over the specified memcached locations.
*
* @param addrs the socket addrs
* @throws IOException if connections cannot be established
*/
public MemcachedClient(List<InetSocketAddress> addrs)
throws IOException {
this(new DefaultConnectionFactory(), DEFAULT_MEMCACHED_CLIENT_NAME, addrs);
}
/**
* Get a memcached client over the specified memcached locations.
*
* @param cf the connection factory to configure connections for this client
* @param addrs the socket addresses
* @throws IOException if connections cannot be established
*/
public MemcachedClient(ConnectionFactory cf, List<InetSocketAddress> addrs)
throws IOException {
this(cf, DEFAULT_MEMCACHED_CLIENT_NAME, addrs);
}
/**
* Get a memcached client over the specified memcached locations.
*
* @param cf the connection factory to configure connections for this client
* @param name client name
* @param addrs the socket addresses
* @throws IOException if connections cannot be established
*/
@SuppressWarnings("this-escape")
public MemcachedClient(ConnectionFactory cf, String name, List<InetSocketAddress> addrs)
throws IOException {
if (cf == null) {
throw new NullPointerException("Connection factory required");
}
if (name == null) {
throw new NullPointerException("Client name required");
}
if (addrs == null) {
throw new NullPointerException("Server list required");
}
if (addrs.isEmpty()) {
throw new IllegalArgumentException(
"You must have at least one server to connect to");
}
if (cf.getOperationTimeout() <= 0) {
throw new IllegalArgumentException(
"Operation timeout must be positive.");
}
transcoder = cf.getDefaultTranscoder();
opFact = cf.getOperationFactory();
assert opFact != null : "Connection factory failed to make op factory";
conn = cf.createConnection(name, addrs);
assert conn != null : "Connection factory failed to make a connection";
operationTimeout = cf.getOperationTimeout();
keyValidator = new KeyValidator(cf.getDelimiter());
setName("Memcached IO over " + conn);
setDaemon(cf.isDaemon());
start();
}
/**
* Get the addresses of available servers.
*
* <p>
* This is based on a snapshot in time so shouldn't be considered
* completely accurate, but is a useful for getting a feel for what's
* working and what's not working.
* </p>
*
* @return point-in-time view of currently available servers
*/
public Collection<SocketAddress> getAvailableServers() {
ArrayList<SocketAddress> rv = new ArrayList<>();
for (MemcachedNode node : conn.getLocator().getAll()) {
if (node.isActive()) {
rv.add(node.getSocketAddress());
}
}
return rv;
}
/**
* Get the addresses of unavailable servers.
*
* <p>
* This is based on a snapshot in time so shouldn't be considered
* completely accurate, but is a useful for getting a feel for what's
* working and what's not working.
* </p>
*
* @return point-in-time view of currently unavailable servers
*/
public Collection<SocketAddress> getUnavailableServers() {
ArrayList<SocketAddress> rv = new ArrayList<>();
for (MemcachedNode node : conn.getLocator().getAll()) {
if (!node.isActive()) {
rv.add(node.getSocketAddress());
}
}
return rv;
}
/**
* Get a read-only wrapper around the node locator wrapping this instance.
*
* @return this instance's NodeLocator
*/
public NodeLocator getNodeLocator() {
return conn.getLocator().getReadonlyCopy();
}
/**
* Get the default transcoder that's in use.
*
* @return this instance's Transcoder
*/
public Transcoder<Object> getTranscoder() {
return transcoder;
}
public OperationFactory getOpFact() {
return opFact;
}
protected void checkState() {
if (shuttingDown) {
throw new IllegalStateException("Shutting down");
}
assert isAlive() : "IO Thread is not running.";
}
/**
* (internal use) Add a raw operation to a numbered connection.
* This method is exposed for testing.
*
* @param key the key the operation is operating upon
* @param op the operation to perform
* @return the Operation
*/
public Operation addOp(final String key, final Operation op) {
keyValidator.validateKey(key);
checkState();
conn.addOperation(key, op);
return op;
}
public Operation addOp(final MemcachedNode node, final Operation op) {
checkState();
conn.addOperation(node, op);
return op;
}
protected void addOpMap(final Map<String, Operation> opMap) {
checkState();
for (Map.Entry<String, Operation> me : opMap.entrySet()) {
conn.addOperation(me.getKey(), me.getValue());
}
}
private <T> OperationFuture<Boolean> asyncStore(StoreType storeType, String key,
int exp, T value, Transcoder<T> tc) {
CachedData co = tc.encode(value);
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<Boolean> rv = new OperationFuture<>(latch,
operationTimeout);
Operation op = opFact.store(storeType, key, co.getFlags(),
exp, co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
rv.set(val.isSuccess(), val);
}
public void complete() {
latch.countDown();
}
});
rv.setOperation(op);
addOp(key, op);
return rv;
}
private OperationFuture<Boolean> asyncStore(StoreType storeType,
String key, int exp, Object value) {
return asyncStore(storeType, key, exp, value, transcoder);
}
private <T> OperationFuture<Boolean> asyncCat(
ConcatenationType catType, long cas, String key,
T value, Transcoder<T> tc) {
CachedData co = tc.encode(value);
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<Boolean> rv = new OperationFuture<>(latch,
operationTimeout);
Operation op = opFact.cat(catType, cas, key, co.getData(),
new OperationCallback() {
public void receivedStatus(OperationStatus val) {
rv.set(val.isSuccess(), val);
}
public void complete() {
latch.countDown();
}
});
rv.setOperation(op);
addOp(key, op);
return rv;
}
/**
* Append to an existing value in the cache.
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* @param cas cas identifier (ignored in the ascii protocol)
* @param key the key to whose value will be appended
* @param val the value to append
* @return a future indicating success, false if there was no change
* to the value
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public OperationFuture<Boolean> append(long cas, String key, Object val) {
return append(cas, key, val, transcoder);
}
/**
* Append to an existing value in the cache.
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* @param <T>
* @param cas cas identifier (ignored in the ascii protocol)
* @param key the key to whose value will be appended
* @param val the value to append
* @param tc the transcoder to serialize and deserialize the value
* @return a future indicating success
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<Boolean> append(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.append, cas, key, val, tc);
}
/**
* Prepend to an existing value in the cache.
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* @param cas cas identifier (ignored in the ascii protocol)
* @param key the key to whose value will be prepended
* @param val the value to append
* @return a future indicating success
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public OperationFuture<Boolean> prepend(long cas, String key, Object val) {
return prepend(cas, key, val, transcoder);
}
/**
* Prepend to an existing value in the cache.
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* @param <T>
* @param cas cas identifier (ignored in the ascii protocol)
* @param key the key to whose value will be prepended
* @param val the value to append
* @param tc the transcoder to serialize and deserialize the value
* @return a future indicating success
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<Boolean> prepend(long cas, String key, T val,
Transcoder<T> tc) {
return asyncCat(ConcatenationType.prepend, cas, key, val, tc);
}
/**
* Asynchronous CAS operation.
*
* @param <T>
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param value the new value
* @param tc the transcoder to serialize and deserialize the value
* @return a future that will indicate the status of the CAS
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<CASResponse> asyncCAS(String key, long casId, T value,
Transcoder<T> tc) {
return asyncCAS(key, casId, 0, value, tc);
}
/**
* Asynchronous CAS operation.
*
* @param <T>
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param exp the expiration of this object
* @param value the new value
* @param tc the transcoder to serialize and deserialize the value
* @return a future that will indicate the status of the CAS
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<CASResponse> asyncCAS(String key, long casId, int exp, T value,
Transcoder<T> tc) {
CachedData co = tc.encode(value);
final CountDownLatch latch = new CountDownLatch(1);
final OperationFuture<CASResponse> rv = new OperationFuture<>(
latch, operationTimeout);
Operation op = opFact.cas(StoreType.set, key, casId, co.getFlags(), exp,
co.getData(), new OperationCallback() {
public void receivedStatus(OperationStatus val) {
if (val instanceof CASOperationStatus) {
rv.set(((CASOperationStatus) val).getCASResponse(), val);
} else if (val instanceof CancelledOperationStatus) {
rv.set(CASResponse.CANCELED, val);
} else {
rv.set(CASResponse.UNDEFINED, val);
}
}
public void complete() {
latch.countDown();
}
});
rv.setOperation(op);
addOp(key, op);
return rv;
}
/**
* Asynchronous CAS operation using the default transcoder.
*
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param value the new value
* @return a future that will indicate the status of the CAS
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public OperationFuture<CASResponse> asyncCAS(String key, long casId, Object value) {
return asyncCAS(key, casId, value, transcoder);
}
/**
* Asynchronous CAS operation using the default transcoder with expiration.
*
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param exp the expiration of this object
* @param value the new value
* @return a future that will indicate the status of the CAS
* @throws IllegalStateException in the rare circumstance where queue is too
* full to accept any more requests
*/
public OperationFuture<CASResponse> asyncCAS(String key, long casId,
int exp, Object value) {
return asyncCAS(key, casId, exp, value, transcoder);
}
/**
* Perform a synchronous CAS operation.
*
* @param <T>
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param value the new value
* @param tc the transcoder to serialize and deserialize the value
* @return a CASResponse
* @throws OperationTimeoutException if global operation timeout is
* exceeded
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> CASResponse cas(String key, long casId, T value,
Transcoder<T> tc) {
return cas(key, casId, 0, value, tc);
}
/**
* Perform a synchronous CAS operation.
*
* @param <T>
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param exp the expiration of this object
* @param value the new value
* @param tc the transcoder to serialize and deserialize the value
* @return a CASResponse
* @throws OperationTimeoutException if global operation timeout is
* exceeded
* @throws CancellationException if operation was canceled
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> CASResponse cas(String key, long casId, int exp, T value,
Transcoder<T> tc) {
OperationFuture<CASResponse> future = asyncCAS(key, casId, exp, value, tc);
return getFromFuture(future);
}
private <T> T getFromFuture(Future<T> future) {
try {
return future.get(operationTimeout, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
future.cancel(true);
throw new RuntimeException("Interrupted waiting for value", e);
} catch (ExecutionException e) {
future.cancel(true);
if (e.getCause() instanceof CancellationException) {
throw (CancellationException) e.getCause();
} else {
throw new RuntimeException("Exception waiting for value", e);
}
} catch (TimeoutException e) {
future.cancel(true);
throw new OperationTimeoutException(e);
}
}
/**
* Perform a synchronous CAS operation with the default transcoder.
*
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param value the new value
* @return a CASResponse
* @throws OperationTimeoutException if the global operation timeout is
* exceeded
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public CASResponse cas(String key, long casId, Object value) {
return cas(key, casId, value, transcoder);
}
/**
* Perform a synchronous CAS operation with the default transcoder.
*
* @param key the key
* @param casId the CAS identifier (from a gets operation)
* @param exp the expiration of this object
* @param value the new value
* @return a CASResponse
* @throws OperationTimeoutException if the global operation timeout is exceeded
* @throws IllegalStateException in the rare circumstance where queue is too
* full to accept any more requests
*/
public CASResponse cas(String key, long casId, int exp, Object value) {
return cas(key, casId, exp, value, transcoder);
}
/**
* Add an object to the cache iff it does not exist already.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param <T>
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @param tc the transcoder to serialize and deserialize the value
* @return a future representing the processing of this operation
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<Boolean> add(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.add, key, exp, o, tc);
}
/**
* Add an object to the cache (using the default transcoder)
* iff it does not exist already.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @return a future representing the processing of this operation
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public OperationFuture<Boolean> add(String key, int exp, Object o) {
return asyncStore(StoreType.add, key, exp, o, transcoder);
}
/**
* Set an object in the cache regardless of any existing value.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param <T>
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @param tc the transcoder to serialize and deserialize the value
* @return a future representing the processing of this operation
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<Boolean> set(String key, int exp, T o, Transcoder<T> tc) {
return asyncStore(StoreType.set, key, exp, o, tc);
}
/**
* Set an object in the cache (using the default transcoder)
* regardless of any existing value.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @return a future representing the processing of this operation
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public OperationFuture<Boolean> set(String key, int exp, Object o) {
return asyncStore(StoreType.set, key, exp, o, transcoder);
}
/**
* Replace an object with the given value iff there is already a value
* for the given key.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param <T>
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @param tc the transcoder to serialize and deserialize the value
* @return a future representing the processing of this operation
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> OperationFuture<Boolean> replace(String key, int exp, T o,
Transcoder<T> tc) {
return asyncStore(StoreType.replace, key, exp, o, tc);
}
/**
* Replace an object with the given value (transcoded with the default
* transcoder) iff there is already a value for the given key.
*
* <p>
* The <code>exp</code> value is passed along to memcached exactly as
* given, and will be processed per the memcached protocol specification:
* </p>
*
* <p>Note that the return will be false any time a mutation has not
* occurred.</p>
*
* <blockquote>
* <p>
* The actual value sent may either be
* Unix time (number of seconds since January 1, 1970, as a 32-bit
* value), or a number of seconds starting from current time. In the
* latter case, this number of seconds may not exceed 60*60*24*30 (number
* of seconds in 30 days); if the number sent by a client is larger than
* that, the server will consider it to be real Unix time value rather
* than an offset from current time.
* </p>
* </blockquote>
*
* @param key the key under which this object should be added.
* @param exp the expiration of this object
* @param o the object to store
* @return a future representing the processing of this operation
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public OperationFuture<Boolean> replace(String key, int exp, Object o) {
return asyncStore(StoreType.replace, key, exp, o, transcoder);
}
/**
* Get the given key asynchronously.
*
* @param <T>
* @param key the key to fetch
* @param tc the transcoder to serialize and deserialize value
* @return a future that will hold the return value of the fetch
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> GetFuture<T> asyncGet(final String key, final Transcoder<T> tc) {
final CountDownLatch latch = new CountDownLatch(1);
final GetFuture<T> future = new GetFuture<>(latch, operationTimeout);
Operation op = opFact.get(key,
new GetOperation.Callback() {
private GetResult<T> result = null;
public void receivedStatus(OperationStatus status) {
future.set(result, status);
}
public void gotData(String k, int flags, byte[] data) {
assert key.equals(k) : "Wrong key returned";
result = new GetResultImpl<>(new CachedData(flags, data, tc.getMaxSize()), tc);
}
public void complete() {
latch.countDown();
}
});
future.setOperation(op);
addOp(key, op);
return future;
}
/**
* Get the given key asynchronously and decode with the default
* transcoder.
*
* @param key the key to fetch
* @return a future that will hold the return value of the fetch
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public GetFuture<Object> asyncGet(final String key) {
return asyncGet(key, transcoder);
}
/**
* Gets (with CAS support) the given key asynchronously.
*
* @param <T>
* @param key the key to fetch
* @param tc the transcoder to serialize and deserialize value
* @return a future that will hold the return value of the fetch
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> GetFuture<CASValue<T>> asyncGets(final String key,
final Transcoder<T> tc) {
final CountDownLatch latch = new CountDownLatch(1);
final GetFuture<CASValue<T>> rv = new GetFuture<>(latch, operationTimeout);
Operation op = opFact.gets(key,
new GetsOperation.Callback() {
private GetResult<CASValue<T>> val = null;
public void receivedStatus(OperationStatus status) {
rv.set(val, status);
}
public void gotData(String k, int flags, long cas, byte[] data) {
assert key.equals(k) : "Wrong key returned";
assert cas > 0 : "CAS was less than zero: " + cas;
val = new GetsResultImpl<>(cas, new CachedData(flags, data, tc.getMaxSize()), tc);
}
public void complete() {
latch.countDown();
}
});
rv.setOperation(op);
addOp(key, op);
return rv;
}
/**
* Gets (with CAS support) the given key asynchronously and decode using
* the default transcoder.
*
* @param key the key to fetch
* @return a future that will hold the return value of the fetch
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public GetFuture<CASValue<Object>> asyncGets(final String key) {
return asyncGets(key, transcoder);
}
/**
* Gets (with CAS support) with a single key.
*
* @param <T>
* @param key the key to get
* @param tc the transcoder to serialize and deserialize value
* @return the result from the cache and CAS id (null if there is none)
* @throws OperationTimeoutException if global operation timeout is
* exceeded
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> CASValue<T> gets(String key, Transcoder<T> tc) {
GetFuture<CASValue<T>> future = asyncGets(key, tc);
return getFromFuture(future);
}
/**
* Gets (with CAS support) with a single key using the default transcoder.
*
* @param key the key to get
* @return the result from the cache and CAS id (null if there is none)
* @throws OperationTimeoutException if the global operation timeout is
* exceeded
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public CASValue<Object> gets(String key) {
return gets(key, transcoder);
}
/**
* Get with a single key.
*
* @param <T>
* @param key the key to get
* @param tc the transcoder to serialize and deserialize value
* @return the result from the cache (null if there is none)
* @throws OperationTimeoutException if the global operation timeout is
* exceeded
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public <T> T get(String key, Transcoder<T> tc) {
Future<T> future = asyncGet(key, tc);
return getFromFuture(future);
}
/**
* Get with a single key and decode using the default transcoder.
*
* @param key the key to get
* @return the result from the cache (null if there is none)
* @throws OperationTimeoutException if the global operation timeout is
* exceeded
* @throws IllegalStateException in the rare circumstance where queue
* is too full to accept any more requests
*/
public Object get(String key) {
return get(key, transcoder);
}