-
Notifications
You must be signed in to change notification settings - Fork 946
/
RedisClient.java
841 lines (695 loc) · 34.3 KB
/
RedisClient.java
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
/*
* Copyright 2011-Present, Redis Ltd. and Contributors
* All rights reserved.
*
* Licensed under the MIT License.
*
* This file contains contributions from third-party contributors
* 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
*
* https://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.
*/
package io.lettuce.core;
import static io.lettuce.core.internal.LettuceStrings.*;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.time.Duration;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.function.Supplier;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.codec.StringCodec;
import io.lettuce.core.internal.ExceptionFactory;
import io.lettuce.core.internal.Futures;
import io.lettuce.core.internal.LettuceAssert;
import io.lettuce.core.masterreplica.MasterReplica;
import io.lettuce.core.protocol.CommandExpiryWriter;
import io.lettuce.core.protocol.CommandHandler;
import io.lettuce.core.protocol.DefaultEndpoint;
import io.lettuce.core.protocol.Endpoint;
import io.lettuce.core.protocol.PushHandler;
import io.lettuce.core.pubsub.PubSubCommandHandler;
import io.lettuce.core.pubsub.PubSubEndpoint;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnection;
import io.lettuce.core.pubsub.StatefulRedisPubSubConnectionImpl;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.sentinel.StatefulRedisSentinelConnectionImpl;
import io.lettuce.core.sentinel.api.StatefulRedisSentinelConnection;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.InternalLoggerFactory;
import reactor.core.publisher.Mono;
/**
* A scalable and thread-safe <a href="https://redis.io/">Redis</a> client supporting synchronous, asynchronous and reactive
* execution models. Multiple threads may share one connection if they avoid blocking and transactional operations such as BLPOP
* and MULTI/EXEC.
* <p>
* {@link RedisClient} can be used with:
* <ul>
* <li>Redis Standalone</li>
* <li>Redis Pub/Sub</li>
* <li>Redis Sentinel, Sentinel connections</li>
* <li>Redis Sentinel, Upstream connections</li>
* </ul>
*
* Redis Cluster is used through {@link io.lettuce.core.cluster.RedisClusterClient}. Upstream/Replica connections through
* {@link MasterReplica} provide connections to Redis Upstream/Replica ("Master/Slave") setups which run either in a static
* Upstream/Replica setup or are managed by Redis Sentinel.
* <p>
* {@link RedisClient} is an expensive resource. It holds a set of netty's {@link io.netty.channel.EventLoopGroup}'s that use
* multiple threads. Reuse this instance as much as possible or share a {@link ClientResources} instance amongst multiple client
* instances.
*
* @author Will Glozer
* @author Mark Paluch
* @see RedisURI
* @see StatefulRedisConnection
* @see RedisFuture
* @see reactor.core.publisher.Mono
* @see reactor.core.publisher.Flux
* @see RedisCodec
* @see ClientOptions
* @see ClientResources
* @see MasterReplica
* @see io.lettuce.core.cluster.RedisClusterClient
*/
public class RedisClient extends AbstractRedisClient {
private static final InternalLogger logger = InternalLoggerFactory.getInstance(RedisClient.class);
private static final RedisURI EMPTY_URI = new RedisURI();
private final RedisURI redisURI;
protected RedisClient(ClientResources clientResources, RedisURI redisURI) {
super(clientResources);
assertNotNull(redisURI);
this.redisURI = redisURI;
setDefaultTimeout(redisURI.getTimeout());
}
/**
* Creates a uri-less RedisClient. You can connect to different Redis servers but you must supply a {@link RedisURI} on
* connecting. Methods without having a {@link RedisURI} will fail with a {@link java.lang.IllegalStateException}.
* Non-private constructor to make {@link RedisClient} proxyable.
*/
protected RedisClient() {
this(null, EMPTY_URI);
}
/**
* Creates a uri-less RedisClient with default {@link ClientResources}. You can connect to different Redis servers but you
* must supply a {@link RedisURI} on connecting. Methods without having a {@link RedisURI} will fail with a
* {@link java.lang.IllegalStateException}.
*
* @return a new instance of {@link RedisClient}
*/
public static RedisClient create() {
return new RedisClient(null, EMPTY_URI);
}
/**
* Create a new client that connects to the supplied {@link RedisURI uri} with default {@link ClientResources}. You can
* connect to different Redis servers but you must supply a {@link RedisURI} on connecting.
*
* @param redisURI the Redis URI, must not be {@code null}
* @return a new instance of {@link RedisClient}
*/
public static RedisClient create(RedisURI redisURI) {
assertNotNull(redisURI);
return new RedisClient(null, redisURI);
}
/**
* Create a new client that connects to the supplied uri with default {@link ClientResources}. You can connect to different
* Redis servers but you must supply a {@link RedisURI} on connecting.
*
* @param uri the Redis URI, must not be {@code null}
* @return a new instance of {@link RedisClient}
*/
public static RedisClient create(String uri) {
LettuceAssert.notEmpty(uri, "URI must not be empty");
return new RedisClient(null, RedisURI.create(uri));
}
/**
* Creates a uri-less RedisClient with shared {@link ClientResources}. You need to shut down the {@link ClientResources}
* upon shutting down your application. You can connect to different Redis servers but you must supply a {@link RedisURI} on
* connecting. Methods without having a {@link RedisURI} will fail with a {@link java.lang.IllegalStateException}.
*
* @param clientResources the client resources, must not be {@code null}
* @return a new instance of {@link RedisClient}
*/
public static RedisClient create(ClientResources clientResources) {
assertNotNull(clientResources);
return new RedisClient(clientResources, EMPTY_URI);
}
/**
* Create a new client that connects to the supplied uri with shared {@link ClientResources}.You need to shut down the
* {@link ClientResources} upon shutting down your application. You can connect to different Redis servers but you must
* supply a {@link RedisURI} on connecting.
*
* @param clientResources the client resources, must not be {@code null}
* @param uri the Redis URI, must not be {@code null}
*
* @return a new instance of {@link RedisClient}
*/
public static RedisClient create(ClientResources clientResources, String uri) {
assertNotNull(clientResources);
LettuceAssert.notEmpty(uri, "URI must not be empty");
return create(clientResources, RedisURI.create(uri));
}
/**
* Create a new client that connects to the supplied {@link RedisURI uri} with shared {@link ClientResources}. You need to
* shut down the {@link ClientResources} upon shutting down your application.You can connect to different Redis servers but
* you must supply a {@link RedisURI} on connecting.
*
* @param clientResources the client resources, must not be {@code null}
* @param redisURI the Redis URI, must not be {@code null}
* @return a new instance of {@link RedisClient}
*/
public static RedisClient create(ClientResources clientResources, RedisURI redisURI) {
assertNotNull(clientResources);
assertNotNull(redisURI);
return new RedisClient(clientResources, redisURI);
}
/**
* Open a new connection to a Redis server that treats keys and values as UTF-8 strings.
*
* @return A new stateful Redis connection
*/
public StatefulRedisConnection<String, String> connect() {
return connect(newStringStringCodec());
}
/**
* Open a new connection to a Redis server. Use the supplied {@link RedisCodec codec} to encode/decode keys and values.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new stateful Redis connection
*/
public <K, V> StatefulRedisConnection<K, V> connect(RedisCodec<K, V> codec) {
checkForRedisURI();
return getConnection(connectStandaloneAsync(codec, this.redisURI, getDefaultTimeout()));
}
/**
* Open a new connection to a Redis server using the supplied {@link RedisURI} that treats keys and values as UTF-8 strings.
*
* @param redisURI the Redis server to connect to, must not be {@code null}
* @return A new connection
*/
public StatefulRedisConnection<String, String> connect(RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectStandaloneAsync(newStringStringCodec(), redisURI, redisURI.getTimeout()));
}
/**
* Open a new connection to a Redis server using the supplied {@link RedisURI} and the supplied {@link RedisCodec codec} to
* encode/decode keys.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param redisURI the Redis server to connect to, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new connection
*/
public <K, V> StatefulRedisConnection<K, V> connect(RedisCodec<K, V> codec, RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectStandaloneAsync(codec, redisURI, redisURI.getTimeout()));
}
/**
* Open asynchronously a new connection to a Redis server using the supplied {@link RedisURI} and the supplied
* {@link RedisCodec codec} to encode/decode keys.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param redisURI the Redis server to connect to, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return {@link ConnectionFuture} to indicate success or failure to connect.
* @since 5.0
*/
public <K, V> ConnectionFuture<StatefulRedisConnection<K, V>> connectAsync(RedisCodec<K, V> codec, RedisURI redisURI) {
assertNotNull(redisURI);
return transformAsyncConnectionException(connectStandaloneAsync(codec, redisURI, redisURI.getTimeout()));
}
private <K, V> ConnectionFuture<StatefulRedisConnection<K, V>> connectStandaloneAsync(RedisCodec<K, V> codec,
RedisURI redisURI, Duration timeout) {
assertNotNull(codec);
checkValidRedisURI(redisURI);
logger.debug("Trying to get a Redis connection for: {}", redisURI);
DefaultEndpoint endpoint = new DefaultEndpoint(getOptions(), getResources());
RedisChannelWriter writer = endpoint;
if (CommandExpiryWriter.isSupported(getOptions())) {
writer = new CommandExpiryWriter(writer, getOptions(), getResources());
}
if (CommandListenerWriter.isSupported(getCommandListeners())) {
writer = new CommandListenerWriter(writer, getCommandListeners());
}
StatefulRedisConnectionImpl<K, V> connection = newStatefulRedisConnection(writer, endpoint, codec, timeout);
ConnectionFuture<StatefulRedisConnection<K, V>> future = connectStatefulAsync(connection, endpoint, redisURI,
() -> new CommandHandler(getOptions(), getResources(), endpoint));
future.whenComplete((channelHandler, throwable) -> {
if (throwable != null) {
connection.closeAsync();
}
});
return future;
}
@SuppressWarnings("unchecked")
private <K, V, S> ConnectionFuture<S> connectStatefulAsync(StatefulRedisConnectionImpl<K, V> connection, Endpoint endpoint,
RedisURI redisURI, Supplier<CommandHandler> commandHandlerSupplier) {
ConnectionBuilder connectionBuilder;
if (redisURI.isSsl()) {
SslConnectionBuilder sslConnectionBuilder = SslConnectionBuilder.sslConnectionBuilder();
sslConnectionBuilder.ssl(redisURI);
connectionBuilder = sslConnectionBuilder;
} else {
connectionBuilder = ConnectionBuilder.connectionBuilder();
}
ConnectionState state = connection.getConnectionState();
state.apply(redisURI);
state.setDb(redisURI.getDatabase());
connectionBuilder.connection(connection);
connectionBuilder.clientOptions(getOptions());
connectionBuilder.clientResources(getResources());
connectionBuilder.commandHandler(commandHandlerSupplier).endpoint(endpoint);
connectionBuilder(getSocketAddressSupplier(redisURI), connectionBuilder, connection.getConnectionEvents(), redisURI);
connectionBuilder.connectionInitializer(createHandshake(state));
ConnectionFuture<RedisChannelHandler<K, V>> future = initializeChannelAsync(connectionBuilder);
return future.thenApply(channelHandler -> (S) connection);
}
/**
* Open a new pub/sub connection to a Redis server that treats keys and values as UTF-8 strings.
*
* @return A new stateful pub/sub connection
*/
public StatefulRedisPubSubConnection<String, String> connectPubSub() {
return getConnection(connectPubSubAsync(newStringStringCodec(), this.redisURI, getDefaultTimeout()));
}
/**
* Open a new pub/sub connection to a Redis server using the supplied {@link RedisURI} that treats keys and values as UTF-8
* strings.
*
* @param redisURI the Redis server to connect to, must not be {@code null}
* @return A new stateful pub/sub connection
*/
public StatefulRedisPubSubConnection<String, String> connectPubSub(RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectPubSubAsync(newStringStringCodec(), redisURI, redisURI.getTimeout()));
}
/**
* Open a new pub/sub connection to the Redis server using the supplied {@link RedisURI} and use the supplied
* {@link RedisCodec codec} to encode/decode keys and values.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new stateful pub/sub connection
*/
public <K, V> StatefulRedisPubSubConnection<K, V> connectPubSub(RedisCodec<K, V> codec) {
checkForRedisURI();
return getConnection(connectPubSubAsync(codec, this.redisURI, getDefaultTimeout()));
}
/**
* Open a new pub/sub connection to the Redis server using the supplied {@link RedisURI} and use the supplied
* {@link RedisCodec codec} to encode/decode keys and values.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param redisURI the Redis server to connect to, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new connection
*/
public <K, V> StatefulRedisPubSubConnection<K, V> connectPubSub(RedisCodec<K, V> codec, RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectPubSubAsync(codec, redisURI, redisURI.getTimeout()));
}
/**
* Open asynchronously a new pub/sub connection to the Redis server using the supplied {@link RedisURI} and use the supplied
* {@link RedisCodec codec} to encode/decode keys and values.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param redisURI the redis server to connect to, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return {@link ConnectionFuture} to indicate success or failure to connect.
* @since 5.0
*/
public <K, V> ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectPubSubAsync(RedisCodec<K, V> codec,
RedisURI redisURI) {
assertNotNull(redisURI);
return transformAsyncConnectionException(connectPubSubAsync(codec, redisURI, redisURI.getTimeout()));
}
private <K, V> ConnectionFuture<StatefulRedisPubSubConnection<K, V>> connectPubSubAsync(RedisCodec<K, V> codec,
RedisURI redisURI, Duration timeout) {
assertNotNull(codec);
checkValidRedisURI(redisURI);
PubSubEndpoint<K, V> endpoint = new PubSubEndpoint<>(getOptions(), getResources());
RedisChannelWriter writer = endpoint;
if (CommandExpiryWriter.isSupported(getOptions())) {
writer = new CommandExpiryWriter(writer, getOptions(), getResources());
}
if (CommandListenerWriter.isSupported(getCommandListeners())) {
writer = new CommandListenerWriter(writer, getCommandListeners());
}
StatefulRedisPubSubConnectionImpl<K, V> connection = newStatefulRedisPubSubConnection(endpoint, writer, codec, timeout);
ConnectionFuture<StatefulRedisPubSubConnection<K, V>> future = connectStatefulAsync(connection, endpoint, redisURI,
() -> new PubSubCommandHandler<>(getOptions(), getResources(), codec, endpoint));
return future.whenComplete((conn, throwable) -> {
if (throwable != null) {
conn.close();
}
});
}
/**
* Open a connection to a Redis Sentinel that treats keys and values as UTF-8 strings.
*
* @return A new stateful Redis Sentinel connection
*/
public StatefulRedisSentinelConnection<String, String> connectSentinel() {
return connectSentinel(newStringStringCodec());
}
/**
* Open a connection to a Redis Sentinel that treats keys and use the supplied {@link RedisCodec codec} to encode/decode
* keys and values. The client {@link RedisURI} must contain one or more sentinels.
*
* @param codec Use this codec to encode/decode keys and values, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new stateful Redis Sentinel connection
*/
public <K, V> StatefulRedisSentinelConnection<K, V> connectSentinel(RedisCodec<K, V> codec) {
checkForRedisURI();
return getConnection(connectSentinelAsync(codec, this.redisURI, getDefaultTimeout()));
}
/**
* Open a connection to a Redis Sentinel using the supplied {@link RedisURI} that treats keys and values as UTF-8 strings.
* The client {@link RedisURI} must contain one or more sentinels.
*
* @param redisURI the Redis server to connect to, must not be {@code null}
* @return A new connection
*/
public StatefulRedisSentinelConnection<String, String> connectSentinel(RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectSentinelAsync(newStringStringCodec(), redisURI, redisURI.getTimeout()));
}
/**
* Open a connection to a Redis Sentinel using the supplied {@link RedisURI} and use the supplied {@link RedisCodec codec}
* to encode/decode keys and values. The client {@link RedisURI} must contain one or more sentinels.
*
* @param codec the Redis server to connect to, must not be {@code null}
* @param redisURI the Redis server to connect to, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new connection
*/
public <K, V> StatefulRedisSentinelConnection<K, V> connectSentinel(RedisCodec<K, V> codec, RedisURI redisURI) {
assertNotNull(redisURI);
return getConnection(connectSentinelAsync(codec, redisURI, redisURI.getTimeout()));
}
/**
* Open asynchronously a connection to a Redis Sentinel using the supplied {@link RedisURI} and use the supplied
* {@link RedisCodec codec} to encode/decode keys and values. The client {@link RedisURI} must contain one or more
* sentinels.
*
* @param codec the Redis server to connect to, must not be {@code null}
* @param redisURI the Redis server to connect to, must not be {@code null}
* @param <K> Key type
* @param <V> Value type
* @return A new connection
* @since 5.1
*/
public <K, V> CompletableFuture<StatefulRedisSentinelConnection<K, V>> connectSentinelAsync(RedisCodec<K, V> codec,
RedisURI redisURI) {
assertNotNull(redisURI);
return transformAsyncConnectionException(connectSentinelAsync(codec, redisURI, redisURI.getTimeout()), redisURI);
}
private <K, V> CompletableFuture<StatefulRedisSentinelConnection<K, V>> connectSentinelAsync(RedisCodec<K, V> codec,
RedisURI redisURI, Duration timeout) {
assertNotNull(codec);
checkValidRedisURI(redisURI);
logger.debug("Trying to get a Redis Sentinel connection for one of: " + redisURI.getSentinels());
if (redisURI.getSentinels().isEmpty() && (isNotEmpty(redisURI.getHost()) || !isEmpty(redisURI.getSocket()))) {
return doConnectSentinelAsync(codec, redisURI, timeout, new ConnectionMetadata(redisURI)).toCompletableFuture();
}
List<RedisURI> sentinels = redisURI.getSentinels();
Queue<Throwable> exceptionCollector = new LinkedBlockingQueue<>();
validateUrisAreOfSameConnectionType(sentinels);
Mono<StatefulRedisSentinelConnection<K, V>> connectionLoop = null;
for (RedisURI uri : sentinels) {
Mono<StatefulRedisSentinelConnection<K, V>> connectionMono = Mono
.fromCompletionStage(() -> doConnectSentinelAsync(codec, uri, timeout, new ConnectionMetadata(redisURI)))
.onErrorMap(CompletionException.class, Throwable::getCause)
.onErrorMap(e -> new RedisConnectionException("Cannot connect Redis Sentinel at " + uri, e))
.doOnError(exceptionCollector::add);
if (connectionLoop == null) {
connectionLoop = connectionMono;
} else {
connectionLoop = connectionLoop.onErrorResume(t -> connectionMono);
}
}
if (connectionLoop == null) {
return Mono
.<StatefulRedisSentinelConnection<K, V>> error(
new RedisConnectionException("Cannot connect to a Redis Sentinel: " + redisURI.getSentinels()))
.toFuture();
}
return connectionLoop.onErrorMap(e -> {
RedisConnectionException ex = new RedisConnectionException(
"Cannot connect to a Redis Sentinel: " + redisURI.getSentinels(), e);
for (Throwable throwable : exceptionCollector) {
if (e != throwable) {
ex.addSuppressed(throwable);
}
}
return ex;
}).toFuture();
}
private <K, V> ConnectionFuture<StatefulRedisSentinelConnection<K, V>> doConnectSentinelAsync(RedisCodec<K, V> codec,
RedisURI redisURI, Duration timeout, ConnectionMetadata metadata) {
ConnectionBuilder connectionBuilder;
if (redisURI.isSsl()) {
SslConnectionBuilder sslConnectionBuilder = SslConnectionBuilder.sslConnectionBuilder();
sslConnectionBuilder.ssl(redisURI);
connectionBuilder = sslConnectionBuilder;
} else {
connectionBuilder = ConnectionBuilder.connectionBuilder();
}
connectionBuilder.clientOptions(ClientOptions.copyOf(getOptions()));
connectionBuilder.clientResources(getResources());
DefaultEndpoint endpoint = new DefaultEndpoint(getOptions(), getResources());
RedisChannelWriter writer = endpoint;
if (CommandExpiryWriter.isSupported(getOptions())) {
writer = new CommandExpiryWriter(writer, getOptions(), getResources());
}
if (CommandListenerWriter.isSupported(getCommandListeners())) {
writer = new CommandListenerWriter(writer, getCommandListeners());
}
StatefulRedisSentinelConnectionImpl<K, V> connection = newStatefulRedisSentinelConnection(writer, codec, timeout);
ConnectionState state = connection.getConnectionState();
state.apply(redisURI);
state.apply(metadata);
connectionBuilder.connectionInitializer(createHandshake(state));
logger.debug("Connecting to Redis Sentinel, address: " + redisURI);
connectionBuilder.endpoint(endpoint).commandHandler(() -> new CommandHandler(getOptions(), getResources(), endpoint))
.connection(connection);
connectionBuilder(getSocketAddressSupplier(redisURI), connectionBuilder, connection.getConnectionEvents(), redisURI);
ConnectionFuture<?> sync = initializeChannelAsync(connectionBuilder);
return sync.thenApply(ignore -> (StatefulRedisSentinelConnection<K, V>) connection).whenComplete((ignore, e) -> {
if (e != null) {
logger.warn("Cannot connect Redis Sentinel at " + redisURI + ": " + e);
connection.closeAsync();
}
});
}
/**
* Set the {@link ClientOptions} for the client.
*
* @param clientOptions the new client options
* @throws IllegalArgumentException if {@literal clientOptions} is null
*/
@Override
public void setOptions(ClientOptions clientOptions) {
super.setOptions(clientOptions);
}
// -------------------------------------------------------------------------
// Implementation hooks and helper methods
// -------------------------------------------------------------------------
/**
* Create a new instance of {@link StatefulRedisPubSubConnectionImpl} or a subclass.
* <p>
* Subclasses of {@link RedisClient} may override that method.
*
* @param endpoint the endpoint
* @param channelWriter the channel writer
* @param codec codec
* @param timeout default timeout
* @param <K> Key-Type
* @param <V> Value Type
* @return new instance of StatefulRedisPubSubConnectionImpl
*/
protected <K, V> StatefulRedisPubSubConnectionImpl<K, V> newStatefulRedisPubSubConnection(PubSubEndpoint<K, V> endpoint,
RedisChannelWriter channelWriter, RedisCodec<K, V> codec, Duration timeout) {
return new StatefulRedisPubSubConnectionImpl<>(endpoint, channelWriter, codec, timeout);
}
/**
* Create a new instance of {@link StatefulRedisSentinelConnectionImpl} or a subclass.
* <p>
* Subclasses of {@link RedisClient} may override that method.
*
* @param channelWriter the channel writer
* @param codec codec
* @param timeout default timeout
* @param <K> Key-Type
* @param <V> Value Type
* @return new instance of StatefulRedisSentinelConnectionImpl
*/
protected <K, V> StatefulRedisSentinelConnectionImpl<K, V> newStatefulRedisSentinelConnection(
RedisChannelWriter channelWriter, RedisCodec<K, V> codec, Duration timeout) {
return new StatefulRedisSentinelConnectionImpl<>(channelWriter, codec, timeout);
}
/**
* Create a new instance of {@link StatefulRedisConnectionImpl} or a subclass.
* <p>
* Subclasses of {@link RedisClient} may override that method.
*
* @param channelWriter the channel writer
* @param pushHandler the handler for push notifications
* @param codec codec
* @param timeout default timeout
* @param <K> Key-Type
* @param <V> Value Type
* @return new instance of StatefulRedisConnectionImpl
*/
protected <K, V> StatefulRedisConnectionImpl<K, V> newStatefulRedisConnection(RedisChannelWriter channelWriter,
PushHandler pushHandler, RedisCodec<K, V> codec, Duration timeout) {
return new StatefulRedisConnectionImpl<>(channelWriter, pushHandler, codec, timeout);
}
/**
* Get a {@link Mono} that resolves {@link RedisURI} to a {@link SocketAddress}. Resolution is performed either using Redis
* Sentinel (if the {@link RedisURI} is configured with Sentinels) or via DNS resolution.
* <p>
* Subclasses of {@link RedisClient} may override that method.
*
* @param redisURI must not be {@code null}.
* @return the resolved {@link SocketAddress}.
* @see ClientResources#dnsResolver()
* @see RedisURI#getSentinels()
* @see RedisURI#getSentinelMasterId()
*/
protected Mono<SocketAddress> getSocketAddress(RedisURI redisURI) {
return Mono.defer(() -> {
if (redisURI.getSentinelMasterId() != null && !redisURI.getSentinels().isEmpty()) {
logger.debug("Connecting to Redis using Sentinels {}, MasterId {}", redisURI.getSentinels(),
redisURI.getSentinelMasterId());
return lookupRedis(redisURI).switchIfEmpty(Mono.error(new RedisConnectionException(
"Cannot provide redisAddress using sentinel for masterId " + redisURI.getSentinelMasterId())));
} else {
return Mono.fromCallable(() -> getResources().socketAddressResolver().resolve((redisURI)));
}
});
}
/**
* Returns a {@link String} {@link RedisCodec codec}.
*
* @return a {@link String} {@link RedisCodec codec}.
* @see StringCodec#UTF8
*/
protected RedisCodec<String, String> newStringStringCodec() {
return StringCodec.UTF8;
}
private static void validateUrisAreOfSameConnectionType(List<RedisURI> redisUris) {
boolean unixDomainSocket = false;
boolean inetSocket = false;
for (RedisURI sentinel : redisUris) {
if (sentinel.getSocket() != null) {
unixDomainSocket = true;
}
if (sentinel.getHost() != null) {
inetSocket = true;
}
}
if (unixDomainSocket && inetSocket) {
throw new RedisConnectionException("You cannot mix unix domain socket and IP socket URI's");
}
}
private Mono<SocketAddress> getSocketAddressSupplier(RedisURI redisURI) {
return getSocketAddress(redisURI).doOnNext(addr -> logger.debug("Resolved SocketAddress {} using {}", addr, redisURI));
}
private Mono<SocketAddress> lookupRedis(RedisURI sentinelUri) {
Duration timeout = sentinelUri.getTimeout();
return Mono.usingWhen(
Mono.fromCompletionStage(() -> connectSentinelAsync(newStringStringCodec(), sentinelUri, timeout)), c -> {
String sentinelMasterId = sentinelUri.getSentinelMasterId();
return c.reactive().getMasterAddrByName(sentinelMasterId).map(it -> {
if (it instanceof InetSocketAddress) {
InetSocketAddress isa = (InetSocketAddress) it;
SocketAddress resolved = getResources().socketAddressResolver()
.resolve(RedisURI.create(isa.getHostString(), isa.getPort()));
logger.debug("Resolved Master {} SocketAddress {}:{} to {}", sentinelMasterId, isa.getHostString(),
isa.getPort(), resolved);
return resolved;
}
return it;
}).timeout(timeout) //
.onErrorMap(e -> {
RedisCommandTimeoutException ex = ExceptionFactory
.createTimeoutException("Cannot obtain master using SENTINEL MASTER", timeout);
ex.addSuppressed(e);
return ex;
});
}, c -> Mono.fromCompletionStage(c::closeAsync), //
(c, ex) -> Mono.fromCompletionStage(c::closeAsync), //
c -> Mono.fromCompletionStage(c::closeAsync));
}
private static <T> ConnectionFuture<T> transformAsyncConnectionException(ConnectionFuture<T> future) {
return future.thenCompose((v, e) -> {
if (e != null) {
return Futures.failed(RedisConnectionException.create(future.getRemoteAddress(), e));
}
return CompletableFuture.completedFuture(v);
});
}
private static <T> CompletableFuture<T> transformAsyncConnectionException(CompletionStage<T> future, RedisURI target) {
return ConnectionFuture.from(null, future.toCompletableFuture()).thenCompose((v, e) -> {
if (e != null) {
return Futures.failed(RedisConnectionException.create(target.toString(), e));
}
return CompletableFuture.completedFuture(v);
}).toCompletableFuture();
}
private static void checkValidRedisURI(RedisURI redisURI) {
LettuceAssert.notNull(redisURI, "A valid RedisURI is required");
if (redisURI.getSentinels().isEmpty()) {
if (isEmpty(redisURI.getHost()) && isEmpty(redisURI.getSocket())) {
throw new IllegalArgumentException("RedisURI for Redis Standalone does not contain a host or a socket");
}
} else {
if (isEmpty(redisURI.getSentinelMasterId())) {
throw new IllegalArgumentException("RedisURI for Redis Sentinel requires a masterId");
}
for (RedisURI sentinel : redisURI.getSentinels()) {
if (isEmpty(sentinel.getHost()) && isEmpty(sentinel.getSocket())) {
throw new IllegalArgumentException("RedisURI for Redis Sentinel does not contain a host or a socket");
}
}
}
}
private static <K, V> void assertNotNull(RedisCodec<K, V> codec) {
LettuceAssert.notNull(codec, "RedisCodec must not be null");
}
private static void assertNotNull(RedisURI redisURI) {
LettuceAssert.notNull(redisURI, "RedisURI must not be null");
}
private static void assertNotNull(ClientResources clientResources) {
LettuceAssert.notNull(clientResources, "ClientResources must not be null");
}
private void checkForRedisURI() {
LettuceAssert.assertState(this.redisURI != EMPTY_URI,
"RedisURI is not available. Use RedisClient(Host), RedisClient(Host, Port) or RedisClient(RedisURI) to construct your client.");
checkValidRedisURI(this.redisURI);
}
}