Class LettuceConnection
- All Implemented Interfaces:
- AutoCloseable,- DefaultedRedisConnection,- RedisCommands,- RedisCommandsProvider,- RedisConnection,- RedisConnectionCommands,- RedisGeoCommands,- RedisHashCommands,- RedisHyperLogLogCommands,- RedisKeyCommands,- RedisListCommands,- RedisPubSubCommands,- RedisScriptingCommands,- RedisServerCommands,- RedisSetCommands,- RedisStreamCommands,- RedisStringCommands,- RedisTxCommands,- RedisZSetCommands
- Direct Known Subclasses:
- LettuceClusterConnection
RedisConnection implementation on top of Lettuce Redis
 client.
 
 While the underlying Lettuce RedisClient and StatefulRedisConnection instances used by
 LettuceConnection are Thread-safe, this class itself is not Thread-safe. Therefore, instances of
 LettuceConnection should not be shared across multiple Threads when executing Redis commands and other
 operations. If optimal performance is required by your application(s), then we recommend direct access to the
 low-level, API provided by the underlying Lettuce client library (driver), where such Thread-safety guarantees can be
 made. Simply call getNativeConnection() and use the native resource as required.
- Author:
- Costin Leau, Jennifer Hickey, Christoph Strobl, Thomas Darimont, David Liu, Mark Paluch, Ninad Divadkar, Tamil Selvan, ihaohong, John Blum
- 
Nested Class SummaryNested ClassesModifier and TypeClassDescriptionstatic interfaceStrategy interface to control pipelining flush behavior.static interfaceState object associated with flushing of the currently ongoing pipeline.Nested classes/interfaces inherited from interface org.springframework.data.redis.connection.RedisGeoCommandsRedisGeoCommands.DistanceUnit, RedisGeoCommands.GeoCommandArgs, RedisGeoCommands.GeoLocation<T>, RedisGeoCommands.GeoRadiusCommandArgs, RedisGeoCommands.GeoSearchCommandArgs, RedisGeoCommands.GeoSearchStoreCommandArgsNested classes/interfaces inherited from interface org.springframework.data.redis.connection.RedisListCommandsRedisListCommands.Direction, RedisListCommands.PositionNested classes/interfaces inherited from interface org.springframework.data.redis.connection.RedisServerCommandsRedisServerCommands.FlushOption, RedisServerCommands.MigrateOption, RedisServerCommands.ShutdownOptionNested classes/interfaces inherited from interface org.springframework.data.redis.connection.RedisStreamCommandsRedisStreamCommands.XAddOptions, RedisStreamCommands.XClaimOptions, RedisStreamCommands.XPendingOptionsNested classes/interfaces inherited from interface org.springframework.data.redis.connection.RedisStringCommandsRedisStringCommands.BitOperation, RedisStringCommands.SetOptionNested classes/interfaces inherited from interface org.springframework.data.redis.connection.RedisZSetCommandsRedisZSetCommands.Limit, RedisZSetCommands.Range, RedisZSetCommands.ZAddArgs
- 
Constructor SummaryConstructorsConstructorDescriptionLettuceConnection(long timeout, io.lettuce.core.RedisClient client) Creates a newLettuceConnection.LettuceConnection(io.lettuce.core.api.StatefulRedisConnection<byte[], byte[]> sharedConnection, long timeout, io.lettuce.core.AbstractRedisClient client, int defaultDbIndex) Creates a newLettuceConnection.LettuceConnection(io.lettuce.core.api.StatefulRedisConnection<byte[], byte[]> sharedConnection, long timeout, io.lettuce.core.RedisClient client) Creates a newLettuceConnection.LettuceConnection(io.lettuce.core.api.StatefulRedisConnection<byte[], byte[]> sharedConnection, LettuceConnectionProvider connectionProvider, long timeout, int defaultDbIndex) Creates a newLettuceConnection.
- 
Method SummaryModifier and TypeMethodDescriptionvoidclose()Closes or quits the connection.Executes the commands in the pipeline and returns their result.commands()GetRedisCommands.protected DataAccessExceptionvoiddiscard()Discard all commands issued afterRedisTxCommands.multi().protected LettuceSubscriptiondoCreateSubscription(MessageListener listener, io.lettuce.core.pubsub.StatefulRedisPubSubConnection<byte[], byte[]> connection, LettuceConnectionProvider connectionProvider) Customization hook to create aLettuceSubscription.protected io.lettuce.core.api.StatefulConnection<byte[],byte[]> byte[]echo(byte[] message) Returnsmessagevia server roundtrip.exec()Executes all queued commands in a transaction started withRedisTxCommands.multi().Native or raw execution of the given Redis command along with the given arguments.'Native' or 'raw' execution of the given command along-side the given arguments.GetRedisGeoCommands.protected io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands<byte[],byte[]> protected io.lettuce.core.cluster.api.sync.RedisClusterCommands<byte[],byte[]> io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands<byte[],byte[]> Returns the native connection (the underlying library/driver object).protected RedisSentinelConnectiongetSentinelConnection(RedisNode sentinel) GetRedisSentinelCommandsconnected to given node.Returns the current subscription for this connection or null if the connection is not subscribed.GetRedisHashCommands.protected booleanCheck if node is active by sending ping.booleanisClosed()Indicates whether the underlying connection is closed or not.booleanIndicates whether the connection is currently pipelined or not.booleanIndicates whether the connection is in "queue"(or "MULTI") mode or not.booleanIndicates whether the current connection is subscribed (to at least one channel) or not.GetRedisKeyCommands.GetRedisListCommands.voidmulti()Mark the start of a transaction block.voidActivates the pipeline mode for this connection.ping()Test connection.voidpSubscribe(MessageListener listener, byte[]... patterns) Subscribes the connection to all channels matching the given patterns.publish(byte[] channel, byte[] message) Publishes the given message to the given channel.voidselect(int dbIndex) Select the DB with given positivedbIndex.GetRedisServerCommands.GetRedisSetCommands.voidsetConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) Specifies if pipelined and transaction results should be converted to the expected data type.voidsetPipeliningFlushPolicy(LettuceConnection.PipeliningFlushPolicy pipeliningFlushPolicy) Configures the flushing policy when using pipelining.GetRedisStreamCommands.GetRedisStringCommands.voidsubscribe(MessageListener listener, byte[]... channels) Subscribes the connection to the given channels.protected io.lettuce.core.pubsub.StatefulRedisPubSubConnection<byte[],byte[]> close()the current connection and open a new pub/sub connection to the Redis server.voidunwatch()Flushes all the previouslyRedisTxCommands.watch(byte[]...)keys.voidwatch(byte[]... keys) Watch givenkeysfor modifications during transaction started withRedisTxCommands.multi().GetRedisZSetCommands.Methods inherited from class org.springframework.data.redis.connection.AbstractRedisConnectiongetSentinelConnection, hasRedisSentinelConfigured, setSentinelConfigurationMethods inherited from class java.lang.Objectclone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitMethods inherited from interface org.springframework.data.redis.connection.DefaultedRedisConnectionappend, bgReWriteAof, bgSave, bitCount, bitCount, bitField, bitOp, bitPos, bLMove, bLPop, bRPop, bRPopLPush, bZPopMax, bZPopMin, copy, dbSize, decr, decrBy, del, dump, encodingOf, eval, evalSha, evalSha, exists, exists, expire, expireAt, flushAll, flushAll, flushDb, flushDb, geoAdd, geoAdd, geoAdd, geoDist, geoDist, geoHash, geoPos, geoRadius, geoRadius, geoRadiusByMember, geoRadiusByMember, geoRemove, geoSearch, geoSearchStore, get, getBit, getClientList, getClientName, getConfig, getDel, getEx, getRange, getSet, hDel, hExists, hGet, hGetAll, hIncrBy, hIncrBy, hKeys, hLen, hMGet, hMSet, hRandField, hRandField, hRandFieldWithValues, hRandFieldWithValues, hScan, hSet, hSetNX, hStrLen, hVals, idletime, incr, incrBy, incrBy, info, info, keys, killClient, lastSave, lIndex, lInsert, lLen, lMove, lPop, lPop, lPos, lPush, lPushX, lRange, lRem, lSet, lTrim, mGet, migrate, migrate, move, mSet, mSetNX, persist, pExpire, pExpireAt, pfAdd, pfCount, pfMerge, pSetEx, pTtl, pTtl, randomKey, refcount, rename, renameNX, replicaOf, replicaOfNoOne, resetConfigStats, restore, rewriteConfig, rPop, rPop, rPopLPush, rPush, rPushX, sAdd, save, scan, sCard, scriptExists, scriptFlush, scriptKill, scriptLoad, sDiff, sDiffStore, set, set, setBit, setClientName, setConfig, setEx, setNX, setRange, shutdown, shutdown, sInter, sInterStore, sIsMember, sMembers, sMIsMember, sMove, sort, sort, sPop, sPop, sRandMember, sRandMember, sRem, sScan, strLen, sUnion, sUnionStore, time, time, touch, ttl, ttl, type, unlink, xAck, xAdd, xClaim, xClaimJustId, xDel, xGroupCreate, xGroupCreate, xGroupDelConsumer, xGroupDestroy, xInfo, xInfoConsumers, xInfoGroups, xLen, xPending, xPending, xRange, xRange, xRead, xRead, xReadGroup, xReadGroup, xRevRange, xRevRange, xTrim, xTrim, zAdd, zAdd, zCard, zCount, zCount, zDiff, zDiffStore, zDiffWithScores, zIncrBy, zInter, zInterStore, zInterStore, zInterStore, zInterWithScores, zInterWithScores, zInterWithScores, zLexCount, zMScore, zPopMax, zPopMax, zPopMin, zPopMin, zRandMember, zRandMember, zRandMemberWithScore, zRandMemberWithScore, zRange, zRangeByLex, zRangeByScore, zRangeByScore, zRangeByScore, zRangeByScoreWithScores, zRangeStoreByLex, zRangeStoreByScore, zRangeStoreRevByLex, zRangeStoreRevByScore, zRangeWithScores, zRank, zRem, zRemRange, zRemRangeByLex, zRemRangeByScore, zRemRangeByScore, zRevRange, zRevRangeByLex, zRevRangeByScore, zRevRangeByScoreWithScores, zRevRangeWithScores, zRevRank, zScan, zScore, zUnion, zUnionStore, zUnionStore, zUnionStore, zUnionWithScores, zUnionWithScores, zUnionWithScoresMethods inherited from interface org.springframework.data.redis.connection.RedisGeoCommandsgeoAdd, geoRadiusByMemberMethods inherited from interface org.springframework.data.redis.connection.RedisKeyCommandsrestore, scanMethods inherited from interface org.springframework.data.redis.connection.RedisListCommandslPosMethods inherited from interface org.springframework.data.redis.connection.RedisStreamCommandsxAck, xAdd, xAdd, xClaim, xDel, xGroupDelConsumer, xPending, xPending, xPending, xPending, xPendingMethods inherited from interface org.springframework.data.redis.connection.RedisStringCommandsbitPosMethods inherited from interface org.springframework.data.redis.connection.RedisZSetCommandszAdd, zAdd, zRangeByLex, zRangeByLex, zRangeByScore, zRangeByScore, zRangeByScore, zRangeByScoreWithScores, zRangeByScoreWithScores, zRangeByScoreWithScores, zRangeStoreByLex, zRangeStoreByScore, zRangeStoreRevByLex, zRangeStoreRevByScore, zRevRangeByLex, zRevRangeByLex, zRevRangeByScore, zRevRangeByScore, zRevRangeByScore, zRevRangeByScoreWithScores, zRevRangeByScoreWithScores, zRevRangeByScoreWithScores
- 
Constructor Details- 
LettuceConnectionpublic LettuceConnection(long timeout, io.lettuce.core.RedisClient client) Creates a newLettuceConnection.- Parameters:
- timeout- The connection timeout (in milliseconds)
- client- The- RedisClientto use when instantiating a native connection
 
