Class LettuceConnectionFactory

java.lang.Object
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
All Implemented Interfaces:
DisposableBean, InitializingBean, Lifecycle, Phased, SmartLifecycle, PersistenceExceptionTranslator, ReactiveRedisConnectionFactory, RedisConnectionFactory

Connection factory creating Lettuce-based connections.

This factory creates a new LettuceConnection on each call to getConnection(). While multiple LettuceConnections share a single thread-safe native connection by default, LettuceConnection and its clustered variant are not Thread-safe and instances should not be shared across threads.

The shared native connection is never closed by LettuceConnection, therefore it is not validated by default on getConnection(). Use setValidateConnection(boolean) to change this behavior if necessary. If shareNativeConnection is true, a shared connection will be used for regular operations and a 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.

LettuceConnectionFactory should be configured using an environmental configuration and the client configuration. Lettuce supports the following environmental configurations:

This connection factory implements InitializingBean and SmartLifecycle for flexible lifecycle control. It must be initialized and started before you can obtain a connection. Initialization starts this bean early by default. You can Lifecycle.stop() and restart this connection factory if needed. Disabling early startup leaves lifecycle management to the container refresh if auto-startup is enabled.

Author:
Costin Leau, Jennifer Hickey, Thomas Darimont, Christoph Strobl, Mark Paluch, Balázs Németh, Ruben Cervilla, Luis De Bello, Andrea Como, Chris Bono, John Blum, Zhian Chen, UHyeon Jeong
  • Constructor Details

  • Method Details

    • createRedisConfiguration

      public static RedisConfiguration createRedisConfiguration(String redisUri)
      Creates a RedisConfiguration based on a URI according to the following:
      Parameters:
      redisUri - the connection URI in the format of a RedisURI.
      Returns:
      an appropriate RedisConfiguration instance representing the Redis URI.
      Since:
      2.5.3
      See Also:
    • createRedisConfiguration

      public static RedisConfiguration createRedisConfiguration(io.lettuce.core.RedisURI redisUri)
      Creates a RedisConfiguration based on a RedisURI according to the following:
      Parameters:
      redisUri - the connection URI.
      Returns:
      an appropriate RedisConfiguration instance representing the Redis URI.
      Since:
      2.5.3
      See Also:
      • RedisURI
    • setExecutor

      public void setExecutor(AsyncTaskExecutor executor)
      Configures the executor used to execute commands asynchronously across the cluster.
      Parameters:
      executor - executor used to execute commands asynchronously across the cluster.
      Since:
      3.2
    • getHostName

      public String getHostName()
      Returns the current host.
      Returns:
      the host.
    • setHostName

      @Deprecated public void setHostName(String hostName)
      Deprecated.
      since 2.0, configure the hostname using RedisStandaloneConfiguration.
      Sets the hostname.
      Parameters:
      hostName - the hostname to set.
    • getPort

      public int getPort()
      Returns the current port.
      Returns:
      the port.
    • setPort

      @Deprecated public void setPort(int port)
      Deprecated.
      since 2.0, configure the port using RedisStandaloneConfiguration.
      Sets the port.
      Parameters:
      port - the port to set.
    • setPipeliningFlushPolicy

      public void setPipeliningFlushPolicy(LettuceConnection.PipeliningFlushPolicy pipeliningFlushPolicy)
      Configures the flushing policy when using pipelining. If not set, defaults to flush on each command.
      Parameters:
      pipeliningFlushPolicy - the flushing policy to control when commands get written to the Redis connection.
      Since:
      2.3
      See Also:
    • getTimeout

      public long getTimeout()
      Returns the connection timeout (in milliseconds).
      Returns:
      connection timeout.
    • setTimeout

      @Deprecated public void setTimeout(long timeout)
      Deprecated.
      since 2.0, configure the timeout using LettuceClientConfiguration.
      Sets the connection timeout (in milliseconds).
      Parameters:
      timeout - the timeout.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
    • isUseSsl

      public boolean isUseSsl()
      Returns whether to use SSL.
      Returns:
      use of SSL.
    • setUseSsl

      @Deprecated public void setUseSsl(boolean useSsl)
      Deprecated.
      since 2.0, configure SSL usage using LettuceClientConfiguration.
      Sets to use SSL connection.
      Parameters:
      useSsl - true to use SSL.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
    • isVerifyPeer

      @Deprecated(since="3.4") public boolean isVerifyPeer()
      Deprecated.
      Returns whether to verify certificate validity/hostname check when SSL is used.
      Returns:
      whether to verify peers when using SSL.
    • setVerifyPeer

      @Deprecated public void setVerifyPeer(boolean verifyPeer)
      Deprecated.
      since 2.0, configure peer verification using LettuceClientConfiguration.
      Sets to use verify certificate validity/hostname check when SSL is used.
      Parameters:
      verifyPeer - false not to verify hostname.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
    • isStartTls

      public boolean isStartTls()
      Returns whether to issue a StartTLS.
      Returns:
      use of StartTLS.
    • setStartTls

      @Deprecated public void setStartTls(boolean startTls)
      Deprecated.
      since 2.0, configure StartTLS using LettuceClientConfiguration.
      Sets to issue StartTLS.
      Parameters:
      startTls - true to issue StartTLS.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
    • getValidateConnection

      public boolean getValidateConnection()
      Indicates if validation of the native Lettuce connection is enabled.
      Returns:
      connection validation enabled.
    • setValidateConnection

      public void setValidateConnection(boolean validateConnection)
      Enables validation of the shared native Lettuce connection on calls to getConnection(). A new connection will be created and used if validation fails.

      Lettuce will automatically reconnect until close is called, which should never happen through LettuceConnection if a shared native connection is used, therefore the default is false.

      Setting this to 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.

      Parameters:
      validateConnection - enable connection validation.
    • getShareNativeConnection

      public boolean getShareNativeConnection()
      Indicates if multiple LettuceConnections should share a single native connection.
      Returns:
      native connection shared.
    • setShareNativeConnection

      public void setShareNativeConnection(boolean shareNativeConnection)
      Enables multiple LettuceConnections to share a single native connection. If set to false, every operation on LettuceConnection will open and close a socket.
      Parameters:
      shareNativeConnection - enable connection sharing.
    • getEagerInitialization

      public boolean getEagerInitialization()
      Indicates shared connections should be eagerly initialized. Eager initialization requires a running Redis instance during 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.
      Returns:
      true if the shared connection is initialized upon start().
      Since:
      2.2
      See Also:
    • setEagerInitialization

      public void setEagerInitialization(boolean eagerInitialization)
      Enables eager initialization of shared connections.
      Parameters:
      eagerInitialization - enable eager connection shared connection initialization upon afterPropertiesSet().
      Since:
      2.2
    • getDatabase

      public int getDatabase()
      Returns the index of the database.
      Returns:
      the database index.
    • setDatabase

      @Deprecated public void setDatabase(int index)
      Sets the index of the database used by this connection factory. Default is 0.
      Parameters:
      index - database index.
    • getClientName

      public @Nullable String getClientName()
      Returns the client name.
      Returns:
      the client name or null if not set.
      Since:
      2.1
    • setClientName

      @Deprecated public void setClientName(@Nullable String clientName)
      Deprecated.
      configure the client name using LettuceClientConfiguration.
      Sets the client name used by this connection factory.
      Parameters:
      clientName - the client name. Can be null.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
      Since:
      2.1
    • getNativeClient

      public @Nullable io.lettuce.core.AbstractRedisClient getNativeClient()
      Returns the native AbstractRedisClient used by this instance. The client is initialized as part of the bean initialization lifecycle and only available when this connection factory is initialized.

      Depending on the configuration, the client can be either RedisClient or RedisClusterClient.

      Returns:
      the native AbstractRedisClient. Can be null if not initialized.
      Since:
      2.5
      See Also:
    • getRequiredNativeClient

      public io.lettuce.core.AbstractRedisClient getRequiredNativeClient()
      Returns the native AbstractRedisClient used by this instance. The client is initialized as part of the bean initialization lifecycle and only available when this connection factory is initialized. Throws IllegalStateException if not yet initialized.

      Depending on the configuration, the client can be either RedisClient or RedisClusterClient.

      Returns:
      the native AbstractRedisClient.
      Throws:
      IllegalStateException - if not yet initialized.
      Since:
      2.5
      See Also:
    • getPassword

      public @Nullable String getPassword()
      Returns the password used for authenticating with the Redis server.
      Returns:
      password for authentication or null if not set.
    • setPassword

      @Deprecated public void setPassword(String password)
      Deprecated.
      Sets the password used for authenticating with the Redis server.
      Parameters:
      password - the password to set
    • getShutdownTimeout

      public long getShutdownTimeout()
      Returns the shutdown timeout for shutting down the RedisClient (in milliseconds).
      Returns:
      shutdown timeout.
      Since:
      1.6
    • setShutdownTimeout

      @Deprecated public void setShutdownTimeout(long shutdownTimeout)
      Deprecated.
      since 2.0, configure the shutdown timeout using LettuceClientConfiguration.
      Sets the shutdown timeout for shutting down the RedisClient (in milliseconds).
      Parameters:
      shutdownTimeout - the shutdown timeout.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
      Since:
      1.6
    • getClientResources

      public @Nullable io.lettuce.core.resource.ClientResources getClientResources()
      Get the ClientResources to reuse infrastructure.
      Returns:
      null if not set.
      Since:
      1.7
    • setClientResources

      @Deprecated public void setClientResources(io.lettuce.core.resource.ClientResources clientResources)
      Deprecated.
      since 2.0, configure ClientResources using LettuceClientConfiguration.
      Sets the ClientResources to reuse the client infrastructure.
      Set to null to not share resources.
      Parameters:
      clientResources - can be null.
      Throws:
      IllegalStateException - if LettuceClientConfiguration is immutable.
      Since:
      1.7
    • getClientConfiguration

      public LettuceClientConfiguration getClientConfiguration()
      Returns:
      the LettuceClientConfiguration.
      Since:
      2.0
    • getStandaloneConfiguration

      public RedisStandaloneConfiguration getStandaloneConfiguration()
      Returns:
      the RedisStandaloneConfiguration.
      Since:
      2.0
    • getSocketConfiguration

      public @Nullable RedisSocketConfiguration getSocketConfiguration()
      Returns:
      the RedisSocketConfiguration or null if not set.
      Since:
      2.1
    • getSentinelConfiguration

      public @Nullable RedisSentinelConfiguration getSentinelConfiguration()
      Returns:
      the RedisSentinelConfiguration, may be null.
      Since:
      2.0
    • getClusterConfiguration

      public @Nullable RedisClusterConfiguration getClusterConfiguration()
      Returns:
      the RedisClusterConfiguration, may be null.
      Since:
      2.0
    • getPhase

      public int getPhase()
      Specified by:
      getPhase in interface Phased
      Specified by:
      getPhase in interface SmartLifecycle
    • setPhase

      public void setPhase(int phase)
      Specify the lifecycle phase for pausing and resuming this executor. The default is 0.
      Since:
      3.2
      See Also:
    • isAutoStartup

      public boolean isAutoStartup()
      Specified by:
      isAutoStartup in interface SmartLifecycle
      Since:
      3.3
    • setAutoStartup

      public void setAutoStartup(boolean autoStartup)
      Configure if this Lifecycle connection factory should get started automatically by the container at the time that the containing ApplicationContext gets refreshed.

      This connection factory defaults to early auto-startup during afterPropertiesSet() and can potentially create Redis connections early on in the lifecycle. See setEarlyStartup(boolean) for delaying connection creation to the ApplicationContext refresh if auto-startup is enabled.

      Parameters:
      autoStartup - true to automatically start() the connection factory; false otherwise.
      Since:
      3.3
      See Also:
    • isEarlyStartup

      public boolean isEarlyStartup()
      Returns:
      whether to start() the component during afterPropertiesSet().
      Since:
      3.3
    • setEarlyStartup

      public void setEarlyStartup(boolean earlyStartup)
      Configure if this InitializingBean's component Lifecycle should get started early by afterPropertiesSet() at the time that the bean is initialized. The component defaults to auto-startup.

      This method is related to auto-startup and can be used to delay Redis client startup until the ApplicationContext refresh. Disabling early startup does not disable auto-startup.

      Parameters:
      earlyStartup - true to early start() the component; false otherwise.
      Since:
      3.3
      See Also:
    • getConvertPipelineAndTxResults

      public boolean getConvertPipelineAndTxResults()
      Specifies if pipelined results should be converted to the expected data type. If false, results of LettuceConnection.closePipeline() and {LettuceConnection#exec()} will be of the type returned by the Lettuce driver.
      Specified by:
      getConvertPipelineAndTxResults in interface RedisConnectionFactory
      Returns:
      true to convert pipeline and transaction results; false otherwise.
    • setConvertPipelineAndTxResults

      public void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults)
      Specifies if pipelined and transaction results should be converted to the expected data type. If false, results of LettuceConnection.closePipeline() and {LettuceConnection#exec()} will be of the type returned by the Lettuce driver.
      Parameters:
      convertPipelineAndTxResults - true to convert pipeline and transaction results; false otherwise.
    • isRedisSentinelAware

      public boolean isRedisSentinelAware()
      Returns:
      true when RedisSentinelConfiguration is present.
      Since:
      1.5
    • isClusterAware

      public boolean isClusterAware()
      Returns:
      true when RedisClusterConfiguration is present.
      Since:
      1.7
    • start

      public void start()
      Specified by:
      start in interface Lifecycle
    • stop

      public void stop()
      Specified by:
      stop in interface Lifecycle
    • isRunning

      public boolean isRunning()
      Specified by:
      isRunning in interface Lifecycle
    • afterPropertiesSet

      public void afterPropertiesSet()
      Specified by:
      afterPropertiesSet in interface InitializingBean
    • destroy

      public void destroy()
      Specified by:
      destroy in interface DisposableBean
    • getConnection

      public RedisConnection getConnection()
      Description copied from interface: RedisConnectionFactory
      Returns a suitable connection for interacting with Redis.
      Specified by:
      getConnection in interface RedisConnectionFactory
      Returns:
      connection for interacting with Redis.
    • getClusterConnection

      public RedisClusterConnection getClusterConnection()
      Description copied from interface: RedisConnectionFactory
      Returns a suitable connection for interacting with Redis Cluster.
      Specified by:
      getClusterConnection in interface RedisConnectionFactory
      Returns:
      a connection for interacting with Redis Cluster.
    • getSentinelConnection

      public RedisSentinelConnection getSentinelConnection()
      Description copied from interface: RedisConnectionFactory
      Returns a suitable connection for interacting with Redis Sentinel.
      Specified by:
      getSentinelConnection in interface RedisConnectionFactory
      Returns:
      a connection for interacting with Redis Sentinel.
    • doCreateLettuceConnection

      protected LettuceConnection doCreateLettuceConnection(@Nullable io.lettuce.core.api.StatefulRedisConnection<byte[],byte[]> sharedConnection, LettuceConnectionProvider connectionProvider, long timeout, int database)
      Customization hook for LettuceConnection creation.
      Parameters:
      sharedConnection - the shared StatefulRedisConnection if getShareNativeConnection() is true; null otherwise.
      connectionProvider - the LettuceConnectionProvider to release connections.
      timeout - command timeout in TimeUnit.MILLISECONDS.
      database - database index to operate on.
      Returns:
      the LettuceConnection.
      Throws:
      IllegalArgumentException - if a required parameter is null.
      Since:
      2.2
    • doCreateLettuceClusterConnection

      protected LettuceClusterConnection doCreateLettuceClusterConnection(@Nullable io.lettuce.core.cluster.api.StatefulRedisClusterConnection<byte[],byte[]> sharedConnection, LettuceConnectionProvider connectionProvider, ClusterTopologyProvider topologyProvider, ClusterCommandExecutor clusterCommandExecutor, Duration commandTimeout)
      Customization hook for LettuceClusterConnection creation.
      Parameters:
      sharedConnection - the shared StatefulRedisConnection if getShareNativeConnection() is true; null otherwise.
      connectionProvider - the LettuceConnectionProvider to release connections.
      topologyProvider - the ClusterTopologyProvider.
      clusterCommandExecutor - the ClusterCommandExecutor to release connections.
      commandTimeout - command timeout Duration.
      Returns:
      the LettuceConnection.
      Throws:
      IllegalArgumentException - if a required parameter is null.
      Since:
      2.2
    • getReactiveConnection

      public org.springframework.data.redis.connection.lettuce.LettuceReactiveRedisConnection getReactiveConnection()
      Specified by:
      getReactiveConnection in interface ReactiveRedisConnectionFactory
      Returns:
      a reactive Redis connection.
    • getReactiveClusterConnection

      public org.springframework.data.redis.connection.lettuce.LettuceReactiveRedisClusterConnection getReactiveClusterConnection()
      Specified by:
      getReactiveClusterConnection in interface ReactiveRedisConnectionFactory
      Returns:
      a reactive Redis Cluster connection.
    • initConnection

      public void initConnection()
      Initialize the shared connection if native connection sharing is enabled and reset any previously existing connection.
    • resetConnection

      public void resetConnection()
      Reset the underlying shared Connection, to be reinitialized on next access.
    • validateConnection

      public void validateConnection()
      Validate the shared connections and reinitialize if invalid.
    • translateExceptionIfPossible

      public @Nullable DataAccessException translateExceptionIfPossible(RuntimeException ex)
      Specified by:
      translateExceptionIfPossible in interface PersistenceExceptionTranslator
    • getSharedConnection

      protected @Nullable io.lettuce.core.api.StatefulRedisConnection<byte[],byte[]> getSharedConnection()
      Returns:
      the shared connection using byte[] encoding for imperative API use. null if connection sharing is disabled or when connected to Redis Cluster.
    • getSharedClusterConnection

      protected @Nullable io.lettuce.core.cluster.api.StatefulRedisClusterConnection<byte[],byte[]> getSharedClusterConnection()
      Returns:
      the shared cluster connection using byte[] encoding for imperative API use. null if connection sharing is disabled or when connected to Redis Standalone/Sentinel/Master-Replica.
      Since:
      2.5.7
    • getSharedReactiveConnection

      protected @Nullable io.lettuce.core.api.StatefulConnection<ByteBuffer,ByteBuffer> getSharedReactiveConnection()
      Returns:
      the shared connection using ByteBuffer encoding for reactive API use. null if connection sharing is disabled.
      Since:
      2.0.1
    • doCreateConnectionProvider

      protected LettuceConnectionProvider doCreateConnectionProvider(io.lettuce.core.AbstractRedisClient client, io.lettuce.core.codec.RedisCodec<?,?> codec)
      Create a LettuceConnectionProvider given AbstractRedisClient and RedisCodec. Configuration of this connection factory specifies the type of the created connection provider. This method creates either a LettuceConnectionProvider for either RedisClient or RedisClusterClient. Subclasses may override this method to decorate the connection provider.
      Parameters:
      client - either RedisClient or RedisClusterClient, must not be null.
      codec - used for connection creation, must not be null. By default, a byte[] codec. Reactive connections require a ByteBuffer codec.
      Returns:
      the connection provider.
      Since:
      2.1
    • createClient

      protected io.lettuce.core.AbstractRedisClient createClient()