/
LettuceConnectionFactory.java
1850 lines (1494 loc) · 59.3 KB
/
LettuceConnectionFactory.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
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
/*
* Copyright 2011-2024 the original author or authors.
*
* 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 org.springframework.data.redis.connection.lettuce;
import static org.springframework.data.redis.connection.lettuce.LettuceConnection.*;
import io.lettuce.core.AbstractRedisClient;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.ReadFrom;
import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisConnectionException;
import io.lettuce.core.RedisCredentialsProvider;
import io.lettuce.core.RedisURI;
import io.lettuce.core.api.StatefulConnection;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.RedisClusterClient;
import io.lettuce.core.cluster.api.StatefulRedisClusterConnection;
import io.lettuce.core.codec.RedisCodec;
import io.lettuce.core.resource.ClientResources;
import java.nio.ByteBuffer;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.SmartLifecycle;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.redis.ExceptionTranslationStrategy;
import org.springframework.data.redis.PassThroughExceptionTranslationStrategy;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.RedisConfiguration.ClusterConfiguration;
import org.springframework.data.redis.connection.RedisConfiguration.WithDatabaseIndex;
import org.springframework.data.redis.connection.RedisConfiguration.WithPassword;
import org.springframework.data.redis.util.RedisAssertions;
import org.springframework.data.util.Optionals;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* {@link RedisConnectionFactory Connection factory} creating <a href="https://lettuce.io/">Lettuce</a>-based
* connections.
* <p>
* This factory creates a new {@link LettuceConnection} on each call to {@link #getConnection()}. While multiple
* {@link LettuceConnection}s share a single thread-safe native connection by default, {@link LettuceConnection} and its
* {@link LettuceClusterConnection clustered variant} are not Thread-safe and instances should not be shared across
* threads.
* <p>
* The shared native connection is never closed by {@link LettuceConnection}, therefore it is not validated by default
* on {@link #getConnection()}. Use {@link #setValidateConnection(boolean)} to change this behavior if necessary. If
* {@code shareNativeConnection} is {@literal true}, a shared connection will be used for regular operations and a
* {@link LettuceConnectionProvider} will be used to select a connection for blocking and tx operations only, which
* should not share a connection. If native connection sharing is disabled, new (or pooled) connections will be used for
* all operations.
* <p>
* {@link LettuceConnectionFactory} should be configured using an environmental configuration and the
* {@link LettuceConnectionFactory client configuration}. Lettuce supports the following environmental configurations:
* <ul>
* <li>{@link RedisStandaloneConfiguration}</li>
* <li>{@link RedisStaticMasterReplicaConfiguration}</li>
* <li>{@link RedisSocketConfiguration}</li>
* <li>{@link RedisSentinelConfiguration}</li>
* <li>{@link RedisClusterConfiguration}</li>
* </ul>
* <p>
* This connection factory implements {@link InitializingBean} and {@link SmartLifecycle} for flexible lifecycle
* control. It must be {@link #afterPropertiesSet() initialized} and {@link #start() started} before you can obtain a
* connection. {@link #afterPropertiesSet() Initialization} {@link SmartLifecycle#start() starts} this bean
* {@link #isEarlyStartup() early} by default. You can {@link SmartLifecycle#stop()} and {@link SmartLifecycle#start()
* restart} this connection factory if needed. Disabling {@link #isEarlyStartup() early startup} leaves lifecycle
* management to the container refresh if {@link #isAutoStartup() auto-startup} is enabled.
*
* @author Costin Leau
* @author Jennifer Hickey
* @author Thomas Darimont
* @author Christoph Strobl
* @author Mark Paluch
* @author Balázs Németh
* @author Ruben Cervilla
* @author Luis De Bello
* @author Andrea Como
* @author Chris Bono
* @author John Blum
*/
public class LettuceConnectionFactory implements RedisConnectionFactory, ReactiveRedisConnectionFactory,
InitializingBean, DisposableBean, SmartLifecycle {
private static final ExceptionTranslationStrategy EXCEPTION_TRANSLATION = new PassThroughExceptionTranslationStrategy(
LettuceExceptionConverter.INSTANCE);
private int phase = 0; // in between min and max values
private boolean autoStartup = true;
private boolean earlyStartup = true;
private boolean convertPipelineAndTxResults = true;
private boolean eagerInitialization = false;
private boolean shareNativeConnection = true;
private boolean validateConnection = false;
private @Nullable AbstractRedisClient client;
private final AtomicReference<State> state = new AtomicReference<>(State.CREATED);
private @Nullable ClusterCommandExecutor clusterCommandExecutor;
private @Nullable AsyncTaskExecutor executor;
private final LettuceClientConfiguration clientConfiguration;
private @Nullable LettuceConnectionProvider connectionProvider;
private @Nullable LettuceConnectionProvider reactiveConnectionProvider;
private final Log log = LogFactory.getLog(getClass());
private final Lock lock = new ReentrantLock();
private PipeliningFlushPolicy pipeliningFlushPolicy = PipeliningFlushPolicy.flushEachCommand();
private @Nullable RedisConfiguration configuration;
private RedisStandaloneConfiguration standaloneConfig = new RedisStandaloneConfiguration("localhost", 6379);
private @Nullable SharedConnection<byte[]> connection;
private @Nullable SharedConnection<ByteBuffer> reactiveConnection;
/**
* Lifecycle state of this factory.
*/
enum State {
CREATED, STARTING, STARTED, STOPPING, STOPPED, DESTROYED;
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance with default settings.
*/
public LettuceConnectionFactory() {
this(new MutableLettuceClientConfiguration());
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance with default settings.
*/
public LettuceConnectionFactory(String host, int port) {
this(new RedisStandaloneConfiguration(host, port), new MutableLettuceClientConfiguration());
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance given {@link LettuceClientConfiguration}.
*
* @param clientConfiguration must not be {@literal null}
* @since 2.0
*/
private LettuceConnectionFactory(LettuceClientConfiguration clientConfiguration) {
Assert.notNull(clientConfiguration, "LettuceClientConfiguration must not be null");
this.clientConfiguration = clientConfiguration;
this.configuration = this.standaloneConfig;
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given {@link RedisSocketConfiguration}.
*
* @param redisConfiguration must not be {@literal null}.
* @since 2.1
*/
public LettuceConnectionFactory(RedisConfiguration redisConfiguration) {
this(redisConfiguration, new MutableLettuceClientConfiguration());
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given
* {@link RedisStaticMasterReplicaConfiguration} and {@link LettuceClientConfiguration}.
*
* @param redisConfiguration must not be {@literal null}.
* @param clientConfiguration must not be {@literal null}.
* @since 2.1
*/
public LettuceConnectionFactory(RedisConfiguration redisConfiguration,
LettuceClientConfiguration clientConfiguration) {
this(clientConfiguration);
Assert.notNull(redisConfiguration, "RedisConfiguration must not be null");
this.configuration = redisConfiguration;
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given {@link RedisClusterConfiguration}
* applied to create a {@link RedisClusterClient}.
*
* @param clusterConfiguration must not be {@literal null}.
* @since 1.7
*/
public LettuceConnectionFactory(RedisClusterConfiguration clusterConfiguration) {
this(clusterConfiguration, new MutableLettuceClientConfiguration());
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given {@link RedisClusterConfiguration} and
* {@link LettuceClientConfiguration}.
*
* @param clusterConfiguration must not be {@literal null}.
* @param clientConfiguration must not be {@literal null}.
* @since 2.0
*/
public LettuceConnectionFactory(RedisClusterConfiguration clusterConfiguration,
LettuceClientConfiguration clientConfiguration) {
this(clientConfiguration);
Assert.notNull(clusterConfiguration, "RedisClusterConfiguration must not be null");
this.configuration = clusterConfiguration;
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given {@link RedisSentinelConfiguration}.
*
* @param sentinelConfiguration must not be {@literal null}.
* @since 1.6
*/
public LettuceConnectionFactory(RedisSentinelConfiguration sentinelConfiguration) {
this(sentinelConfiguration, new MutableLettuceClientConfiguration());
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given {@link RedisSentinelConfiguration} and
* {@link LettuceClientConfiguration}.
*
* @param sentinelConfiguration must not be {@literal null}.
* @param clientConfiguration must not be {@literal null}.
* @since 2.0
*/
public LettuceConnectionFactory(RedisSentinelConfiguration sentinelConfiguration,
LettuceClientConfiguration clientConfiguration) {
this(clientConfiguration);
Assert.notNull(sentinelConfiguration, "RedisSentinelConfiguration must not be null");
this.configuration = sentinelConfiguration;
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance with default settings.
*/
public LettuceConnectionFactory(RedisStandaloneConfiguration configuration) {
this(configuration, new MutableLettuceClientConfiguration());
}
/**
* Constructs a new {@link LettuceConnectionFactory} instance using the given {@link RedisStandaloneConfiguration} and
* {@link LettuceClientConfiguration}.
*
* @param standaloneConfiguration must not be {@literal null}.
* @param clientConfiguration must not be {@literal null}.
* @since 2.0
*/
public LettuceConnectionFactory(RedisStandaloneConfiguration standaloneConfiguration,
LettuceClientConfiguration clientConfiguration) {
this(clientConfiguration);
Assert.notNull(standaloneConfiguration, "RedisStandaloneConfiguration must not be null");
this.standaloneConfig = standaloneConfiguration;
this.configuration = this.standaloneConfig;
}
/**
* Creates a {@link RedisConfiguration} based on a {@link String URI} according to the following:
* <ul>
* <li>If {@code redisUri} contains sentinels, a {@link RedisSentinelConfiguration} is returned</li>
* <li>If {@code redisUri} has a configured socket a {@link RedisSocketConfiguration} is returned</li>
* <li>Otherwise a {@link RedisStandaloneConfiguration} is returned</li>
* </ul>
*
* @param redisUri the connection URI in the format of a {@link RedisURI}.
* @return an appropriate {@link RedisConfiguration} instance representing the Redis URI.
* @since 2.5.3
* @see #createRedisConfiguration(RedisURI)
* @see RedisURI
*/
public static RedisConfiguration createRedisConfiguration(String redisUri) {
Assert.hasText(redisUri, "RedisURI must not be null or empty");
return createRedisConfiguration(RedisURI.create(redisUri));
}
/**
* Creates a {@link RedisConfiguration} based on a {@link RedisURI} according to the following:
* <ul>
* <li>If {@link RedisURI} contains sentinels, a {@link RedisSentinelConfiguration} is returned</li>
* <li>If {@link RedisURI} has a configured socket a {@link RedisSocketConfiguration} is returned</li>
* <li>Otherwise a {@link RedisStandaloneConfiguration} is returned</li>
* </ul>
*
* @param redisUri the connection URI.
* @return an appropriate {@link RedisConfiguration} instance representing the Redis URI.
* @since 2.5.3
* @see RedisURI
*/
public static RedisConfiguration createRedisConfiguration(RedisURI redisUri) {
Assert.notNull(redisUri, "RedisURI must not be null");
if (!ObjectUtils.isEmpty(redisUri.getSentinels())) {
return LettuceConverters.createRedisSentinelConfiguration(redisUri);
}
if (!ObjectUtils.isEmpty(redisUri.getSocket())) {
return LettuceConverters.createRedisSocketConfiguration(redisUri);
}
return LettuceConverters.createRedisStandaloneConfiguration(redisUri);
}
ClusterCommandExecutor getRequiredClusterCommandExecutor() {
Assert.state(this.clusterCommandExecutor != null, "ClusterCommandExecutor not initialized");
return this.clusterCommandExecutor;
}
/**
* Configures the {@link AsyncTaskExecutor executor} used to execute commands asynchronously across the cluster.
*
* @param executor {@link AsyncTaskExecutor executor} used to execute commands asynchronously across the cluster.
* @since 3.2
*/
public void setExecutor(AsyncTaskExecutor executor) {
Assert.notNull(executor, "AsyncTaskExecutor must not be null");
this.executor = executor;
}
/**
* Returns the current host.
*
* @return the host.
*/
public String getHostName() {
return RedisConfiguration.getHostOrElse(configuration, standaloneConfig::getHostName);
}
/**
* Sets the hostname.
*
* @param hostName the hostname to set.
* @deprecated since 2.0, configure the hostname using {@link RedisStandaloneConfiguration}.
*/
@Deprecated
public void setHostName(String hostName) {
standaloneConfig.setHostName(hostName);
}
/**
* Returns the current port.
*
* @return the port.
*/
public int getPort() {
return RedisConfiguration.getPortOrElse(configuration, standaloneConfig::getPort);
}
/**
* Sets the port.
*
* @param port the port to set.
* @deprecated since 2.0, configure the port using {@link RedisStandaloneConfiguration}.
*/
@Deprecated
public void setPort(int port) {
standaloneConfig.setPort(port);
}
/**
* Configures the flushing policy when using pipelining. If not set, defaults to
* {@link PipeliningFlushPolicy#flushEachCommand() flush on each command}.
*
* @param pipeliningFlushPolicy the flushing policy to control when commands get written to the Redis connection.
* @see LettuceConnection#openPipeline()
* @see StatefulRedisConnection#flushCommands()
* @since 2.3
*/
public void setPipeliningFlushPolicy(PipeliningFlushPolicy pipeliningFlushPolicy) {
Assert.notNull(pipeliningFlushPolicy, "PipeliningFlushingPolicy must not be null");
this.pipeliningFlushPolicy = pipeliningFlushPolicy;
}
/**
* Returns the connection timeout (in milliseconds).
*
* @return connection timeout.
*/
public long getTimeout() {
return getClientTimeout();
}
/**
* Sets the connection timeout (in milliseconds).
*
* @param timeout the timeout.
* @deprecated since 2.0, configure the timeout using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setTimeout(long timeout) {
getMutableConfiguration().setTimeout(Duration.ofMillis(timeout));
}
/**
* Returns whether to use SSL.
*
* @return use of SSL.
*/
public boolean isUseSsl() {
return clientConfiguration.isUseSsl();
}
/**
* Sets to use SSL connection.
*
* @param useSsl {@literal true} to use SSL.
* @deprecated since 2.0, configure SSL usage using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setUseSsl(boolean useSsl) {
getMutableConfiguration().setUseSsl(useSsl);
}
/**
* Returns whether to verify certificate validity/hostname check when SSL is used.
*
* @return whether to verify peers when using SSL.
*/
public boolean isVerifyPeer() {
return clientConfiguration.isVerifyPeer();
}
/**
* Sets to use verify certificate validity/hostname check when SSL is used.
*
* @param verifyPeer {@literal false} not to verify hostname.
* @deprecated since 2.0, configure peer verification using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setVerifyPeer(boolean verifyPeer) {
getMutableConfiguration().setVerifyPeer(verifyPeer);
}
/**
* Returns whether to issue a StartTLS.
*
* @return use of StartTLS.
*/
public boolean isStartTls() {
return clientConfiguration.isStartTls();
}
/**
* Sets to issue StartTLS.
*
* @param startTls {@literal true} to issue StartTLS.
* @deprecated since 2.0, configure StartTLS using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setStartTls(boolean startTls) {
getMutableConfiguration().setStartTls(startTls);
}
/**
* Indicates if validation of the native Lettuce connection is enabled.
*
* @return connection validation enabled.
*/
public boolean getValidateConnection() {
return validateConnection;
}
/**
* Enables validation of the shared native Lettuce connection on calls to {@link #getConnection()}. A new connection
* will be created and used if validation fails.
* <p>
* Lettuce will automatically reconnect until close is called, which should never happen through
* {@link LettuceConnection} if a shared native connection is used, therefore the default is {@literal false}.
* <p>
* Setting this to {@literal true} will result in a round-trip call to the server on each new connection, so this
* setting should only be used if connection sharing is enabled and there is code that is actively closing the native
* Lettuce connection.
*
* @param validateConnection enable connection validation.
*/
public void setValidateConnection(boolean validateConnection) {
this.validateConnection = validateConnection;
}
/**
* Indicates if multiple {@link LettuceConnection}s should share a single native connection.
*
* @return native connection shared.
*/
public boolean getShareNativeConnection() {
return this.shareNativeConnection;
}
/**
* Enables multiple {@link LettuceConnection}s to share a single native connection. If set to {@literal false}, every
* operation on {@link LettuceConnection} will open and close a socket.
*
* @param shareNativeConnection enable connection sharing.
*/
public void setShareNativeConnection(boolean shareNativeConnection) {
this.shareNativeConnection = shareNativeConnection;
}
/**
* Indicates {@link #setShareNativeConnection(boolean) shared connections} should be eagerly initialized. Eager
* initialization requires a running Redis instance during {@link #start() startup} to allow early validation of
* connection factory configuration. Eager initialization also prevents blocking connect while using reactive API and
* is recommended for reactive API usage.
*
* @return {@link true} if the shared connection is initialized upon {@link #start()}.
* @since 2.2
* @see #start()
*/
public boolean getEagerInitialization() {
return this.eagerInitialization;
}
/**
* Enables eager initialization of {@link #setShareNativeConnection(boolean) shared connections}.
*
* @param eagerInitialization enable eager connection shared connection initialization upon
* {@link #afterPropertiesSet()}.
* @since 2.2
*/
public void setEagerInitialization(boolean eagerInitialization) {
this.eagerInitialization = eagerInitialization;
}
/**
* Returns the index of the database.
*
* @return the database index.
*/
public int getDatabase() {
return RedisConfiguration.getDatabaseOrElse(configuration, standaloneConfig::getDatabase);
}
/**
* Sets the index of the database used by this connection factory. Default is 0.
*
* @param index database index.
* @deprecated since 3.2, configure the database index using {@link RedisStandaloneConfiguration},
* {@link RedisSocketConfiguration}, {@link RedisSentinelConfiguration}, or
* {@link RedisStaticMasterReplicaConfiguration}.
*/
@Deprecated
public void setDatabase(int index) {
Assert.isTrue(index >= 0, "invalid DB index (a positive index required)");
if (RedisConfiguration.isDatabaseIndexAware(configuration)) {
((WithDatabaseIndex) configuration).setDatabase(index);
return;
}
standaloneConfig.setDatabase(index);
}
/**
* Returns the client name.
*
* @return the client name or {@literal null} if not set.
* @since 2.1
*/
@Nullable
public String getClientName() {
return clientConfiguration.getClientName().orElse(null);
}
/**
* Sets the client name used by this connection factory.
*
* @param clientName the client name. Can be {@literal null}.
* @since 2.1
* @deprecated configure the client name using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setClientName(@Nullable String clientName) {
this.getMutableConfiguration().setClientName(clientName);
}
/**
* Returns the native {@link AbstractRedisClient} used by this instance. The client is initialized as part of
* {@link #afterPropertiesSet() the bean initialization lifecycle} and only available when this connection factory is
* initialized.
* <p>
* Depending on the configuration, the client can be either {@link RedisClient} or {@link RedisClusterClient}.
*
* @return the native {@link AbstractRedisClient}. Can be {@literal null} if not initialized.
* @since 2.5
* @see #afterPropertiesSet()
*/
@Nullable
public AbstractRedisClient getNativeClient() {
assertStarted();
return this.client;
}
/**
* Returns the native {@link AbstractRedisClient} used by this instance. The client is initialized as part of
* {@link #afterPropertiesSet() the bean initialization lifecycle} and only available when this connection factory is
* initialized. Throws {@link IllegalStateException} if not yet initialized.
* <p>
* Depending on the configuration, the client can be either {@link RedisClient} or {@link RedisClusterClient}.
*
* @return the native {@link AbstractRedisClient}.
* @since 2.5
* @throws IllegalStateException if not yet initialized.
* @see #getNativeClient()
*/
public AbstractRedisClient getRequiredNativeClient() {
return RedisAssertions.requireState(getNativeClient(),
"Client not yet initialized; Did you forget to call initialize the bean");
}
@Nullable
private String getRedisUsername() {
return RedisConfiguration.getUsernameOrElse(configuration, standaloneConfig::getUsername);
}
/**
* Returns the password used for authenticating with the Redis server.
*
* @return password for authentication or {@literal null} if not set.
*/
@Nullable
public String getPassword() {
return getRedisPassword().map(String::new).orElse(null);
}
private RedisPassword getRedisPassword() {
return RedisConfiguration.getPasswordOrElse(configuration, standaloneConfig::getPassword);
}
/**
* Sets the password used for authenticating with the Redis server.
*
* @param password the password to set
* @deprecated since 2.0, configure the password using {@link RedisStandaloneConfiguration},
* {@link RedisSentinelConfiguration} or {@link RedisClusterConfiguration}.
*/
@Deprecated
public void setPassword(String password) {
if (RedisConfiguration.isAuthenticationAware(configuration)) {
((WithPassword) configuration).setPassword(password);
return;
}
standaloneConfig.setPassword(RedisPassword.of(password));
}
/**
* Returns the shutdown timeout for shutting down the RedisClient (in milliseconds).
*
* @return shutdown timeout.
* @since 1.6
*/
public long getShutdownTimeout() {
return clientConfiguration.getShutdownTimeout().toMillis();
}
/**
* Sets the shutdown timeout for shutting down the RedisClient (in milliseconds).
*
* @param shutdownTimeout the shutdown timeout.
* @since 1.6
* @deprecated since 2.0, configure the shutdown timeout using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setShutdownTimeout(long shutdownTimeout) {
getMutableConfiguration().setShutdownTimeout(Duration.ofMillis(shutdownTimeout));
}
/**
* Get the {@link ClientResources} to reuse infrastructure.
*
* @return {@literal null} if not set.
* @since 1.7
*/
@Nullable
public ClientResources getClientResources() {
return clientConfiguration.getClientResources().orElse(null);
}
/**
* Sets the {@link ClientResources} to reuse the client infrastructure. <br />
* Set to {@literal null} to not share resources.
*
* @param clientResources can be {@literal null}.
* @since 1.7
* @deprecated since 2.0, configure {@link ClientResources} using {@link LettuceClientConfiguration}.
* @throws IllegalStateException if {@link LettuceClientConfiguration} is immutable.
*/
@Deprecated
public void setClientResources(ClientResources clientResources) {
getMutableConfiguration().setClientResources(clientResources);
}
/**
* @return the {@link LettuceClientConfiguration}.
* @since 2.0
*/
public LettuceClientConfiguration getClientConfiguration() {
return this.clientConfiguration;
}
/**
* @return the {@link RedisStandaloneConfiguration}.
* @since 2.0
*/
public RedisStandaloneConfiguration getStandaloneConfiguration() {
return this.standaloneConfig;
}
/**
* @return the {@link RedisSocketConfiguration} or {@literal null} if not set.
* @since 2.1
*/
@Nullable
public RedisSocketConfiguration getSocketConfiguration() {
return isDomainSocketAware() ? (RedisSocketConfiguration) this.configuration : null;
}
/**
* @return the {@link RedisSentinelConfiguration}, may be {@literal null}.
* @since 2.0
*/
@Nullable
public RedisSentinelConfiguration getSentinelConfiguration() {
return isRedisSentinelAware() ? (RedisSentinelConfiguration) this.configuration : null;
}
/**
* @return the {@link RedisClusterConfiguration}, may be {@literal null}.
* @since 2.0
*/
@Nullable
public RedisClusterConfiguration getClusterConfiguration() {
return isClusterAware() ? (RedisClusterConfiguration) this.configuration : null;
}
@Override
public int getPhase() {
return this.phase;
}
/**
* Specify the lifecycle phase for pausing and resuming this executor. The default is {@code 0}.
*
* @since 3.2
* @see SmartLifecycle#getPhase()
*/
public void setPhase(int phase) {
this.phase = phase;
}
/**
* @since 3.3
*/
@Override
public boolean isAutoStartup() {
return this.autoStartup;
}
/**
* Configure if this Lifecycle connection factory should get started automatically by the container at the time that
* the containing ApplicationContext gets refreshed.
* <p>
* This connection factory defaults to early auto-startup during {@link #afterPropertiesSet()} and can potentially
* create Redis connections early on in the lifecycle. See {@link #setEarlyStartup(boolean)} for delaying connection
* creation to the ApplicationContext refresh if auto-startup is enabled.
*
* @param autoStartup {@literal true} to automatically {@link #start()} the connection factory; {@literal false}
* otherwise.
* @since 3.3
* @see #setEarlyStartup(boolean)
* @see #start()
*/
public void setAutoStartup(boolean autoStartup) {
this.autoStartup = autoStartup;
}
/**
* @return whether to {@link #start()} the component during {@link #afterPropertiesSet()}.
* @since 3.3
*/
public boolean isEarlyStartup() {
return this.earlyStartup;
}
/**
* Configure if this InitializingBean's component Lifecycle should get started early by {@link #afterPropertiesSet()}
* at the time that the bean is initialized. The component defaults to auto-startup.
* <p>
* This method is related to {@link #setAutoStartup(boolean) auto-startup} and can be used to delay Redis client
* startup until the ApplicationContext refresh. Disabling early startup does not disable auto-startup.
*
* @param earlyStartup {@literal true} to early {@link #start()} the component; {@literal false} otherwise.
* @since 3.3
* @see #setAutoStartup(boolean)
*/
public void setEarlyStartup(boolean earlyStartup) {
this.earlyStartup = earlyStartup;
}
/**
* Specifies if pipelined results should be converted to the expected data type. If {@code false}, results of
* {@link LettuceConnection#closePipeline()} and {LettuceConnection#exec()} will be of the type returned by the
* Lettuce driver.
*
* @return {@code true} to convert pipeline and transaction results; {@code false} otherwise.
*/
@Override
public boolean getConvertPipelineAndTxResults() {
return convertPipelineAndTxResults;
}
/**
* Specifies if pipelined and transaction results should be converted to the expected data type. If {@code false},
* results of {@link LettuceConnection#closePipeline()} and {LettuceConnection#exec()} will be of the type returned by
* the Lettuce driver.
*
* @param convertPipelineAndTxResults {@code true} to convert pipeline and transaction results; {@code false}
* otherwise.
*/
public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) {
this.convertPipelineAndTxResults = convertPipelineAndTxResults;
}
/**
* @return true when {@link RedisStaticMasterReplicaConfiguration} is present.
* @since 2.1
*/
private boolean isStaticMasterReplicaAware() {
return RedisConfiguration.isStaticMasterReplicaConfiguration(this.configuration);
}
/**
* @return true when {@link RedisSentinelConfiguration} is present.
* @since 1.5
*/
public boolean isRedisSentinelAware() {
return RedisConfiguration.isSentinelConfiguration(this.configuration);
}
/**
* @return true when {@link RedisSocketConfiguration} is present.
* @since 2.1
*/
private boolean isDomainSocketAware() {
return RedisConfiguration.isDomainSocketConfiguration(this.configuration);
}
/**
* @return true when {@link RedisClusterConfiguration} is present.
* @since 1.7
*/
public boolean isClusterAware() {
return RedisConfiguration.isClusterConfiguration(this.configuration);
}
@Override
public void start() {
State current = this.state.getAndUpdate(state -> isCreatedOrStopped(state) ? State.STARTING : state);
if (isCreatedOrStopped(current)) {
AbstractRedisClient client = createClient();
this.client = client;
LettuceConnectionProvider connectionProvider = new ExceptionTranslatingConnectionProvider(
createConnectionProvider(client, CODEC));
this.connectionProvider = connectionProvider;
this.reactiveConnectionProvider = new ExceptionTranslatingConnectionProvider(
createConnectionProvider(client, LettuceReactiveRedisConnection.CODEC));
if (isClusterAware()) {
this.clusterCommandExecutor = createClusterCommandExecutor((RedisClusterClient) client, connectionProvider);
}
this.state.set(State.STARTED);
if (getEagerInitialization() && getShareNativeConnection()) {
initConnection();
}
}
}
private static boolean isCreatedOrStopped(@Nullable State state) {
return State.CREATED.equals(state) || State.STOPPED.equals(state);
}
private ClusterCommandExecutor createClusterCommandExecutor(RedisClusterClient client,
LettuceConnectionProvider connectionProvider) {
return new ClusterCommandExecutor(new LettuceClusterTopologyProvider(client),
new LettuceClusterConnection.LettuceClusterNodeResourceProvider(connectionProvider), EXCEPTION_TRANSLATION,
this.executor);
}
@Override
public void stop() {
if (state.compareAndSet(State.STARTED, State.STOPPING)) {
resetConnection();
dispose(connectionProvider);
connectionProvider = null;
dispose(reactiveConnectionProvider);
reactiveConnectionProvider = null;
if (client != null) {
try {
Duration quietPeriod = clientConfiguration.getShutdownQuietPeriod();
Duration timeout = clientConfiguration.getShutdownTimeout();
client.shutdown(quietPeriod.toMillis(), timeout.toMillis(), TimeUnit.MILLISECONDS);
client = null;
} catch (Exception ex) {
if (log.isWarnEnabled()) {
log.warn(ClassUtils.getShortName(client.getClass()) + " did not shut down gracefully.", ex);
}
}
}
}
state.set(State.STOPPED);
}
@Override
public boolean isRunning() {
return State.STARTED.equals(this.state.get());
}
@Override
public void afterPropertiesSet() {