- 
LettuceConnectionpublic LettuceConnection(@Nullable io.lettuce.core.api.StatefulRedisConnection<byte[], byte[]> sharedConnection, long timeout, io.lettuce.core.RedisClient client) Creates a newLettuceConnection.- Parameters:
- sharedConnection- A native connection that is shared with other- LettuceConnections. Will not be used for transactions or blocking operations
- timeout- The connection timeout (in milliseconds)
- client- The- RedisClientto use when making pub/sub, blocking, and tx connections
 
- 
LettuceConnectionpublic LettuceConnection(@Nullable io.lettuce.core.api.StatefulRedisConnection<byte[], byte[]> sharedConnection, long timeout, @Nullable io.lettuce.core.AbstractRedisClient client, int defaultDbIndex) Creates a newLettuceConnection.- Parameters:
- sharedConnection- A native connection that is shared with other- LettuceConnections. Should not be used for transactions or blocking operations.
- timeout- The connection timeout (in milliseconds)
- client- The- RedisClientto use when making pub/sub connections.
- defaultDbIndex- The db index to use along with- RedisClientwhen establishing a dedicated connection.
- Since:
- 1.7
 
- 
LettuceConnectionpublic LettuceConnection(@Nullable io.lettuce.core.api.StatefulRedisConnection<byte[], byte[]> sharedConnection, LettuceConnectionProvider connectionProvider, long timeout, int defaultDbIndex) Creates a newLettuceConnection.- Parameters:
- sharedConnection- A native connection that is shared with other- LettuceConnections. Should not be used for transactions or blocking operations.
- connectionProvider- connection provider to obtain and release native connections.
- timeout- The connection timeout (in milliseconds)
- defaultDbIndex- The db index to use along with- RedisClientwhen establishing a dedicated connection.
- Since:
- 2.0
 
 
- 
- 
Method Details- 
commandsDescription copied from interface:RedisCommandsProviderGetRedisCommands.- Returns:
- never null.
 
