Class LettuceConnectionFactory

java.lang.Object
org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory
All Implemented Interfaces:
org.springframework.beans.factory.DisposableBean, org.springframework.beans.factory.InitializingBean, org.springframework.dao.support.PersistenceExceptionTranslator, ReactiveRedisConnectionFactory, RedisConnectionFactory

public class LettuceConnectionFactory extends Object implements org.springframework.beans.factory.InitializingBean, org.springframework.beans.factory.DisposableBean, RedisConnectionFactory, ReactiveRedisConnectionFactory
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 must be initialized prior to obtaining connections.

Author:
Costin Leau, Jennifer Hickey, Thomas Darimont, Christoph Strobl, Mark Paluch, Balázs Németh, Ruben Cervilla, Luis De Bello, Andrea Como, Chris Bono
  • 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:
      • RedisURI
    • 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
    • afterPropertiesSet

      public void afterPropertiesSet()
      Specified by:
      afterPropertiesSet in interface org.springframework.beans.factory.InitializingBean
    • destroy

      public void destroy()
      Specified by:
      destroy in interface org.springframework.beans.factory.DisposableBean
    • getConnection

      public RedisConnection getConnection()
      Description copied from interface: RedisConnectionFactory
      Provides 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
      Provides a suitable connection for interacting with Redis Cluster.
      Specified by:
      getClusterConnection in interface RedisConnectionFactory
      Returns:
    • 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 org.springframework.dao.DataAccessException translateExceptionIfPossible(RuntimeException ex)
      Specified by:
      translateExceptionIfPossible in interface org.springframework.dao.support.PersistenceExceptionTranslator
    • 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

      public boolean isVerifyPeer()
      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 application 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:
      {@link true} if the shared connection is initialized upon afterPropertiesSet().
      Since:
      2.2
    • 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

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

      @Nullable public 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

      @Nullable public 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

      @Nullable public 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 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

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

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

      @Nullable public RedisClusterConfiguration getClusterConfiguration()
      Returns:
      the RedisClusterConfiguration, may be null.
      Since:
      2.0
    • 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:
      Whether or not to convert pipeline and tx results.
    • 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 - Whether or not to convert pipeline and tx results.
    • 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
    • getSharedConnection

      @Nullable protected 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

      @Nullable protected 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

      @Nullable protected 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()
    • getSentinelConnection

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