- 
geoCommandsDescription copied from interface:RedisCommandsProviderGetRedisGeoCommands.- Returns:
- never null.
 
- 
hashCommandsDescription copied from interface:RedisCommandsProviderGetRedisHashCommands.- Returns:
- never null.
 
- 
hyperLogLogCommandsDescription copied from interface:RedisCommandsProvider- Returns:
- never null.
 
- 
keyCommandsDescription copied from interface:RedisCommandsProviderGetRedisKeyCommands.- Returns:
- never null.
 
- 
listCommandsDescription copied from interface:RedisCommandsProviderGetRedisListCommands.- Returns:
- never null.
 
- 
scriptingCommandsDescription copied from interface:RedisCommandsProvider- Returns:
- never null.
 
- 
setCommandsDescription copied from interface:RedisCommandsProviderGetRedisSetCommands.- Returns:
- never null.
 
- 
serverCommandsDescription copied from interface:RedisCommandsProviderGetRedisServerCommands.- Returns:
- never null.
 
- 
streamCommandsDescription copied from interface:RedisCommandsProviderGetRedisStreamCommands.- Returns:
- never null.
 
- 
stringCommandsDescription copied from interface:RedisCommandsProviderGetRedisStringCommands.- Returns:
- never null.
 
- 
zSetCommandsDescription copied from interface:RedisCommandsProviderGetRedisZSetCommands.- Returns:
- never null.
 
- 
convertLettuceAccessException
- 
executeDescription copied from interface:RedisCommandsNative or raw execution of the given Redis command along with the given arguments.The command is executed as is, with as little interpretation as possible - it is up to the caller to take care of any processing of arguments or the result. - Parameters:
- command- Redis- commandto execute; must not be null.
- args- optional array of command arguments; may be empty;
- Returns:
- the execution result; may be null.
 
- 
execute@Nullable public Object execute(String command, @Nullable io.lettuce.core.output.CommandOutput commandOutputTypeHint, byte[]... args) 'Native' or 'raw' execution of the given command along-side the given arguments.- Parameters:
- command- Command to execute
- commandOutputTypeHint- Type of Output to use, may be (may be null).
- args- Possible command arguments (may be null)
- Returns:
- execution result.
- See Also:
 
- 
closepublic void close()Description copied from interface:RedisConnectionCloses or quits the connection.- Specified by:
- closein interface- AutoCloseable
- Specified by:
- closein interface- RedisConnection
- Overrides:
- closein class- AbstractRedisConnection
 
- 
isClosedpublic boolean isClosed()Description copied from interface:RedisConnectionIndicates whether the underlying connection is closed or not.- Returns:
- true if the connection is closed, false otherwise.
 
- 
getNativeConnectionpublic io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands<byte[],byte[]> getNativeConnection()Description copied from interface:RedisConnectionReturns the native connection (the underlying library/driver object).- Returns:
- underlying, native object
 
- 
isQueueingpublic boolean isQueueing()Description copied from interface:RedisConnectionIndicates whether the connection is in "queue"(or "MULTI") mode or not. When queueing, all commands are postponed until EXEC or DISCARD commands are issued. Since in queueing no results are returned, the connection will return NULL on all operations that interact with the data.- Returns:
- true if the connection is in queue/MULTI mode, false otherwise
 
- 
isPipelinedpublic boolean isPipelined()Description copied from interface:RedisConnectionIndicates whether the connection is currently pipelined or not.- Returns:
- true if the connection is pipelined, false otherwise
- See Also:
 
- 
openPipelinepublic void openPipeline()Description copied from interface:RedisConnectionActivates the pipeline mode for this connection. When pipelined, all commands return null (the reply is read at the end throughRedisConnection.closePipeline(). Calling this method when the connection is already pipelined has no effect. Pipelining is used for issuing commands without requesting the response right away but rather at the end of the batch. While somewhat similar to MULTI, pipelining does not guarantee atomicity - it only tries to improve performance when issuing a lot of commands (such as in batching scenarios).Note: Consider doing some performance testing before using this feature since in many cases the performance benefits are minimal yet the impact on usage are not.- See Also:
 
- 
closePipelineDescription copied from interface:RedisConnectionExecutes the commands in the pipeline and returns their result. If the connection is not pipelined, an empty collection is returned.- Returns:
- the result of the executed commands.
 
- 
echopublic byte[] echo(byte[] message) Description copied from interface:RedisConnectionCommandsReturnsmessagevia server roundtrip.- Parameters:
- message- the message to echo.
- Returns:
- the message or null when used in pipeline / transaction.
- See Also:
 
- 
pingDescription copied from interface:RedisConnectionCommandsTest connection.- Returns:
- Server response message - usually PONG. null when used in pipeline / transaction.
- See Also:
 
- 
discardpublic void discard()Description copied from interface:RedisTxCommandsDiscard all commands issued afterRedisTxCommands.multi().- See Also:
 
- 
execDescription copied from interface:RedisTxCommandsExecutes all queued commands in a transaction started withRedisTxCommands.multi().
 If used along withRedisTxCommands.watch(byte[]...)the operation will fail if any of watched keys has been modified.- Returns:
- List of replies for each executed command.
- See Also:
 
- 
multipublic void multi()Description copied from interface:RedisTxCommandsMark the start of a transaction block.
 Commands will be queued and can then be executed by callingRedisTxCommands.exec()or rolled back usingRedisTxCommands.discard()- See Also:
 
- 
selectpublic void select(int dbIndex) Description copied from interface:RedisConnectionCommandsSelect the DB with given positivedbIndex.- Parameters:
- dbIndex- the database index.
- See Also:
 
- 
unwatchpublic void unwatch()Description copied from interface:RedisTxCommandsFlushes all the previouslyRedisTxCommands.watch(byte[]...)keys.- See Also:
 
- 
watchpublic void watch(byte[]... keys) Description copied from interface:RedisTxCommandsWatch givenkeysfor modifications during transaction started withRedisTxCommands.multi().- Parameters:
- keys- must not be null.
- See Also:
 
- 
publishDescription copied from interface:RedisPubSubCommandsPublishes the given message to the given channel.- Parameters:
- channel- the channel to publish to. Must not be null.
- message- message to publish. Must not be null.
- Returns:
- the number of clients that received the message or null when used in pipeline / transaction.
- See Also:
 
- 
getSubscriptionDescription copied from interface:RedisPubSubCommandsReturns the current subscription for this connection or null if the connection is not subscribed.- Returns:
- the current subscription, null if none is available.
 
- 
isSubscribedpublic boolean isSubscribed()Description copied from interface:RedisPubSubCommandsIndicates whether the current connection is subscribed (to at least one channel) or not.- Returns:
- true if the connection is subscribed, false otherwise
 
- 
pSubscribeDescription copied from interface:RedisPubSubCommandsSubscribes the connection to all channels matching the given patterns. Once subscribed, a connection enters listening mode and can only subscribe to other channels or unsubscribe. No other commands are accepted until the connection is unsubscribed.Note that this operation is blocking and the current thread starts waiting for new messages immediately. - Parameters:
- listener- message listener, must not be null.
- patterns- channel name patterns, must not be null.
- See Also:
 
- 
subscribeDescription copied from interface:RedisPubSubCommandsSubscribes the connection to the given channels. Once subscribed, a connection enters listening mode and can only subscribe to other channels or unsubscribe. No other commands are accepted until the connection is unsubscribed.Note that this operation is blocking and the current thread starts waiting for new messages immediately. - Parameters:
- listener- message listener, must not be null.
- channels- channel names, must not be null.
- See Also:
 
- 
setConvertPipelineAndTxResultspublic void setConvertPipelineAndTxResults(boolean convertPipelineAndTxResults) Specifies if pipelined and transaction results should be converted to the expected data type. If false, results ofclosePipeline()andexec()will be of the type returned by the Lettuce driver- Parameters:
- convertPipelineAndTxResults- Whether or not to convert pipeline and tx results
 
- 
setPipeliningFlushPolicyConfigures the flushing policy when using pipelining.- Parameters:
- pipeliningFlushPolicy- the flushing policy to control when commands get written to the Redis connection.
- Since:
- 2.3
- See Also:
- 
- LettuceConnection.PipeliningFlushPolicy.flushEachCommand()
- openPipeline()
- StatefulConnection.flushCommands()
 
 
- 
switchToPubSubprotected io.lettuce.core.pubsub.StatefulRedisPubSubConnection<byte[],byte[]> switchToPubSub()close()the current connection and open a new pub/sub connection to the Redis server.- Returns:
- never null.
 
- 
doCreateSubscriptionprotected LettuceSubscription doCreateSubscription(MessageListener listener, io.lettuce.core.pubsub.StatefulRedisPubSubConnection<byte[], byte[]> connection, LettuceConnectionProvider connectionProvider) Customization hook to create aLettuceSubscription.- Parameters:
- listener- the- MessageListenerto notify.
- connection- Pub/Sub connection.
- connectionProvider- the- LettuceConnectionProviderfor connection release.
- Returns:
- a LettuceSubscription.
- Since:
- 2.2
 
- 
getConnectionprotected io.lettuce.core.cluster.api.sync.RedisClusterCommands<byte[],byte[]> getConnection()
- 
getAsyncDedicatedConnectionprotected io.lettuce.core.cluster.api.async.RedisClusterAsyncCommands<byte[],byte[]> getAsyncDedicatedConnection()
- 
doGetAsyncDedicatedConnectionprotected io.lettuce.core.api.StatefulConnection<byte[],byte[]> doGetAsyncDedicatedConnection()
- 
isActiveDescription copied from class:AbstractRedisConnectionCheck if node is active by sending ping.- Overrides:
- isActivein class- AbstractRedisConnection
- Returns:
 
- 
getSentinelConnectionDescription copied from class:AbstractRedisConnectionGetRedisSentinelCommandsconnected to given node.- Overrides:
- getSentinelConnectionin class- AbstractRedisConnection
- Returns:
 
 
-