From 61197d626e312133d1de28c02ff05d6ce5edce0f Mon Sep 17 00:00:00 2001 From: M Sazzadul Hoque <7600764+sazzad16@users.noreply.github.com> Date: Sat, 4 Dec 2021 12:55:33 +0600 Subject: [PATCH] Jedis 4 --- pom.xml | 14 +- .../redis/clients/jedis/BinaryClient.java | 2099 ----- .../java/redis/clients/jedis/BinaryJedis.java | 5061 ------------ .../clients/jedis/BinaryJedisCluster.java | 2909 ------- .../clients/jedis/BinaryJedisPubSub.java | 49 +- .../clients/jedis/BinaryShardedJedis.java | 1334 ---- src/main/java/redis/clients/jedis/BitOP.java | 11 - .../redis/clients/jedis/BitPosParams.java | 27 - .../java/redis/clients/jedis/Builder.java | 1 + .../redis/clients/jedis/BuilderFactory.java | 505 +- src/main/java/redis/clients/jedis/Client.java | 1722 ---- .../jedis/ClusterCommandArguments.java | 40 + .../clients/jedis/ClusterCommandObjects.java | 210 + .../redis/clients/jedis/ClusterPipeline.java | 23 + .../redis/clients/jedis/ClusterReset.java | 11 - .../redis/clients/jedis/CommandArguments.java | 141 + .../redis/clients/jedis/CommandObject.java | 20 + .../redis/clients/jedis/CommandObjects.java | 2852 +++++++ .../java/redis/clients/jedis/Connection.java | 266 +- .../clients/jedis/ConnectionFactory.java | 107 + .../redis/clients/jedis/ConnectionPool.java | 32 + .../clients/jedis/ConnectionPoolConfig.java | 14 + .../java/redis/clients/jedis/DebugParams.java | 31 - .../jedis/DefaultJedisClientConfig.java | 15 + .../jedis/DefaultJedisSocketFactory.java | 183 +- .../redis/clients/jedis/GeoCoordinate.java | 1 + .../java/redis/clients/jedis/GeoUnit.java | 13 - .../java/redis/clients/jedis/HostAndPort.java | 115 +- src/main/java/redis/clients/jedis/Jedis.java | 6904 +++++++++++++---- .../redis/clients/jedis/JedisCluster.java | 2929 +------ .../clients/jedis/JedisClusterCommand.java | 222 - .../jedis/JedisClusterConnectionHandler.java | 87 - .../clients/jedis/JedisClusterInfoCache.java | 160 +- .../redis/clients/jedis/JedisFactory.java | 31 +- .../redis/clients/jedis/JedisMonitor.java | 7 +- .../java/redis/clients/jedis/JedisPool.java | 12 +- .../redis/clients/jedis/JedisPoolConfig.java | 1 + .../java/redis/clients/jedis/JedisPooled.java | 380 + .../java/redis/clients/jedis/JedisPubSub.java | 50 +- .../clients/jedis/JedisSentinelPool.java | 11 +- .../redis/clients/jedis/JedisShardInfo.java | 266 - .../redis/clients/jedis/JedisSharding.java | 42 + .../JedisSlotBasedConnectionHandler.java | 112 - .../clients/jedis/JedisSocketFactory.java | 33 - .../redis/clients/jedis/ListPosition.java | 12 - .../clients/jedis/MultiKeyPipelineBase.java | 1022 --- .../clients/jedis/MultiNodePipelineBase.java | 3008 +++++++ .../java/redis/clients/jedis/Pipeline.java | 3073 +++++++- .../redis/clients/jedis/PipelineBase.java | 2459 ------ .../java/redis/clients/jedis/Protocol.java | 229 +- .../java/redis/clients/jedis/Queable.java | 21 +- .../clients/jedis/ReliableTransaction.java | 53 + .../java/redis/clients/jedis/Response.java | 4 +- .../java/redis/clients/jedis/Sentinel.java | 405 + .../jedis/ShardedCommandArguments.java | 59 + .../clients/jedis/ShardedCommandObjects.java | 112 + .../redis/clients/jedis/ShardedJedis.java | 1319 ---- .../redis/clients/jedis/ShardedJedisPool.java | 128 - .../redis/clients/jedis/ShardedPipeline.java | 29 + .../java/redis/clients/jedis/Transaction.java | 110 +- .../redis/clients/jedis/TransactionBase.java | 3078 ++++++++ .../redis/clients/jedis/UnifiedJedis.java | 3235 ++++++++ .../java/redis/clients/jedis/args/BitOP.java | 19 + .../redis/clients/jedis/args/FlushMode.java | 2 +- .../redis/clients/jedis/args/GeoUnit.java | 20 + .../clients/jedis/args/ListDirection.java | 5 +- .../clients/jedis/args/ListPosition.java | 19 + .../clients/jedis/args/RawableFactory.java | 39 + .../redis/clients/jedis/args/UnblockType.java | 3 +- .../clients/jedis/args/package-info.java | 2 +- .../AccessControlLogBinaryCommands.java | 154 + .../commands/AccessControlLogCommands.java | 156 + .../commands/AdvancedBinaryJedisCommands.java | 121 - .../jedis/commands/AdvancedJedisCommands.java | 115 - .../jedis/commands/BasicRedisPipeline.java | 58 - .../commands/BinaryJedisClusterCommands.java | 49 - .../jedis/commands/BinaryJedisCommands.java | 495 -- .../jedis/commands/BinaryRedisPipeline.java | 456 -- .../commands/BinaryScriptingCommands.java | 37 - .../BinaryScriptingCommandsPipeline.java | 9 +- .../jedis/commands/ClientBinaryCommands.java | 38 + .../jedis/commands/ClientCommands.java | 38 + .../jedis/commands/ClusterCommands.java | 14 +- .../jedis/commands/ClusterPipeline.java | 25 - .../clients/jedis/commands/Commands.java | 590 -- .../jedis/commands/ConfigCommands.java | 19 + .../jedis/commands/ControlBinaryCommands.java | 25 + .../jedis/commands/ControlCommands.java | 25 + .../jedis/commands/DatabaseCommands.java | 56 + .../commands/GenericControlCommands.java | 16 + .../jedis/commands/GeoBinaryCommands.java | 57 + .../clients/jedis/commands/GeoCommands.java | 57 + .../commands/GeoPipelineBinaryCommands.java | 58 + .../jedis/commands/GeoPipelineCommands.java | 58 + .../jedis/commands/HashBinaryCommands.java | 54 + .../clients/jedis/commands/HashCommands.java | 53 + .../commands/HashPipelineBinaryCommands.java | 55 + .../jedis/commands/HashPipelineCommands.java | 54 + .../commands/HyperLogLogBinaryCommands.java | 13 + .../jedis/commands/HyperLogLogCommands.java | 13 + .../HyperLogLogPipelineBinaryCommands.java | 15 + .../commands/HyperLogLogPipelineCommands.java | 15 + .../jedis/commands/JedisBinaryCommands.java | 6 + .../JedisClusterBinaryScriptingCommands.java | 64 - .../jedis/commands/JedisClusterCommands.java | 16 - .../JedisClusterScriptingCommands.java | 60 - .../clients/jedis/commands/JedisCommands.java | 704 +- .../jedis/commands/KeyBinaryCommands.java | 92 + .../clients/jedis/commands/KeyCommands.java | 92 + .../commands/KeyPipelineBinaryCommands.java | 93 + .../jedis/commands/KeyPipelineCommands.java | 93 + .../jedis/commands/ListBinaryCommands.java | 63 + .../clients/jedis/commands/ListCommands.java | 72 + .../commands/ListPipelineBinaryCommands.java | 64 + .../jedis/commands/ListPipelineCommands.java | 73 + .../jedis/commands/ModuleCommands.java | 3 +- .../commands/MultiKeyBinaryCommands.java | 166 - .../MultiKeyBinaryJedisClusterCommands.java | 65 - .../commands/MultiKeyBinaryRedisPipeline.java | 146 - .../jedis/commands/MultiKeyCommands.java | 263 - .../commands/MultiKeyCommandsPipeline.java | 154 - .../MultiKeyJedisClusterCommands.java | 62 - .../commands/PipelineBinaryCommands.java | 8 + .../jedis/commands/PipelineCommands.java | 7 + .../jedis/commands/RedisModuleCommands.java | 7 + .../commands/RedisModulePipelineCommands.java | 7 + .../clients/jedis/commands/RedisPipeline.java | 473 -- .../commands/SampleBinaryKeyedCommands.java | 25 + .../SampleBinaryKeyedPipelineCommands.java | 26 + .../jedis/commands/SampleKeyedCommands.java | 25 + .../commands/SampleKeyedPipelineCommands.java | 26 + .../commands/ScriptingCommandsPipeline.java | 4 +- .../commands/ScriptingControlCommands.java | 26 + .../commands/ScriptingKeyBinaryCommands.java | 18 + ...ommands.java => ScriptingKeyCommands.java} | 15 +- .../ScriptingKeyPipelineBinaryCommands.java | 19 + .../ScriptingKeyPipelineCommands.java | 19 + .../jedis/commands/SentinelCommands.java | 1 + ...BasicCommands.java => ServerCommands.java} | 54 +- .../jedis/commands/SetBinaryCommands.java | 51 + .../clients/jedis/commands/SetCommands.java | 51 + .../commands/SetPipelineBinaryCommands.java | 52 + .../jedis/commands/SetPipelineCommands.java | 52 + .../jedis/commands/SlowlogCommands.java | 20 + .../commands/SortedSetBinaryCommands.java | 150 + .../jedis/commands/SortedSetCommands.java | 151 + .../SortedSetPipelineBinaryCommands.java | 151 + .../commands/SortedSetPipelineCommands.java | 152 + .../jedis/commands/StreamBinaryCommands.java | 69 + .../jedis/commands/StreamCommands.java | 287 + .../StreamPipelineBinaryCommands.java | 72 + .../commands/StreamPipelineCommands.java | 288 + .../jedis/commands/StringBinaryCommands.java | 77 + .../jedis/commands/StringCommands.java | 78 + .../StringPipelineBinaryCommands.java | 78 + .../commands/StringPipelineCommands.java | 79 + .../jedis/exceptions/InvalidURIException.java | 1 - .../exceptions/JedisAskDataException.java | 2 +- .../jedis/exceptions/JedisBusyException.java | 1 - .../exceptions/JedisClusterException.java | 1 + .../JedisClusterMaxAttemptsException.java | 23 - .../JedisClusterOperationException.java | 3 +- .../exceptions/JedisConnectionException.java | 1 + .../jedis/exceptions/JedisDataException.java | 1 + .../jedis/exceptions/JedisException.java | 1 + .../JedisExhaustedPoolException.java | 20 - .../exceptions/JedisMovedDataException.java | 1 + .../JedisNoReachableClusterNodeException.java | 22 - .../exceptions/JedisNoScriptException.java | 1 + .../exceptions/JedisRedirectionException.java | 5 +- .../executors/ClusterCommandExecutor.java | 155 + .../jedis/executors/CommandExecutor.java | 8 + .../executors/DefaultCommandExecutor.java | 27 + .../executors/RetryableCommandExecutor.java | 113 + .../executors/SimpleCommandExecutor.java | 24 + .../clients/jedis/json/JsonProtocol.java | 36 + .../clients/jedis/json/JsonSetParams.java | 39 + .../java/redis/clients/jedis/json/Path.java | 43 + .../java/redis/clients/jedis/json/Path2.java | 55 + .../clients/jedis/json/RedisJsonCommands.java | 144 + .../jedis/json/RedisJsonPipelineCommands.java | 149 + .../clients/jedis/json/package-info.java | 4 + .../clients/jedis/params/BitPosParams.java | 30 + .../clients/jedis/params/FailoverParams.java | 22 +- .../clients/jedis/params/GeoAddParams.java | 44 +- .../clients/jedis/params/GeoRadiusParam.java | 70 +- .../jedis/params/GeoRadiusStoreParam.java | 100 +- .../clients/jedis/params/GetExParams.java | 34 +- .../redis/clients/jedis/params/IParams.java | 8 + .../clients/jedis/params/LPosParams.java | 23 +- .../clients/jedis/params/MigrateParams.java | 53 +- .../clients/jedis/params/RestoreParams.java | 27 +- .../jedis/{ => params}/ScanParams.java | 35 +- .../redis/clients/jedis/params/SetParams.java | 40 +- .../jedis/{ => params}/SortingParams.java | 13 +- .../jedis/params/StrAlgoLCSParams.java | 30 +- .../clients/jedis/params/XAddParams.java | 42 +- .../jedis/params/XAutoClaimParams.java | 18 +- .../clients/jedis/params/XClaimParams.java | 41 +- .../clients/jedis/params/XPendingParams.java | 26 +- .../jedis/params/XReadGroupParams.java | 37 +- .../clients/jedis/params/XReadParams.java | 29 +- .../clients/jedis/params/XTrimParams.java | 42 +- .../clients/jedis/params/ZAddParams.java | 27 +- .../clients/jedis/params/ZIncrByParams.java | 22 +- .../clients/jedis/{ => params}/ZParams.java | 18 +- .../clients/jedis/params/package-info.java | 4 + .../providers/ClusterConnectionProvider.java | 136 + .../jedis/providers/ConnectionProvider.java | 11 + .../providers/ManagedConnectionProvider.java | 27 + .../providers/PooledConnectionProvider.java | 56 + .../providers/ShardedConnectionProvider.java | 160 + .../{ => resps}/AccessControlLogEntry.java | 2 +- .../jedis/{ => resps}/AccessControlUser.java | 2 +- .../jedis/{ => resps}/GeoRadiusResponse.java | 3 +- .../clients/jedis/resps/KeyedZSetElement.java | 1 - .../clients/jedis/{ => resps}/ScanResult.java | 3 +- .../jedis/{util => resps}/Slowlog.java | 3 +- .../{ => resps}/StreamConsumersInfo.java | 2 +- .../jedis/{ => resps}/StreamEntry.java | 3 +- .../jedis/{ => resps}/StreamGroupInfo.java | 3 +- .../clients/jedis/{ => resps}/StreamInfo.java | 3 +- .../jedis/{ => resps}/StreamPendingEntry.java | 3 +- .../{ => resps}/StreamPendingSummary.java | 3 +- .../clients/jedis/{ => resps}/Tuple.java | 2 +- .../redis/clients/jedis/search/Document.java | 134 + .../redis/clients/jedis/search/FieldName.java | 93 + .../clients/jedis/search/IndexDefinition.java | 160 + .../clients/jedis/search/IndexOptions.java | 129 + .../redis/clients/jedis/search/Query.java | 522 ++ .../jedis/search/RediSearchCommands.java | 55 + .../search/RediSearchPipelineCommands.java | 12 + .../clients/jedis/search/RediSearchUtil.java | 36 + .../redis/clients/jedis/search/Schema.java | 276 + .../clients/jedis/search/SearchProtocol.java | 62 + .../clients/jedis/search/SearchResult.java | 84 + .../jedis/search/aggr/AggregationBuilder.java | 146 + .../jedis/search/aggr/AggregationResult.java | 58 + .../clients/jedis/search/aggr/Group.java | 51 + .../clients/jedis/search/aggr/Limit.java | 39 + .../clients/jedis/search/aggr/Reducer.java | 71 + .../clients/jedis/search/aggr/Reducers.java | 122 + .../redis/clients/jedis/search/aggr/Row.java | 42 + .../jedis/search/aggr/SortedField.java | 35 + .../jedis/search/aggr/package-info.java | 4 + .../clients/jedis/search/package-info.java | 4 + .../redis/clients/jedis/util/IOUtils.java | 17 +- .../clients/jedis/util/JedisClusterCRC16.java | 2 +- ...hTagUtil.java => JedisClusterHashTag.java} | 4 +- .../clients/jedis/util/JedisURIHelper.java | 5 + .../clients/jedis/util/KeyMergeUtil.java | 21 - .../java/redis/clients/jedis/util/Pool.java | 49 +- .../clients/jedis/util/RedisInputStream.java | 1 - .../redis/clients/jedis/util/SafeEncoder.java | 12 +- .../redis/clients/jedis/util/ShardInfo.java | 20 - .../redis/clients/jedis/util/Sharded.java | 109 - ...entialsTest.java => ACLJedisPoolTest.java} | 18 +- ...est.java => ACLJedisSentinelPoolTest.java} | 20 +- ...CredentialsTest.java => ACLJedisTest.java} | 31 +- ...ilderFactoryTest.java => BuilderTest.java} | 7 +- .../redis/clients/jedis/ConnectionTest.java | 43 + .../redis/clients/jedis/HostAndPortTest.java | 23 + ...HostAndPortUtil.java => HostAndPorts.java} | 28 +- .../jedis/JedisClusterCommandTest.java | 371 + .../jedis/JedisClusterPipelineTest.java | 461 ++ .../jedis/{tests => }/JedisClusterTest.java | 212 +- .../jedis/{tests => }/JedisPoolTest.java | 21 +- .../redis/clients/jedis/JedisPooledTest.java | 173 + .../{tests => }/JedisSentinelPoolTest.java | 34 +- .../jedis/{tests => }/JedisSentinelTest.java | 37 +- .../clients/jedis/{tests => }/JedisTest.java | 53 +- .../jedis/ManagedConnectionProviderTest.java | 38 + .../clients/jedis/{tests => }/ModuleTest.java | 8 +- .../jedis/{tests => }/PipeliningTest.java | 696 +- .../jedis/{tests => }/ProtocolTest.java | 9 +- .../jedis/ReliableTransactionTest.java | 279 + ...sTest.java => SSLACLJedisClusterTest.java} | 32 +- .../redis/clients/jedis/SSLACLJedisTest.java | 168 + .../{tests => }/SSLJedisClusterTest.java | 42 +- .../{tests => }/SSLJedisSentinelPoolTest.java | 10 +- .../redis/clients/jedis/SSLJedisTest.java | 173 + .../clients/jedis/ShardedConnectionTest.java | 101 + .../redis/clients/jedis/ShardingTest.java | 153 + .../clients/jedis/TransactionV2Test.java | 278 + .../clients/jedis/TupleSortedSetTest.java | 84 + .../clients/jedis/{tests => }/TupleTest.java | 4 +- .../java/redis/clients/jedis/UdsTest.java | 43 + .../UnavailableConnectionTest.java | 7 +- .../{tests => }/benchmark/CRC16Benchmark.java | 10 +- .../benchmark/GetSetBenchmark.java | 9 +- .../HashingBenchmark.java} | 8 +- .../benchmark/PipelinedGetSetBenchmark.java | 9 +- .../{tests => }/benchmark/PoolBenchmark.java | 13 +- .../jedis/benchmark/PooledBenchmark.java | 59 + .../benchmark/ProtocolBenchmark.java | 15 +- .../benchmark/SafeEncoderBenchmark.java | 5 +- .../jedis/benchmark/ShardedBenchmark.java | 50 + .../jedis/benchmark/ShardingBenchmark.java | 36 + .../collections/JedisByteHashMapTest.java | 2 +- .../collections/SetFromListTest.java | 5 +- .../jedis}/AccessControlListCommandsTest.java | 39 +- .../jedis}/AllKindOfValuesCommandsTest.java | 93 +- .../jedis}/BinaryValuesCommandsTest.java | 48 +- .../jedis}/BitCommandsTest.java | 11 +- .../jedis}/ClientCommandsTest.java | 23 +- .../ClusterBinaryValuesCommandsTest.java | 2 +- .../jedis}/ClusterCommandsTest.java | 28 +- .../jedis}/ClusterJedisCommandsTestBase.java | 35 +- .../jedis}/ClusterScriptingCommandsTest.java | 8 +- .../jedis}/ClusterValuesCommandsTest.java | 3 +- .../jedis/ConnectionHandlingCommandsTest.java | 20 + .../jedis}/ControlCommandsTest.java | 38 +- .../jedis}/FailoverCommandsTest.java | 10 +- .../jedis}/GeoCommandsTest.java | 32 +- .../jedis}/HashesCommandsTest.java | 19 +- .../jedis}/HyperLogLogCommandsTest.java | 4 +- .../commands/jedis/JedisCommandsTestBase.java | 35 + .../jedis}/ListCommandsTest.java | 8 +- .../jedis}/MigrateTest.java | 4 +- .../jedis}/ObjectCommandsTest.java | 8 +- .../jedis}/PublishSubscribeCommandsTest.java | 14 +- .../jedis}/ScriptingCommandsTest.java | 28 +- .../jedis}/SentinelCommandsTest.java | 24 +- .../jedis}/SetCommandsTest.java | 33 +- .../jedis}/SlowlogCommandsTest.java | 9 +- .../jedis}/SortedSetCommandsTest.java | 269 +- .../jedis}/SortingCommandsTest.java | 8 +- .../jedis}/StreamsCommandsTest.java | 274 +- .../jedis}/StringValuesCommandsTest.java | 13 +- .../jedis}/TransactionCommandsTest.java | 170 +- .../jedis}/VariadicCommandsTest.java | 18 +- .../AllKindOfValuesCommandsTestBase.java | 801 ++ .../unified/BinaryValuesCommandsTestBase.java | 363 + .../commands/unified/BitCommandsTestBase.java | 258 + .../commands/unified/GeoCommandsTestBase.java | 483 ++ .../unified/HashesCommandsTestBase.java | 463 ++ .../unified/HyperLogLogCommandsTestBase.java | 131 + .../unified/ListCommandsTestBase.java | 866 +++ .../commands/unified/SetCommandsTestBase.java | 607 ++ .../unified/SortedSetCommandsTestBase.java | 1540 ++++ .../unified/StringValuesCommandsTestBase.java | 318 + .../unified/UnifiedJedisCommandsTestBase.java | 11 + .../ClusterAllKindOfValuesCommandsTest.java | 266 + .../ClusterBinaryValuesCommandsTest.java | 45 + .../cluster/ClusterBitCommandsTest.java | 78 + .../cluster/ClusterCommandsTestHelper.java | 82 + .../cluster/ClusterGeoCommandsTest.java | 89 + .../cluster/ClusterHashesCommandsTest.java | 29 + .../ClusterHyperLogLogCommandsTest.java | 78 + .../cluster/ClusterListCommandsTest.java | 266 + .../cluster/ClusterSetCommandsTest.java | 175 + .../cluster/ClusterSortedSetCommandsTest.java | 190 + .../ClusterStringValuesCommandsTest.java | 85 + .../PooledAllKindOfValuesCommandsTest.java | 24 + .../PooledBinaryValuesCommandsTest.java | 24 + .../unified/pooled/PooledBitCommandsTest.java | 24 + .../pooled/PooledCommandsTestHelper.java | 26 + .../unified/pooled/PooledGeoCommandsTest.java | 24 + .../pooled/PooledHashesCommandsTest.java | 24 + .../pooled/PooledHyperLogLogCommandsTest.java | 24 + .../pooled/PooledListCommandsTest.java | 24 + .../unified/pooled/PooledSetCommandsTest.java | 24 + .../pooled/PooledSortedSetCommandsTest.java | 24 + .../PooledStringValuesCommandsTest.java | 24 + .../{tests => exceptions}/ExceptionsTest.java | 85 +- .../FailoverAbortedException.java | 2 +- .../modules/RedisModuleCommandsTestBase.java | 56 + .../clients/jedis/modules/json/Path2Test.java | 43 + .../clients/jedis/modules/json/PathTest.java | 36 + .../jedis/modules/json/RedisJsonV1Test.java | 516 ++ .../jedis/modules/json/RedisJsonV2Test.java | 535 ++ .../search/AggregationBuilderTest.java | 244 + .../jedis/modules/search/CreateTest.java | 70 + .../jedis/modules/search/DocumentTest.java | 49 + .../jedis/modules/search/JsonSearchTest.java | 225 + .../jedis/modules/search/QueryTest.java | 153 + .../jedis/modules/search/SchemaTest.java | 31 + .../jedis/modules/search/SearchTest.java | 1300 ++++ .../jedis/{tests => }/params/ParamsTest.java | 7 +- .../clients/jedis/tests/ConnectionTest.java | 88 - .../clients/jedis/tests/HostAndPortTest.java | 57 - .../jedis/tests/JedisClusterCommandTest.java | 371 - .../clients/jedis/tests/KeyMergeUtilTest.java | 42 - .../clients/jedis/tests/SSLJedisTest.java | 326 - .../SSLJedisWithCompleteCredentialsTest.java | 324 - .../jedis/tests/ShardedJedisPoolTest.java | 258 - ...dJedisPoolWithCompleteCredentialsTest.java | 274 - .../clients/jedis/tests/ShardedJedisTest.java | 361 - .../jedis/tests/TupleSortedSetTest.java | 80 - .../redis/clients/jedis/tests/UdsTest.java | 88 - .../tests/benchmark/HashingBenchmark.java | 49 - .../ConnectionHandlingCommandsTest.java | 26 - .../tests/commands/JedisCommandTestBase.java | 38 - .../jedis/tests/utils/KeyMergeUtilTest.java | 25 - .../{tests/utils => util}/AssertUtil.java | 5 +- .../ByteArrayComparatorTest.java | 5 +- .../{tests/utils => util}/ByteArrayUtil.java | 2 +- .../utils => util}/ClientKillerUtil.java | 7 +- .../FragmentedByteArrayInputStream.java | 2 +- .../utils => util}/JedisClusterCRC16Test.java | 6 +- .../utils => util}/JedisClusterTestUtil.java | 2 +- .../utils => util}/JedisSentinelTestUtil.java | 8 +- .../utils => util}/JedisURIHelperTest.java | 5 +- .../utils => util}/RedisVersionUtil.java | 6 +- 404 files changed, 45276 insertions(+), 33225 deletions(-) delete mode 100644 src/main/java/redis/clients/jedis/BinaryClient.java delete mode 100644 src/main/java/redis/clients/jedis/BinaryJedis.java delete mode 100644 src/main/java/redis/clients/jedis/BinaryJedisCluster.java delete mode 100644 src/main/java/redis/clients/jedis/BinaryShardedJedis.java delete mode 100644 src/main/java/redis/clients/jedis/BitOP.java delete mode 100644 src/main/java/redis/clients/jedis/BitPosParams.java delete mode 100644 src/main/java/redis/clients/jedis/Client.java create mode 100644 src/main/java/redis/clients/jedis/ClusterCommandArguments.java create mode 100644 src/main/java/redis/clients/jedis/ClusterCommandObjects.java create mode 100644 src/main/java/redis/clients/jedis/ClusterPipeline.java delete mode 100644 src/main/java/redis/clients/jedis/ClusterReset.java create mode 100644 src/main/java/redis/clients/jedis/CommandArguments.java create mode 100644 src/main/java/redis/clients/jedis/CommandObject.java create mode 100644 src/main/java/redis/clients/jedis/CommandObjects.java create mode 100644 src/main/java/redis/clients/jedis/ConnectionFactory.java create mode 100644 src/main/java/redis/clients/jedis/ConnectionPool.java create mode 100644 src/main/java/redis/clients/jedis/ConnectionPoolConfig.java delete mode 100644 src/main/java/redis/clients/jedis/DebugParams.java delete mode 100644 src/main/java/redis/clients/jedis/GeoUnit.java delete mode 100644 src/main/java/redis/clients/jedis/JedisClusterCommand.java delete mode 100644 src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java create mode 100644 src/main/java/redis/clients/jedis/JedisPooled.java delete mode 100644 src/main/java/redis/clients/jedis/JedisShardInfo.java create mode 100644 src/main/java/redis/clients/jedis/JedisSharding.java delete mode 100644 src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java delete mode 100644 src/main/java/redis/clients/jedis/ListPosition.java delete mode 100644 src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java create mode 100644 src/main/java/redis/clients/jedis/MultiNodePipelineBase.java delete mode 100644 src/main/java/redis/clients/jedis/PipelineBase.java create mode 100644 src/main/java/redis/clients/jedis/ReliableTransaction.java create mode 100644 src/main/java/redis/clients/jedis/Sentinel.java create mode 100644 src/main/java/redis/clients/jedis/ShardedCommandArguments.java create mode 100644 src/main/java/redis/clients/jedis/ShardedCommandObjects.java delete mode 100644 src/main/java/redis/clients/jedis/ShardedJedis.java delete mode 100644 src/main/java/redis/clients/jedis/ShardedJedisPool.java create mode 100644 src/main/java/redis/clients/jedis/ShardedPipeline.java create mode 100644 src/main/java/redis/clients/jedis/TransactionBase.java create mode 100644 src/main/java/redis/clients/jedis/UnifiedJedis.java create mode 100644 src/main/java/redis/clients/jedis/args/BitOP.java create mode 100644 src/main/java/redis/clients/jedis/args/GeoUnit.java create mode 100644 src/main/java/redis/clients/jedis/args/ListPosition.java create mode 100644 src/main/java/redis/clients/jedis/args/RawableFactory.java create mode 100644 src/main/java/redis/clients/jedis/commands/AccessControlLogBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/AccessControlLogCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/AdvancedJedisCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/BasicRedisPipeline.java delete mode 100644 src/main/java/redis/clients/jedis/commands/BinaryJedisClusterCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/BinaryJedisCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/BinaryRedisPipeline.java delete mode 100644 src/main/java/redis/clients/jedis/commands/BinaryScriptingCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ClientBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ClientCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/ClusterPipeline.java delete mode 100644 src/main/java/redis/clients/jedis/commands/Commands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ConfigCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ControlBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ControlCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/DatabaseCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/GenericControlCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/GeoBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/GeoCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/GeoPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/GeoPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HashBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HashCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HashPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HashPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HyperLogLogBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HyperLogLogCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/JedisBinaryCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/JedisClusterCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/JedisClusterScriptingCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/KeyBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/KeyCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/KeyPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/KeyPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ListBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ListCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ListPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ListPipelineCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/MultiKeyBinaryCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java delete mode 100644 src/main/java/redis/clients/jedis/commands/MultiKeyCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java delete mode 100644 src/main/java/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/PipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/PipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/RedisModuleCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/RedisModulePipelineCommands.java delete mode 100644 src/main/java/redis/clients/jedis/commands/RedisPipeline.java create mode 100644 src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SampleKeyedCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SampleKeyedPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ScriptingControlCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ScriptingKeyBinaryCommands.java rename src/main/java/redis/clients/jedis/commands/{ScriptingCommands.java => ScriptingKeyCommands.java} (71%) create mode 100644 src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineCommands.java rename src/main/java/redis/clients/jedis/commands/{BasicCommands.java => ServerCommands.java} (85%) create mode 100644 src/main/java/redis/clients/jedis/commands/SetBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SetCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SetPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SetPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SlowlogCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SortedSetBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SortedSetCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SortedSetPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/SortedSetPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StreamBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StreamCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StreamPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StreamPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StringCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java create mode 100644 src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java delete mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java delete mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java delete mode 100644 src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java create mode 100644 src/main/java/redis/clients/jedis/executors/ClusterCommandExecutor.java create mode 100644 src/main/java/redis/clients/jedis/executors/CommandExecutor.java create mode 100644 src/main/java/redis/clients/jedis/executors/DefaultCommandExecutor.java create mode 100644 src/main/java/redis/clients/jedis/executors/RetryableCommandExecutor.java create mode 100644 src/main/java/redis/clients/jedis/executors/SimpleCommandExecutor.java create mode 100644 src/main/java/redis/clients/jedis/json/JsonProtocol.java create mode 100644 src/main/java/redis/clients/jedis/json/JsonSetParams.java create mode 100644 src/main/java/redis/clients/jedis/json/Path.java create mode 100644 src/main/java/redis/clients/jedis/json/Path2.java create mode 100644 src/main/java/redis/clients/jedis/json/RedisJsonCommands.java create mode 100644 src/main/java/redis/clients/jedis/json/RedisJsonPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/json/package-info.java create mode 100644 src/main/java/redis/clients/jedis/params/BitPosParams.java create mode 100644 src/main/java/redis/clients/jedis/params/IParams.java rename src/main/java/redis/clients/jedis/{ => params}/ScanParams.java (72%) rename src/main/java/redis/clients/jedis/{ => params}/SortingParams.java (94%) rename src/main/java/redis/clients/jedis/{ => params}/ZParams.java (79%) create mode 100644 src/main/java/redis/clients/jedis/params/package-info.java create mode 100644 src/main/java/redis/clients/jedis/providers/ClusterConnectionProvider.java create mode 100644 src/main/java/redis/clients/jedis/providers/ConnectionProvider.java create mode 100644 src/main/java/redis/clients/jedis/providers/ManagedConnectionProvider.java create mode 100644 src/main/java/redis/clients/jedis/providers/PooledConnectionProvider.java create mode 100644 src/main/java/redis/clients/jedis/providers/ShardedConnectionProvider.java rename src/main/java/redis/clients/jedis/{ => resps}/AccessControlLogEntry.java (98%) rename src/main/java/redis/clients/jedis/{ => resps}/AccessControlUser.java (96%) rename src/main/java/redis/clients/jedis/{ => resps}/GeoRadiusResponse.java (91%) rename src/main/java/redis/clients/jedis/{ => resps}/ScanResult.java (92%) rename src/main/java/redis/clients/jedis/{util => resps}/Slowlog.java (95%) rename src/main/java/redis/clients/jedis/{ => resps}/StreamConsumersInfo.java (97%) rename src/main/java/redis/clients/jedis/{ => resps}/StreamEntry.java (92%) rename src/main/java/redis/clients/jedis/{ => resps}/StreamGroupInfo.java (95%) rename src/main/java/redis/clients/jedis/{ => resps}/StreamInfo.java (96%) rename src/main/java/redis/clients/jedis/{ => resps}/StreamPendingEntry.java (94%) rename src/main/java/redis/clients/jedis/{ => resps}/StreamPendingSummary.java (91%) rename src/main/java/redis/clients/jedis/{ => resps}/Tuple.java (98%) create mode 100644 src/main/java/redis/clients/jedis/search/Document.java create mode 100644 src/main/java/redis/clients/jedis/search/FieldName.java create mode 100644 src/main/java/redis/clients/jedis/search/IndexDefinition.java create mode 100644 src/main/java/redis/clients/jedis/search/IndexOptions.java create mode 100644 src/main/java/redis/clients/jedis/search/Query.java create mode 100644 src/main/java/redis/clients/jedis/search/RediSearchCommands.java create mode 100644 src/main/java/redis/clients/jedis/search/RediSearchPipelineCommands.java create mode 100644 src/main/java/redis/clients/jedis/search/RediSearchUtil.java create mode 100644 src/main/java/redis/clients/jedis/search/Schema.java create mode 100644 src/main/java/redis/clients/jedis/search/SearchProtocol.java create mode 100644 src/main/java/redis/clients/jedis/search/SearchResult.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/AggregationBuilder.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/AggregationResult.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/Group.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/Limit.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/Reducer.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/Reducers.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/Row.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/SortedField.java create mode 100644 src/main/java/redis/clients/jedis/search/aggr/package-info.java create mode 100644 src/main/java/redis/clients/jedis/search/package-info.java rename src/main/java/redis/clients/jedis/util/{JedisClusterHashTagUtil.java => JedisClusterHashTag.java} (92%) delete mode 100644 src/main/java/redis/clients/jedis/util/KeyMergeUtil.java delete mode 100644 src/main/java/redis/clients/jedis/util/ShardInfo.java delete mode 100644 src/main/java/redis/clients/jedis/util/Sharded.java rename src/test/java/redis/clients/jedis/{tests/JedisPoolWithCompleteCredentialsTest.java => ACLJedisPoolTest.java} (94%) rename src/test/java/redis/clients/jedis/{tests/JedisSentinelPoolWithCompleteCredentialsTest.java => ACLJedisSentinelPoolTest.java} (93%) rename src/test/java/redis/clients/jedis/{tests/JedisWithCompleteCredentialsTest.java => ACLJedisTest.java} (77%) rename src/test/java/redis/clients/jedis/{tests/BuilderFactoryTest.java => BuilderTest.java} (84%) create mode 100644 src/test/java/redis/clients/jedis/ConnectionTest.java create mode 100644 src/test/java/redis/clients/jedis/HostAndPortTest.java rename src/test/java/redis/clients/jedis/{tests/HostAndPortUtil.java => HostAndPorts.java} (82%) create mode 100644 src/test/java/redis/clients/jedis/JedisClusterCommandTest.java create mode 100644 src/test/java/redis/clients/jedis/JedisClusterPipelineTest.java rename src/test/java/redis/clients/jedis/{tests => }/JedisClusterTest.java (82%) rename src/test/java/redis/clients/jedis/{tests => }/JedisPoolTest.java (94%) create mode 100644 src/test/java/redis/clients/jedis/JedisPooledTest.java rename src/test/java/redis/clients/jedis/{tests => }/JedisSentinelPoolTest.java (86%) rename src/test/java/redis/clients/jedis/{tests => }/JedisSentinelTest.java (85%) rename src/test/java/redis/clients/jedis/{tests => }/JedisTest.java (82%) create mode 100644 src/test/java/redis/clients/jedis/ManagedConnectionProviderTest.java rename src/test/java/redis/clients/jedis/{tests => }/ModuleTest.java (83%) rename src/test/java/redis/clients/jedis/{tests => }/PipeliningTest.java (55%) rename src/test/java/redis/clients/jedis/{tests => }/ProtocolTest.java (92%) create mode 100644 src/test/java/redis/clients/jedis/ReliableTransactionTest.java rename src/test/java/redis/clients/jedis/{tests/SSLJedisClusterWithCompleteCredentialsTest.java => SSLACLJedisClusterTest.java} (90%) create mode 100644 src/test/java/redis/clients/jedis/SSLACLJedisTest.java rename src/test/java/redis/clients/jedis/{tests => }/SSLJedisClusterTest.java (87%) rename src/test/java/redis/clients/jedis/{tests => }/SSLJedisSentinelPoolTest.java (90%) create mode 100644 src/test/java/redis/clients/jedis/SSLJedisTest.java create mode 100644 src/test/java/redis/clients/jedis/ShardedConnectionTest.java create mode 100644 src/test/java/redis/clients/jedis/ShardingTest.java create mode 100644 src/test/java/redis/clients/jedis/TransactionV2Test.java create mode 100644 src/test/java/redis/clients/jedis/TupleSortedSetTest.java rename src/test/java/redis/clients/jedis/{tests => }/TupleTest.java (96%) create mode 100644 src/test/java/redis/clients/jedis/UdsTest.java rename src/test/java/redis/clients/jedis/{tests => }/UnavailableConnectionTest.java (91%) rename src/test/java/redis/clients/jedis/{tests => }/benchmark/CRC16Benchmark.java (72%) rename src/test/java/redis/clients/jedis/{tests => }/benchmark/GetSetBenchmark.java (82%) rename src/test/java/redis/clients/jedis/{tests/benchmark/ShardedBenchmark.java => benchmark/HashingBenchmark.java} (92%) rename src/test/java/redis/clients/jedis/{tests => }/benchmark/PipelinedGetSetBenchmark.java (84%) rename src/test/java/redis/clients/jedis/{tests => }/benchmark/PoolBenchmark.java (89%) create mode 100644 src/test/java/redis/clients/jedis/benchmark/PooledBenchmark.java rename src/test/java/redis/clients/jedis/{tests => }/benchmark/ProtocolBenchmark.java (91%) rename src/test/java/redis/clients/jedis/{tests => }/benchmark/SafeEncoderBenchmark.java (95%) create mode 100644 src/test/java/redis/clients/jedis/benchmark/ShardedBenchmark.java create mode 100644 src/test/java/redis/clients/jedis/benchmark/ShardingBenchmark.java rename src/test/java/redis/clients/jedis/{tests => }/collections/JedisByteHashMapTest.java (98%) rename src/test/java/redis/clients/jedis/{tests => }/collections/SetFromListTest.java (93%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/AccessControlListCommandsTest.java (94%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/AllKindOfValuesCommandsTest.java (91%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/BinaryValuesCommandsTest.java (85%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/BitCommandsTest.java (97%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ClientCommandsTest.java (92%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ClusterBinaryValuesCommandsTest.java (98%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ClusterCommandsTest.java (86%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ClusterJedisCommandsTestBase.java (68%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ClusterScriptingCommandsTest.java (93%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ClusterValuesCommandsTest.java (84%) create mode 100644 src/test/java/redis/clients/jedis/commands/jedis/ConnectionHandlingCommandsTest.java rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ControlCommandsTest.java (90%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/FailoverCommandsTest.java (93%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/GeoCommandsTest.java (95%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/HashesCommandsTest.java (96%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/HyperLogLogCommandsTest.java (96%) create mode 100644 src/test/java/redis/clients/jedis/commands/jedis/JedisCommandsTestBase.java rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ListCommandsTest.java (99%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/MigrateTest.java (98%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ObjectCommandsTest.java (91%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/PublishSubscribeCommandsTest.java (97%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/ScriptingCommandsTest.java (91%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/SentinelCommandsTest.java (60%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/SetCommandsTest.java (93%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/SlowlogCommandsTest.java (93%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/SortedSetCommandsTest.java (83%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/SortingCommandsTest.java (96%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/StreamsCommandsTest.java (72%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/StringValuesCommandsTest.java (94%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/TransactionCommandsTest.java (73%) rename src/test/java/redis/clients/jedis/{tests/commands => commands/jedis}/VariadicCommandsTest.java (89%) create mode 100644 src/test/java/redis/clients/jedis/commands/unified/AllKindOfValuesCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/BinaryValuesCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/BitCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/GeoCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/HashesCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/HyperLogLogCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/ListCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/SetCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/SortedSetCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/StringValuesCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/UnifiedJedisCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterAllKindOfValuesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBinaryValuesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBitCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterCommandsTestHelper.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterGeoCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHashesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHyperLogLogCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterListCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSetCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSortedSetCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterStringValuesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledAllKindOfValuesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBinaryValuesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBitCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledCommandsTestHelper.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledGeoCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHashesCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHyperLogLogCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledListCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSetCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSortedSetCommandsTest.java create mode 100644 src/test/java/redis/clients/jedis/commands/unified/pooled/PooledStringValuesCommandsTest.java rename src/test/java/redis/clients/jedis/{tests => exceptions}/ExceptionsTest.java (80%) rename src/test/java/redis/clients/jedis/{tests/utils => exceptions}/FailoverAbortedException.java (90%) create mode 100644 src/test/java/redis/clients/jedis/modules/RedisModuleCommandsTestBase.java create mode 100644 src/test/java/redis/clients/jedis/modules/json/Path2Test.java create mode 100644 src/test/java/redis/clients/jedis/modules/json/PathTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/json/RedisJsonV1Test.java create mode 100644 src/test/java/redis/clients/jedis/modules/json/RedisJsonV2Test.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/AggregationBuilderTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/CreateTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/DocumentTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/JsonSearchTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/QueryTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/SchemaTest.java create mode 100644 src/test/java/redis/clients/jedis/modules/search/SearchTest.java rename src/test/java/redis/clients/jedis/{tests => }/params/ParamsTest.java (81%) delete mode 100644 src/test/java/redis/clients/jedis/tests/ConnectionTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/HostAndPortTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/JedisClusterCommandTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/KeyMergeUtilTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/SSLJedisTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/ShardedJedisPoolWithCompleteCredentialsTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/TupleSortedSetTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/UdsTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java delete mode 100644 src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java delete mode 100644 src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java delete mode 100644 src/test/java/redis/clients/jedis/tests/utils/KeyMergeUtilTest.java rename src/test/java/redis/clients/jedis/{tests/utils => util}/AssertUtil.java (96%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/ByteArrayComparatorTest.java (83%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/ByteArrayUtil.java (94%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/ClientKillerUtil.java (71%) rename src/test/java/redis/clients/jedis/{tests => util}/FragmentedByteArrayInputStream.java (95%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/JedisClusterCRC16Test.java (94%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/JedisClusterTestUtil.java (98%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/JedisSentinelTestUtil.java (83%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/JedisURIHelperTest.java (95%) rename src/test/java/redis/clients/jedis/{tests/utils => util}/RedisVersionUtil.java (87%) diff --git a/pom.xml b/pom.xml index 955f365ad6..5a55157830 100644 --- a/pom.xml +++ b/pom.xml @@ -60,15 +60,22 @@ org.apache.commons commons-pool2 2.11.1 - jar - compile + + + org.json + json + 20210307 + + + com.google.code.gson + gson + 2.8.8 junit junit 4.13.1 - jar test @@ -144,6 +151,7 @@ ${redis-hosts} + diff --git a/src/main/java/redis/clients/jedis/BinaryClient.java b/src/main/java/redis/clients/jedis/BinaryClient.java deleted file mode 100644 index efed109655..0000000000 --- a/src/main/java/redis/clients/jedis/BinaryClient.java +++ /dev/null @@ -1,2099 +0,0 @@ -package redis.clients.jedis; - -import static redis.clients.jedis.Protocol.toByteArray; -import static redis.clients.jedis.Protocol.Command.*; -import static redis.clients.jedis.Protocol.Command.EXISTS; -import static redis.clients.jedis.Protocol.Command.GET; -import static redis.clients.jedis.Protocol.Command.INCR; -import static redis.clients.jedis.Protocol.Command.KEYS; -import static redis.clients.jedis.Protocol.Command.PING; -import static redis.clients.jedis.Protocol.Command.PSUBSCRIBE; -import static redis.clients.jedis.Protocol.Command.PUNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Command.SAVE; -import static redis.clients.jedis.Protocol.Command.SET; -import static redis.clients.jedis.Protocol.Command.SUBSCRIBE; -import static redis.clients.jedis.Protocol.Command.TIME; -import static redis.clients.jedis.Protocol.Command.TYPE; -import static redis.clients.jedis.Protocol.Command.UNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.*; - -import java.util.*; -import java.util.Map.Entry; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - -import redis.clients.jedis.Protocol.Keyword; -import redis.clients.jedis.Protocol.SentinelKeyword; -import redis.clients.jedis.args.ClientPauseMode; -import redis.clients.jedis.args.ClientType; -import redis.clients.jedis.args.ListDirection; -import redis.clients.jedis.args.FlushMode; -import redis.clients.jedis.args.SaveMode; -import redis.clients.jedis.args.UnblockType; -import redis.clients.jedis.params.*; -import redis.clients.jedis.util.SafeEncoder; - -public class BinaryClient extends Connection { - - private boolean isInMulti; - - @Deprecated - private String user; - @Deprecated - private String password; - - private int db; - - private boolean isInWatch; - - public BinaryClient() { - super(); - } - - /** - * @param host - * @deprecated This constructor will be removed in future. It can be replaced with - * {@link #BinaryClient(java.lang.String, int)} with the host and {@link Protocol#DEFAULT_PORT}. - */ - @Deprecated - public BinaryClient(final String host) { - super(host); - } - - public BinaryClient(final String host, final int port) { - super(host, port); - } - - /** - * @deprecated This constructor will be removed in future. Use - * {@link #BinaryClient(redis.clients.jedis.HostAndPort, redis.clients.jedis.JedisClientConfig)}. - */ - @Deprecated - public BinaryClient(final String host, final int port, final boolean ssl) { - super(host, port, ssl); - } - - /** - * @deprecated This constructor will be removed in future. Use - * {@link #BinaryClient(redis.clients.jedis.HostAndPort, redis.clients.jedis.JedisClientConfig)}. - */ - @Deprecated - public BinaryClient(final String host, final int port, final boolean ssl, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - super(host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - } - - public BinaryClient(final HostAndPort hostPort, final JedisClientConfig clientConfig) { - super(hostPort, clientConfig); - } - - public BinaryClient(final JedisSocketFactory jedisSocketFactory) { - super(jedisSocketFactory); - } - - public boolean isInMulti() { - return isInMulti; - } - - public boolean isInWatch() { - return isInWatch; - } - - /** - * @param user - * @deprecated This method will be removed in future. Because this class will be restricted from - * holding any user data. - */ - @Deprecated - public void setUser(final String user) { - this.user = user; - } - - /** - * @param password - * @deprecated This method will be removed in future. Because this class will be restricted from - * holding any user data. - */ - @Deprecated - public void setPassword(final String password) { - this.password = password; - } - - /** - * This method should be called only after a successful SELECT command. - * @param db - */ - public void setDb(int db) { - this.db = db; - } - - public int getDB() { - return db; - } - - @Override - public void connect() { - if (!isConnected()) { - super.connect(); - if (user != null) { - auth(user, password); - getStatusCodeReply(); - } else if (password != null) { - auth(password); - getStatusCodeReply(); - } - if (db > 0) { - select(db); - getStatusCodeReply(); - } - } - } - - @Override - public void disconnect() { - db = 0; - super.disconnect(); - } - - @Override - public void close() { - db = 0; - super.close(); - } - - public void resetState() { - if (isInWatch()) { - unwatch(); - getStatusCodeReply(); - } - } - - public void copy(byte[] srcKey, byte[] dstKey, boolean replace) { - if (replace) { - sendCommand(COPY, srcKey, dstKey, REPLACE.getRaw()); - } else { - sendCommand(COPY, srcKey, dstKey); - } - } - - public void copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) { - if (replace) { - sendCommand(COPY, srcKey, dstKey, DB.getRaw(), toByteArray(db), REPLACE.getRaw()); - } else { - sendCommand(COPY, srcKey, dstKey, DB.getRaw(), toByteArray(db)); - } - } - - public void ping() { - sendCommand(PING); - } - - public void ping(final byte[] message) { - sendCommand(PING, message); - } - - public void set(final byte[] key, final byte[] value) { - sendCommand(SET, key, value); - } - - public void set(final byte[] key, final byte[] value, final SetParams params) { - sendCommand(SET, params.getByteParams(key, value)); - } - - public void get(final byte[] key) { - sendCommand(GET, key); - } - - public void getDel(final byte[] key) { - sendCommand(GETDEL, key); - } - - public void getEx(final byte[] key, final GetExParams params) { - sendCommand(GETEX, params.getByteParams(key)); - } - - public void quit() { - db = 0; - sendCommand(QUIT); - } - - public void exists(final byte[]... keys) { - sendCommand(EXISTS, keys); - } - - public void del(final byte[]... keys) { - sendCommand(DEL, keys); - } - - public void unlink(final byte[]... keys) { - sendCommand(UNLINK, keys); - } - - public void type(final byte[] key) { - sendCommand(TYPE, key); - } - - public void flushDB() { - sendCommand(FLUSHDB); - } - - public void flushDB(FlushMode flushMode) { - sendCommand(FLUSHDB, flushMode.getRaw()); - } - - public void keys(final byte[] pattern) { - sendCommand(KEYS, pattern); - } - - public void randomKey() { - sendCommand(RANDOMKEY); - } - - public void rename(final byte[] oldkey, final byte[] newkey) { - sendCommand(RENAME, oldkey, newkey); - } - - public void renamenx(final byte[] oldkey, final byte[] newkey) { - sendCommand(RENAMENX, oldkey, newkey); - } - - public void dbSize() { - sendCommand(DBSIZE); - } - - /** - * @deprecated Use {@link #expire(byte[], long)}. - */ - @Deprecated - public void expire(final byte[] key, final int seconds) { - sendCommand(EXPIRE, key, toByteArray(seconds)); - } - - public void expire(final byte[] key, final long seconds) { - sendCommand(EXPIRE, key, toByteArray(seconds)); - } - - public void expireAt(final byte[] key, final long unixTime) { - sendCommand(EXPIREAT, key, toByteArray(unixTime)); - } - - public void ttl(final byte[] key) { - sendCommand(TTL, key); - } - - public void touch(final byte[]... keys) { - sendCommand(TOUCH, keys); - } - - public void select(final int index) { - sendCommand(SELECT, toByteArray(index)); - } - - public void swapDB(final int index1, final int index2) { - sendCommand(SWAPDB, toByteArray(index1), toByteArray(index2)); - } - - public void move(final byte[] key, final int dbIndex) { - sendCommand(MOVE, key, toByteArray(dbIndex)); - } - - public void flushAll() { - sendCommand(FLUSHALL); - } - - public void flushAll(FlushMode flushMode) { - sendCommand(FLUSHALL, flushMode.getRaw()); - } - - public void getSet(final byte[] key, final byte[] value) { - sendCommand(GETSET, key, value); - } - - public void mget(final byte[]... keys) { - sendCommand(MGET, keys); - } - - public void setnx(final byte[] key, final byte[] value) { - sendCommand(SETNX, key, value); - } - - /** - * @deprecated Use {@link #setex(byte[], long, byte[])}. - */ - @Deprecated - public void setex(final byte[] key, final int seconds, final byte[] value) { - sendCommand(SETEX, key, toByteArray(seconds), value); - } - - public void setex(final byte[] key, final long seconds, final byte[] value) { - sendCommand(SETEX, key, toByteArray(seconds), value); - } - - public void mset(final byte[]... keysvalues) { - sendCommand(MSET, keysvalues); - } - - public void msetnx(final byte[]... keysvalues) { - sendCommand(MSETNX, keysvalues); - } - - public void decrBy(final byte[] key, final long decrement) { - sendCommand(DECRBY, key, toByteArray(decrement)); - } - - public void decr(final byte[] key) { - sendCommand(DECR, key); - } - - public void incrBy(final byte[] key, final long increment) { - sendCommand(INCRBY, key, toByteArray(increment)); - } - - public void incrByFloat(final byte[] key, final double increment) { - sendCommand(INCRBYFLOAT, key, toByteArray(increment)); - } - - public void incr(final byte[] key) { - sendCommand(INCR, key); - } - - public void append(final byte[] key, final byte[] value) { - sendCommand(APPEND, key, value); - } - - public void substr(final byte[] key, final int start, final int end) { - sendCommand(SUBSTR, key, toByteArray(start), toByteArray(end)); - } - - public void hset(final byte[] key, final byte[] field, final byte[] value) { - sendCommand(HSET, key, field, value); - } - - public void hset(final byte[] key, final Map hash) { - final byte[][] params = new byte[1 + hash.size() * 2][]; - - int index = 0; - params[index++] = key; - for (final Entry entry : hash.entrySet()) { - params[index++] = entry.getKey(); - params[index++] = entry.getValue(); - } - sendCommand(HSET, params); - } - - public void hget(final byte[] key, final byte[] field) { - sendCommand(HGET, key, field); - } - - public void hsetnx(final byte[] key, final byte[] field, final byte[] value) { - sendCommand(HSETNX, key, field, value); - } - - public void hmset(final byte[] key, final Map hash) { - final List params = new ArrayList<>(); - params.add(key); - - for (final Entry entry : hash.entrySet()) { - params.add(entry.getKey()); - params.add(entry.getValue()); - } - sendCommand(HMSET, params.toArray(new byte[params.size()][])); - } - - public void hmget(final byte[] key, final byte[]... fields) { - sendCommand(HMGET, joinParameters(key, fields)); - } - - public void hincrBy(final byte[] key, final byte[] field, final long value) { - sendCommand(HINCRBY, key, field, toByteArray(value)); - } - - public void hexists(final byte[] key, final byte[] field) { - sendCommand(HEXISTS, key, field); - } - - public void hdel(final byte[] key, final byte[]... fields) { - sendCommand(HDEL, joinParameters(key, fields)); - } - - public void hlen(final byte[] key) { - sendCommand(HLEN, key); - } - - public void hkeys(final byte[] key) { - sendCommand(HKEYS, key); - } - - public void hvals(final byte[] key) { - sendCommand(HVALS, key); - } - - public void hgetAll(final byte[] key) { - sendCommand(HGETALL, key); - } - - public void hrandfield(final byte[] key) { - sendCommand(HRANDFIELD, key); - } - - public void hrandfield(final byte[] key, final long count) { - sendCommand(HRANDFIELD, key, toByteArray(count)); - } - - public void hrandfieldWithValues(final byte[] key, final long count) { - sendCommand(HRANDFIELD, key, toByteArray(count), WITHVALUES.getRaw()); - } - - public void rpush(final byte[] key, final byte[]... strings) { - sendCommand(RPUSH, joinParameters(key, strings)); - } - - public void lpush(final byte[] key, final byte[]... strings) { - sendCommand(LPUSH, joinParameters(key, strings)); - } - - public void llen(final byte[] key) { - sendCommand(LLEN, key); - } - - public void lrange(final byte[] key, final long start, final long stop) { - sendCommand(LRANGE, key, toByteArray(start), toByteArray(stop)); - } - - public void ltrim(final byte[] key, final long start, final long stop) { - sendCommand(LTRIM, key, toByteArray(start), toByteArray(stop)); - } - - public void lindex(final byte[] key, final long index) { - sendCommand(LINDEX, key, toByteArray(index)); - } - - public void lset(final byte[] key, final long index, final byte[] value) { - sendCommand(LSET, key, toByteArray(index), value); - } - - public void lrem(final byte[] key, final long count, final byte[] value) { - sendCommand(LREM, key, toByteArray(count), value); - } - - public void lpop(final byte[] key) { - sendCommand(LPOP, key); - } - - public void lpop(final byte[] key, final int count) { - sendCommand(LPOP, key, toByteArray(count)); - } - - public void lpos(final byte[] key, final byte[] element) { - sendCommand(LPOS, key, element); - } - - public void lpos(final byte[] key, final byte[] element, LPosParams params) { - sendCommand(LPOS, joinParameters(key, element, params.getByteParams())); - } - - public void lpos(final byte[] key, final byte[] element, final LPosParams params, final long count) { - sendCommand( - LPOS, - joinParameters(key, element, params.getByteParams(Keyword.COUNT.getRaw(), toByteArray(count)))); - } - - public void rpop(final byte[] key) { - sendCommand(RPOP, key); - } - - public void rpop(final byte[] key, final int count) { - sendCommand(RPOP, key, toByteArray(count)); - } - - public void rpoplpush(final byte[] srckey, final byte[] dstkey) { - sendCommand(RPOPLPUSH, srckey, dstkey); - } - - public void sadd(final byte[] key, final byte[]... members) { - sendCommand(SADD, joinParameters(key, members)); - } - - public void smembers(final byte[] key) { - sendCommand(SMEMBERS, key); - } - - public void srem(final byte[] key, final byte[]... members) { - sendCommand(SREM, joinParameters(key, members)); - } - - public void spop(final byte[] key) { - sendCommand(SPOP, key); - } - - public void spop(final byte[] key, final long count) { - sendCommand(SPOP, key, toByteArray(count)); - } - - public void smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { - sendCommand(SMOVE, srckey, dstkey, member); - } - - public void scard(final byte[] key) { - sendCommand(SCARD, key); - } - - public void sismember(final byte[] key, final byte[] member) { - sendCommand(SISMEMBER, key, member); - } - - public void smismember(final byte[] key, final byte[]... members) { - sendCommand(SMISMEMBER, joinParameters(key, members)); - } - - public void sinter(final byte[]... keys) { - sendCommand(SINTER, keys); - } - - public void sinterstore(final byte[] dstkey, final byte[]... keys) { - sendCommand(SINTERSTORE, joinParameters(dstkey, keys)); - } - - public void sunion(final byte[]... keys) { - sendCommand(SUNION, keys); - } - - public void sunionstore(final byte[] dstkey, final byte[]... keys) { - sendCommand(SUNIONSTORE, joinParameters(dstkey, keys)); - } - - public void sdiff(final byte[]... keys) { - sendCommand(SDIFF, keys); - } - - public void sdiffstore(final byte[] dstkey, final byte[]... keys) { - sendCommand(SDIFFSTORE, joinParameters(dstkey, keys)); - } - - public void srandmember(final byte[] key) { - sendCommand(SRANDMEMBER, key); - } - - public void zadd(final byte[] key, final double score, final byte[] member) { - sendCommand(ZADD, key, toByteArray(score), member); - } - - public void zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { - sendCommand(ZADD, params.getByteParams(key, toByteArray(score), member)); - } - - public void zadd(final byte[] key, final Map scoreMembers) { - ArrayList args = new ArrayList<>(scoreMembers.size() * 2 + 1); - args.add(key); - args.addAll(convertScoreMembersToByteArrays(scoreMembers)); - - byte[][] argsArray = new byte[args.size()][]; - args.toArray(argsArray); - - sendCommand(ZADD, argsArray); - } - - public void zadd(final byte[] key, final Map scoreMembers, final ZAddParams params) { - ArrayList args = convertScoreMembersToByteArrays(scoreMembers); - byte[][] argsArray = new byte[args.size()][]; - args.toArray(argsArray); - - sendCommand(ZADD, params.getByteParams(key, argsArray)); - } - - public void zdiff(final byte[]... keys) { - sendCommand(ZDIFF, joinParameters(toByteArray(keys.length), keys)); - } - - public void zdiffWithScores(final byte[]... keys) { - final List args = new ArrayList<>(keys.length + 2); - args.add(toByteArray(keys.length)); - Collections.addAll(args, keys); - args.add(WITHSCORES.getRaw()); - sendCommand(ZDIFF, args.toArray(new byte[args.size()][])); - } - - public void zaddIncr(final byte[] key, final double score, final byte[] member, final ZAddParams params) { - sendCommand(ZADD, params.getByteParams(key, INCR.getRaw(), toByteArray(score), member)); - } - - public void zdiffStore(final byte[] dstkey, final byte[]... keys) { - sendCommand(ZDIFFSTORE, joinParameters(dstkey, toByteArray(keys.length), keys)); - } - - public void zrange(final byte[] key, final long start, final long stop) { - sendCommand(ZRANGE, key, toByteArray(start), toByteArray(stop)); - } - - public void zrem(final byte[] key, final byte[]... members) { - sendCommand(ZREM, joinParameters(key, members)); - } - - public void zincrby(final byte[] key, final double increment, final byte[] member) { - sendCommand(ZINCRBY, key, toByteArray(increment), member); - } - - public void zincrby(final byte[] key, final double increment, final byte[] member, - final ZIncrByParams params) { - // Note that it actually calls ZADD with INCR option, so it requires Redis 3.0.2 or upper. - sendCommand(ZADD, params.getByteParams(key, toByteArray(increment), member)); - } - - public void zrank(final byte[] key, final byte[] member) { - sendCommand(ZRANK, key, member); - } - - public void zrevrank(final byte[] key, final byte[] member) { - sendCommand(ZREVRANK, key, member); - } - - public void zrevrange(final byte[] key, final long start, final long stop) { - sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(stop)); - } - - public void zrangeWithScores(final byte[] key, final long start, final long stop) { - sendCommand(ZRANGE, key, toByteArray(start), toByteArray(stop), WITHSCORES.getRaw()); - } - - public void zrevrangeWithScores(final byte[] key, final long start, final long stop) { - sendCommand(ZREVRANGE, key, toByteArray(start), toByteArray(stop), WITHSCORES.getRaw()); - } - - public void zrandmember(final byte[] key) { - sendCommand(ZRANDMEMBER, key); - } - - public void zrandmember(final byte[] key, final long count) { - sendCommand(ZRANDMEMBER, key, toByteArray(count)); - } - - public void zrandmemberWithScores(final byte[] key, final long count) { - sendCommand(ZRANDMEMBER, key, toByteArray(count), WITHSCORES.getRaw()); - } - - public void zcard(final byte[] key) { - sendCommand(ZCARD, key); - } - - public void zscore(final byte[] key, final byte[] member) { - sendCommand(ZSCORE, key, member); - } - - public void zmscore(final byte[] key, final byte[]... members) { - sendCommand(ZMSCORE, joinParameters(key, members)); - } - - public void zpopmax(final byte[] key) { - sendCommand(ZPOPMAX, key); - } - - public void zpopmax(final byte[] key, final int count) { - sendCommand(ZPOPMAX, key, toByteArray(count)); - } - - public void zpopmin(final byte[] key) { - sendCommand(ZPOPMIN, key); - } - - public void zpopmin(final byte[] key, final long count) { - sendCommand(ZPOPMIN, key, toByteArray(count)); - } - - public void multi() { - sendCommand(MULTI); - isInMulti = true; - } - - public void discard() { - sendCommand(DISCARD); - isInMulti = false; - isInWatch = false; - } - - public void exec() { - sendCommand(EXEC); - isInMulti = false; - isInWatch = false; - } - - public void watch(final byte[]... keys) { - sendCommand(WATCH, keys); - isInWatch = true; - } - - public void unwatch() { - sendCommand(UNWATCH); - isInWatch = false; - } - - public void sort(final byte[] key) { - sendCommand(SORT, key); - } - - public void sort(final byte[] key, final SortingParams sortingParameters) { - final List args = new ArrayList<>(); - args.add(key); - args.addAll(sortingParameters.getParams()); - sendCommand(SORT, args.toArray(new byte[args.size()][])); - } - - public void sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { - final List args = new ArrayList<>(); - args.add(key); - args.addAll(sortingParameters.getParams()); - args.add(STORE.getRaw()); - args.add(dstkey); - sendCommand(SORT, args.toArray(new byte[args.size()][])); - } - - public void sort(final byte[] key, final byte[] dstkey) { - sendCommand(SORT, key, STORE.getRaw(), dstkey); - } - - public void lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { - sendCommand(LMOVE, srcKey, dstKey, from.getRaw(), to.getRaw()); - } - - public void blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { - sendCommand(BLMOVE, srcKey, dstKey, from.getRaw(), to.getRaw(), toByteArray(timeout)); - } - - public void blpop(final byte[][] args) { - sendCommand(BLPOP, args); - } - - public void blpop(final int timeout, final byte[]... keys) { - blpop(getKeysAndTimeout(timeout, keys)); - } - - public void blpop(final double timeout, final byte[]... keys) { - blpop(getKeysAndTimeout(timeout, keys)); - } - - public void brpop(final byte[][] args) { - sendCommand(BRPOP, args); - } - - public void brpop(final int timeout, final byte[]... keys) { - brpop(getKeysAndTimeout(timeout, keys)); - } - - public void brpop(final double timeout, final byte[]... keys) { - brpop(getKeysAndTimeout(timeout, keys)); - } - - public void bzpopmax(final double timeout, final byte[]... keys) { - sendCommand(BZPOPMAX, getKeysAndTimeout(timeout, keys)); - } - - public void bzpopmin(final double timeout, final byte[]... keys) { - sendCommand(BZPOPMIN, getKeysAndTimeout(timeout, keys)); - } - - private static byte[][] getKeysAndTimeout(final int timeout, final byte[]... keys) { - int numKeys = keys.length; - byte[][] args = new byte[numKeys + 1][]; - System.arraycopy(keys, 0, args, 0, numKeys); - args[numKeys] = toByteArray(timeout); - return args; - } - - private static byte[][] getKeysAndTimeout(final double timeout, final byte[]... keys) { - int numKeys = keys.length; - byte[][] args = new byte[numKeys + 1][]; - System.arraycopy(keys, 0, args, 0, numKeys); - args[numKeys] = toByteArray(timeout); - return args; - } - - public void auth(final String password) { - setPassword(password); - sendCommand(AUTH, password); - } - - public void auth(final String user, final String password) { - setUser(user); - setPassword(password); - sendCommand(AUTH, user, password); - } - - public void subscribe(final byte[]... channels) { - sendCommand(SUBSCRIBE, channels); - } - - public void publish(final byte[] channel, final byte[] message) { - sendCommand(PUBLISH, channel, message); - } - - public void unsubscribe() { - sendCommand(UNSUBSCRIBE); - } - - public void unsubscribe(final byte[]... channels) { - sendCommand(UNSUBSCRIBE, channels); - } - - public void psubscribe(final byte[]... patterns) { - sendCommand(PSUBSCRIBE, patterns); - } - - public void punsubscribe() { - sendCommand(PUNSUBSCRIBE); - } - - public void punsubscribe(final byte[]... patterns) { - sendCommand(PUNSUBSCRIBE, patterns); - } - - public void pubsub(final byte[]... args) { - sendCommand(PUBSUB, args); - } - - public void zcount(final byte[] key, final double min, final double max) { - sendCommand(ZCOUNT, key, toByteArray(min), toByteArray(max)); - } - - public void zcount(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZCOUNT, key, min, max); - } - - public void zrangeByScore(final byte[] key, final double min, final double max) { - sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max)); - } - - public void zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZRANGEBYSCORE, key, min, max); - } - - public void zrevrangeByScore(final byte[] key, final double max, final double min) { - sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min)); - } - - public void zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { - sendCommand(ZREVRANGEBYSCORE, key, max, min); - } - - public void zrangeByScore(final byte[] key, final double min, final double max, final int offset, - final int count) { - sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.getRaw(), - toByteArray(offset), toByteArray(count)); - } - - public void zrevrangeByScore(final byte[] key, final double max, final double min, - final int offset, final int count) { - sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), LIMIT.getRaw(), - toByteArray(offset), toByteArray(count)); - } - - public void zrangeByScoreWithScores(final byte[] key, final double min, final double max) { - sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), WITHSCORES.getRaw()); - } - - public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), WITHSCORES.getRaw()); - } - - public void zrangeByScoreWithScores(final byte[] key, final double min, final double max, - final int offset, final int count) { - sendCommand(ZRANGEBYSCORE, key, toByteArray(min), toByteArray(max), LIMIT.getRaw(), - toByteArray(offset), toByteArray(count), WITHSCORES.getRaw()); - } - - public void zrevrangeByScoreWithScores(final byte[] key, final double max, final double min, - final int offset, final int count) { - sendCommand(ZREVRANGEBYSCORE, key, toByteArray(max), toByteArray(min), LIMIT.getRaw(), - toByteArray(offset), toByteArray(count), WITHSCORES.getRaw()); - } - - public void zrangeByScore(final byte[] key, final byte[] min, final byte[] max, final int offset, - final int count) { - sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.getRaw(), toByteArray(offset), - toByteArray(count)); - } - - public void zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - sendCommand(ZREVRANGEBYSCORE, key, max, min, LIMIT.getRaw(), toByteArray(offset), - toByteArray(count)); - } - - public void zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZRANGEBYSCORE, key, min, max, WITHSCORES.getRaw()); - } - - public void zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { - sendCommand(ZREVRANGEBYSCORE, key, max, min, WITHSCORES.getRaw()); - } - - public void zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - sendCommand(ZRANGEBYSCORE, key, min, max, LIMIT.getRaw(), toByteArray(offset), - toByteArray(count), WITHSCORES.getRaw()); - } - - public void zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - sendCommand(ZREVRANGEBYSCORE, key, max, min, LIMIT.getRaw(), toByteArray(offset), - toByteArray(count), WITHSCORES.getRaw()); - } - - public void zremrangeByRank(final byte[] key, final long start, final long stop) { - sendCommand(ZREMRANGEBYRANK, key, toByteArray(start), toByteArray(stop)); - } - - public void zremrangeByScore(final byte[] key, final double min, final double max) { - sendCommand(ZREMRANGEBYSCORE, key, toByteArray(min), toByteArray(max)); - } - - public void zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZREMRANGEBYSCORE, key, min, max); - } - - public void zunion(final ZParams params, final byte[]... keys) { - sendCommand(ZUNION, buildByteZParams(params, false, keys)); - } - - public void zunionWithScores(final ZParams params, final byte[]... keys) { - sendCommand(ZUNION, buildByteZParams(params, true, keys)); - } - - private byte[][] buildByteZParams(final ZParams params, final boolean withScores, final byte[]... keys) { - final List args = new ArrayList<>(); - args.add(Protocol.toByteArray(keys.length)); - Collections.addAll(args, keys); - - args.addAll(params.getParams()); - if (withScores) { - args.add(WITHSCORES.getRaw()); - } - return args.toArray(new byte[args.size()][]); - } - - public void zunionstore(final byte[] dstkey, final byte[]... sets) { - sendCommand(ZUNIONSTORE, joinParameters(dstkey, toByteArray(sets.length), sets)); - } - - public void zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { - final List args = new ArrayList<>(); - args.add(dstkey); - args.add(Protocol.toByteArray(sets.length)); - Collections.addAll(args, sets); - - args.addAll(params.getParams()); - sendCommand(ZUNIONSTORE, args.toArray(new byte[args.size()][])); - } - - public void zinter(final ZParams params, final byte[]... keys) { - sendCommand(ZINTER, buildByteZParams(params, false, keys)); - } - - public void zinterWithScores(final ZParams params, final byte[]... keys) { - sendCommand(ZINTER, buildByteZParams(params, true, keys)); - } - - public void zinterstore(final byte[] dstkey, final byte[]... sets) { - sendCommand(ZINTERSTORE, joinParameters(dstkey, Protocol.toByteArray(sets.length), sets)); - } - - public void zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { - final List args = new ArrayList<>(); - args.add(dstkey); - args.add(Protocol.toByteArray(sets.length)); - Collections.addAll(args, sets); - - args.addAll(params.getParams()); - sendCommand(ZINTERSTORE, args.toArray(new byte[args.size()][])); - } - - public void zlexcount(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZLEXCOUNT, key, min, max); - } - - public void zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZRANGEBYLEX, key, min, max); - } - - public void zrangeByLex(final byte[] key, final byte[] min, final byte[] max, final int offset, - final int count) { - sendCommand(ZRANGEBYLEX, key, min, max, LIMIT.getRaw(), toByteArray(offset), toByteArray(count)); - } - - public void zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { - sendCommand(ZREVRANGEBYLEX, key, max, min); - } - - public void zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - sendCommand(ZREVRANGEBYLEX, key, max, min, LIMIT.getRaw(), toByteArray(offset), - toByteArray(count)); - } - - public void zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - sendCommand(ZREMRANGEBYLEX, key, min, max); - } - - public void save() { - sendCommand(SAVE); - } - - public void bgsave() { - sendCommand(BGSAVE); - } - - public void bgrewriteaof() { - sendCommand(BGREWRITEAOF); - } - - public void lastsave() { - sendCommand(LASTSAVE); - } - - public void shutdown() { - sendCommand(SHUTDOWN); - } - - public void shutdown(SaveMode saveMode) { - if (saveMode == null) { - sendCommand(SHUTDOWN); - } else { - sendCommand(SHUTDOWN, saveMode.getRaw()); - } - } - - public void info() { - sendCommand(INFO); - } - - public void info(final String section) { - sendCommand(INFO, section); - } - - public void monitor() { - sendCommand(MONITOR); - } - - public void slaveof(final String host, final int port) { - sendCommand(SLAVEOF, host, String.valueOf(port)); - } - - public void slaveofNoOne() { - sendCommand(SLAVEOF, NO.getRaw(), ONE.getRaw()); - } - - public void role() { - sendCommand(ROLE); - } - - public void configGet(final byte[] pattern) { - sendCommand(CONFIG, Keyword.GET.getRaw(), pattern); - } - - public void configSet(final byte[] parameter, final byte[] value) { - sendCommand(CONFIG, Keyword.SET.getRaw(), parameter, value); - } - - public void strlen(final byte[] key) { - sendCommand(STRLEN, key); - } - - public void strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params) { - sendCommand(STRALGO, params.getByteParams(Keyword.KEYS, keyA, keyB)); - } - - public void strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params) { - sendCommand(STRALGO, params.getByteParams(Keyword.STRINGS, strA, strB)); - } - - public void lpushx(final byte[] key, final byte[]... string) { - sendCommand(LPUSHX, joinParameters(key, string)); - } - - public void persist(final byte[] key) { - sendCommand(PERSIST, key); - } - - public void rpushx(final byte[] key, final byte[]... string) { - sendCommand(RPUSHX, joinParameters(key, string)); - } - - public void echo(final byte[] string) { - sendCommand(ECHO, string); - } - - public void linsert(final byte[] key, final ListPosition where, final byte[] pivot, - final byte[] value) { - sendCommand(LINSERT, key, where.raw, pivot, value); - } - - public void debug(final DebugParams params) { - sendCommand(DEBUG, params.getCommand()); - } - - public void brpoplpush(final byte[] source, final byte[] destination, final int timeout) { - sendCommand(BRPOPLPUSH, source, destination, toByteArray(timeout)); - } - - public void configResetStat() { - sendCommand(CONFIG, Keyword.RESETSTAT.getRaw()); - } - - public void configRewrite() { - sendCommand(CONFIG, Keyword.REWRITE.getRaw()); - } - - public void setbit(final byte[] key, final long offset, final byte[] value) { - sendCommand(SETBIT, key, toByteArray(offset), value); - } - - public void setbit(final byte[] key, final long offset, final boolean value) { - sendCommand(SETBIT, key, toByteArray(offset), toByteArray(value)); - } - - public void getbit(final byte[] key, final long offset) { - sendCommand(GETBIT, key, toByteArray(offset)); - } - - public void bitpos(final byte[] key, final boolean value, final BitPosParams params) { - final List args = new ArrayList<>(); - args.add(key); - args.add(toByteArray(value)); - args.addAll(params.getParams()); - sendCommand(BITPOS, args.toArray(new byte[args.size()][])); - } - - public void setrange(final byte[] key, final long offset, final byte[] value) { - sendCommand(SETRANGE, key, toByteArray(offset), value); - } - - public void getrange(final byte[] key, final long startOffset, final long endOffset) { - sendCommand(GETRANGE, key, toByteArray(startOffset), toByteArray(endOffset)); - } - - public void eval(final byte[] script, final byte[] keyCount, final byte[][] params) { - sendCommand(EVAL, joinParameters(script, keyCount, params)); - } - - public void eval(final byte[] script, final int keyCount, final byte[]... params) { - sendCommand(EVAL, joinParameters(script, toByteArray(keyCount), params)); - } - - public void evalsha(final byte[] sha1, final byte[] keyCount, final byte[]... params) { - sendCommand(EVALSHA, joinParameters(sha1, keyCount, params)); - } - - public void evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { - sendCommand(EVALSHA, joinParameters(sha1, toByteArray(keyCount), params)); - } - - public void scriptFlush() { - sendCommand(SCRIPT, Keyword.FLUSH.getRaw()); - } - - public void scriptFlush(FlushMode flushMode) { - sendCommand(SCRIPT, Keyword.FLUSH.getRaw(), flushMode.getRaw()); - } - - public void scriptExists(final byte[]... sha1) { - sendCommand(SCRIPT, joinParameters(Keyword.EXISTS.getRaw(), sha1)); - } - - public void scriptLoad(final byte[] script) { - sendCommand(SCRIPT, Keyword.LOAD.getRaw(), script); - } - - public void scriptKill() { - sendCommand(SCRIPT, Keyword.KILL.getRaw()); - } - - public void slowlogGet() { - sendCommand(SLOWLOG, Keyword.GET.getRaw()); - } - - public void slowlogGet(final long entries) { - sendCommand(SLOWLOG, Keyword.GET.getRaw(), toByteArray(entries)); - } - - public void slowlogReset() { - sendCommand(SLOWLOG, RESET.getRaw()); - } - - public void slowlogLen() { - sendCommand(SLOWLOG, LEN.getRaw()); - } - - public void objectRefcount(final byte[] key) { - sendCommand(OBJECT, REFCOUNT.getRaw(), key); - } - - public void objectIdletime(final byte[] key) { - sendCommand(OBJECT, IDLETIME.getRaw(), key); - } - - public void objectEncoding(final byte[] key) { - sendCommand(OBJECT, ENCODING.getRaw(), key); - } - - public void objectHelp() { - sendCommand(OBJECT, HELP.getRaw()); - } - - public void objectFreq(final byte[] key) { - sendCommand(OBJECT, FREQ.getRaw(), key); - } - - public void bitcount(final byte[] key) { - sendCommand(BITCOUNT, key); - } - - public void bitcount(final byte[] key, final long start, final long end) { - sendCommand(BITCOUNT, key, toByteArray(start), toByteArray(end)); - } - - public void bitop(final BitOP op, final byte[] destKey, final byte[]... srcKeys) { - sendCommand(BITOP, joinParameters(op.raw, destKey, srcKeys)); - } - - public void sentinel(final byte[]... args) { - sendCommand(SENTINEL, args); - } - - public void sentinel(SentinelKeyword subcommand, final byte[]... args) { - sendCommand(SENTINEL, joinParameters(subcommand.getRaw(), args)); - } - - public void sentinel(SentinelKeyword subcommand) { - sendCommand(SENTINEL, subcommand.getRaw()); - } - - public void dump(final byte[] key) { - sendCommand(DUMP, key); - } - - /** - * @deprecated Use {@link #restore(byte[], long, byte[])}. - */ - @Deprecated - public void restore(final byte[] key, final int ttl, final byte[] serializedValue) { - sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); - } - - public void restore(final byte[] key, final long ttl, final byte[] serializedValue) { - sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); - } - - /** - * @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - public void restoreReplace(final byte[] key, final int ttl, final byte[] serializedValue) { - sendCommand(RESTORE, key, toByteArray(ttl), serializedValue, Keyword.REPLACE.getRaw()); - } - - /** - * @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - public void restoreReplace(final byte[] key, final long ttl, final byte[] serializedValue) { - sendCommand(RESTORE, key, toByteArray(ttl), serializedValue, Keyword.REPLACE.getRaw()); - } - - public void restore(final byte[] key, final long ttl, final byte[] serializedValue, final RestoreParams params) { - if (params == null) { - sendCommand(RESTORE, key, toByteArray(ttl), serializedValue); - } else { - sendCommand(RESTORE, params.getByteParams(key, toByteArray(ttl), serializedValue)); - } - } - - public void pexpire(final byte[] key, final long milliseconds) { - sendCommand(PEXPIRE, key, toByteArray(milliseconds)); - } - - public void pexpireAt(final byte[] key, final long millisecondsTimestamp) { - sendCommand(PEXPIREAT, key, toByteArray(millisecondsTimestamp)); - } - - public void pttl(final byte[] key) { - sendCommand(PTTL, key); - } - - public void psetex(final byte[] key, final long milliseconds, final byte[] value) { - sendCommand(PSETEX, key, toByteArray(milliseconds), value); - } - - public void srandmember(final byte[] key, final int count) { - sendCommand(SRANDMEMBER, key, toByteArray(count)); - } - - public void memoryDoctor() { - sendCommand(MEMORY, Keyword.DOCTOR.getRaw()); - } - - public void memoryUsage(final byte[] key) { - sendCommand(MEMORY, Keyword.USAGE.getRaw(), key); - } - - public void memoryUsage(final byte[] key, final int samples) { - sendCommand(MEMORY, Keyword.USAGE.getRaw(), key, Keyword.SAMPLES.getRaw(), toByteArray(samples)); - } - - public void failover(FailoverParams failoverParams) { - if (failoverParams == null) { - sendCommand(FAILOVER); - } else { - sendCommand(FAILOVER, failoverParams.getByteParams()); - } - } - - public void failoverAbort() { - sendCommand(FAILOVER, ABORT.getRaw()); - } - - public void clientKill(final byte[] ipPort) { - sendCommand(CLIENT, Keyword.KILL.getRaw(), ipPort); - } - - public void clientKill(final String ip, final int port) { - sendCommand(CLIENT, Keyword.KILL.name(), ip + ':' + port); - } - - public void clientKill(ClientKillParams params) { - sendCommand(CLIENT, joinParameters(Keyword.KILL.getRaw(), params.getByteParams())); - } - - public void clientGetname() { - sendCommand(CLIENT, Keyword.GETNAME.getRaw()); - } - - public void clientList() { - sendCommand(CLIENT, Keyword.LIST.getRaw()); - } - - public void clientList(ClientType type) { - sendCommand(CLIENT, Keyword.LIST.getRaw(), Keyword.TYPE.getRaw(), type.getRaw()); - } - - public void clientList(final long... clientIds) { - final byte[][] params = new byte[2 + clientIds.length][]; - int index = 0; - params[index++] = Keyword.LIST.getRaw(); - params[index++] = ID.getRaw(); - for (final long clientId : clientIds) { - params[index++] = toByteArray(clientId); - } - sendCommand(CLIENT, params); - } - - public void clientInfo() { - sendCommand(CLIENT, INFO.getRaw()); - } - - public void clientSetname(final byte[] name) { - sendCommand(CLIENT, Keyword.SETNAME.getRaw(), name); - } - - public void clientPause(final long timeout) { - sendCommand(CLIENT, Keyword.PAUSE.getRaw(), toByteArray(timeout)); - } - - public void clientId() { - sendCommand(CLIENT, Keyword.ID.getRaw()); - } - - public void clientUnblock(final long clientId, final UnblockType unblockType) { - if (unblockType == null) { - sendCommand(CLIENT, Keyword.UNBLOCK.getRaw(), toByteArray(clientId)); - } else { - sendCommand(CLIENT, Keyword.UNBLOCK.getRaw(), toByteArray(clientId), unblockType.getRaw()); - } - } - - public void clientPause(final long timeout, final ClientPauseMode mode) { - sendCommand(CLIENT, Keyword.PAUSE.getRaw(), toByteArray(timeout), mode.getRaw()); - } - - public void time() { - sendCommand(TIME); - } - - public void migrate(final String host, final int port, final byte[] key, final int destinationDb, - final int timeout) { - sendCommand(MIGRATE, SafeEncoder.encode(host), toByteArray(port), key, - toByteArray(destinationDb), toByteArray(timeout)); - } - - public void migrate(final String host, final int port, final int destinationDB, - final int timeout, final MigrateParams params, final byte[]... keys) { - byte[][] bparams = params.getByteParams(); - int len = 5 + bparams.length + 1 + keys.length; - byte[][] args = new byte[len][]; - int i = 0; - args[i++] = SafeEncoder.encode(host); - args[i++] = toByteArray(port); - args[i++] = new byte[0]; - args[i++] = toByteArray(destinationDB); - args[i++] = toByteArray(timeout); - System.arraycopy(bparams, 0, args, i, bparams.length); - i += bparams.length; - args[i++] = Keyword.KEYS.getRaw(); - System.arraycopy(keys, 0, args, i, keys.length); - sendCommand(MIGRATE, args); - } - - public void hincrByFloat(final byte[] key, final byte[] field, final double increment) { - sendCommand(HINCRBYFLOAT, key, field, toByteArray(increment)); - } - - public void scan(final byte[] cursor, final ScanParams params) { - scan(cursor, params, (byte[]) null); - } - - public void scan(final byte[] cursor, final ScanParams params, final byte[] type) { - final List args = new ArrayList<>(); - args.add(cursor); - args.addAll(params.getParams()); - if (type != null) { - args.add(Keyword.TYPE.getRaw()); - args.add(type); - } - sendCommand(SCAN, args.toArray(new byte[args.size()][])); - } - - public void hscan(final byte[] key, final byte[] cursor, final ScanParams params) { - final List args = new ArrayList<>(); - args.add(key); - args.add(cursor); - args.addAll(params.getParams()); - sendCommand(HSCAN, args.toArray(new byte[args.size()][])); - } - - public void sscan(final byte[] key, final byte[] cursor, final ScanParams params) { - final List args = new ArrayList<>(); - args.add(key); - args.add(cursor); - args.addAll(params.getParams()); - sendCommand(SSCAN, args.toArray(new byte[args.size()][])); - } - - public void zscan(final byte[] key, final byte[] cursor, final ScanParams params) { - final List args = new ArrayList<>(); - args.add(key); - args.add(cursor); - args.addAll(params.getParams()); - sendCommand(ZSCAN, args.toArray(new byte[args.size()][])); - } - - public void waitReplicas(final int replicas, final long timeout) { - sendCommand(WAIT, toByteArray(replicas), toByteArray(timeout)); - } - - public void cluster(final byte[]... args) { - sendCommand(CLUSTER, args); - } - - public void cluster(Protocol.ClusterKeyword keyword, final byte[]... args) { - sendCommand(CLUSTER, joinParameters(keyword.getRaw(), args)); - } - - public void asking() { - sendCommand(ASKING); - } - - public void pfadd(final byte[] key, final byte[]... elements) { - sendCommand(PFADD, joinParameters(key, elements)); - } - - public void pfcount(final byte[] key) { - sendCommand(PFCOUNT, key); - } - - public void pfcount(final byte[]... keys) { - sendCommand(PFCOUNT, keys); - } - - public void pfmerge(final byte[] destkey, final byte[]... sourcekeys) { - sendCommand(PFMERGE, joinParameters(destkey, sourcekeys)); - } - - public void readonly() { - sendCommand(READONLY); - } - - public void readwrite() { - sendCommand(READWRITE); - } - - public void geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { - sendCommand(GEOADD, key, toByteArray(longitude), toByteArray(latitude), member); - } - - public void geoadd(final byte[] key, final Map memberCoordinateMap) { - geoadd(key, GeoAddParams.geoAddParams(), memberCoordinateMap); - } - - public void geoadd(final byte[] key, final GeoAddParams params, final Map memberCoordinateMap) { - List args = new ArrayList<>(memberCoordinateMap.size() * 3); - args.addAll(convertGeoCoordinateMapToByteArrays(memberCoordinateMap)); - - byte[][] argsArray = new byte[args.size()][]; - args.toArray(argsArray); - - sendCommand(GEOADD, params.getByteParams(key, argsArray)); - } - - public void geodist(final byte[] key, final byte[] member1, final byte[] member2) { - sendCommand(GEODIST, key, member1, member2); - } - - public void geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { - sendCommand(GEODIST, key, member1, member2, unit.raw); - } - - public void geohash(final byte[] key, final byte[]... members) { - sendCommand(GEOHASH, joinParameters(key, members)); - } - - public void geopos(final byte[] key, final byte[][] members) { - sendCommand(GEOPOS, joinParameters(key, members)); - } - - public void georadius(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit) { - sendCommand(GEORADIUS, key, toByteArray(longitude), toByteArray(latitude), toByteArray(radius), - unit.raw); - } - - public void georadiusReadonly(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit) { - sendCommand(GEORADIUS_RO, key, toByteArray(longitude), toByteArray(latitude), - toByteArray(radius), unit.raw); - } - - public void georadius(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - sendCommand(GEORADIUS, param.getByteParams(key, toByteArray(longitude), toByteArray(latitude), - toByteArray(radius), unit.raw)); - } - - public void georadiusStore(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - sendCommand(GEORADIUS, param.getByteParams(key, toByteArray(longitude), toByteArray(latitude), - toByteArray(radius), unit.raw, storeParam.getOption(), storeParam.getKey())); - } - - public void georadiusReadonly(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - sendCommand(GEORADIUS_RO, param.getByteParams(key, toByteArray(longitude), - toByteArray(latitude), toByteArray(radius), unit.raw)); - } - - public void georadiusByMember(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit) { - sendCommand(GEORADIUSBYMEMBER, key, member, toByteArray(radius), unit.raw); - } - - public void georadiusByMemberReadonly(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit) { - sendCommand(GEORADIUSBYMEMBER_RO, key, member, toByteArray(radius), unit.raw); - } - - public void georadiusByMember(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit, final GeoRadiusParam param) { - sendCommand(GEORADIUSBYMEMBER, param.getByteParams(key, member, toByteArray(radius), unit.raw)); - } - - public void georadiusByMemberStore(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit, final GeoRadiusParam param, final GeoRadiusStoreParam storeParam) { - sendCommand(GEORADIUSBYMEMBER, param.getByteParams(key, member, toByteArray(radius), unit.raw, - storeParam.getOption(), storeParam.getKey())); - } - - public void georadiusByMemberReadonly(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit, final GeoRadiusParam param) { - sendCommand(GEORADIUSBYMEMBER_RO, - param.getByteParams(key, member, toByteArray(radius), unit.raw)); - } - - public void moduleLoad(final byte[] path) { - sendCommand(MODULE, Keyword.LOAD.getRaw(), path); - } - - public void moduleList() { - sendCommand(MODULE, Keyword.LIST.getRaw()); - } - - public void moduleUnload(final byte[] name) { - sendCommand(MODULE, Keyword.UNLOAD.getRaw(), name); - } - - private ArrayList convertScoreMembersToByteArrays(final Map scoreMembers) { - ArrayList args = new ArrayList<>(scoreMembers.size() * 2); - - for (Map.Entry entry : scoreMembers.entrySet()) { - args.add(toByteArray(entry.getValue())); - args.add(entry.getKey()); - } - - return args; - } - - public void aclWhoAmI() { - sendCommand(ACL, Keyword.WHOAMI.getRaw()); - } - - public void aclGenPass() { - sendCommand(ACL, Keyword.GENPASS.getRaw()); - } - - public void aclList() { - sendCommand(ACL, Keyword.LIST.getRaw()); - } - - public void aclUsers() { - sendCommand(ACL, Keyword.USERS.getRaw()); - } - - public void aclCat() { - sendCommand(ACL, Keyword.CAT.getRaw()); - } - - public void aclCat(final byte[] category) { - sendCommand(ACL, Keyword.CAT.getRaw(), category); - } - - public void aclLog() { - sendCommand(ACL, Keyword.LOG.getRaw()); - } - - public void aclLog(int limit) { - sendCommand(ACL, Keyword.LOG.getRaw(), toByteArray(limit)); - } - - public void aclLog(final byte[] option) { - sendCommand(ACL, Keyword.LOG.getRaw(), option); - } - - public void aclSetUser(final byte[] name) { - sendCommand(ACL, Keyword.SETUSER.getRaw(), name); - } - - public void aclGetUser(final byte[] name) { - sendCommand(ACL, Keyword.GETUSER.getRaw(), name); - } - - public void aclSetUser(final byte[] name, byte[][] parameters) { - sendCommand(ACL, joinParameters(Keyword.SETUSER.getRaw(), name, parameters)); - } - - public void aclDelUser(final byte[] name) { - sendCommand(ACL, Keyword.DELUSER.getRaw(), name); - } - - public void aclLoad() { - sendCommand(ACL, Keyword.LOAD.getRaw()); - } - - public void aclSave() { - sendCommand(ACL, Keyword.SAVE.getRaw()); - } - - private List convertGeoCoordinateMapToByteArrays( - final Map memberCoordinateMap) { - List args = new ArrayList<>(memberCoordinateMap.size() * 3); - - for (Entry entry : memberCoordinateMap.entrySet()) { - GeoCoordinate coordinate = entry.getValue(); - args.add(toByteArray(coordinate.getLongitude())); - args.add(toByteArray(coordinate.getLatitude())); - args.add(entry.getKey()); - } - - return args; - } - - public void bitfield(final byte[] key, final byte[]... value) { - sendCommand(BITFIELD, joinParameters(key, value)); - } - - public void bitfieldReadonly(final byte[] key, final byte[]... arguments) { - sendCommand(BITFIELD_RO, joinParameters(key, arguments)); - } - - public void hstrlen(final byte[] key, final byte[] field) { - sendCommand(HSTRLEN, key, field); - } - - public void xadd(final byte[] key, final byte[] id, final Map hash, long maxLen, - boolean approximateLength) { - int maxLexArgs = 0; - if (maxLen < Long.MAX_VALUE) { // optional arguments - if (approximateLength) { - maxLexArgs = 3; // e.g. MAXLEN ~ 1000 - } else { - maxLexArgs = 2; // e.g. MAXLEN 1000 - } - } - - final byte[][] params = new byte[2 + maxLexArgs + hash.size() * 2][]; - int index = 0; - params[index++] = key; - if (maxLen < Long.MAX_VALUE) { - params[index++] = Keyword.MAXLEN.getRaw(); - if (approximateLength) { - params[index++] = Protocol.BYTES_TILDE; - } - params[index++] = toByteArray(maxLen); - } - - params[index++] = id; - for (final Entry entry : hash.entrySet()) { - params[index++] = entry.getKey(); - params[index++] = entry.getValue(); - } - sendCommand(XADD, params); - } - - public void xadd(final byte[] key, final Map hash, final XAddParams xAddParams) { - final byte[][] params = new byte[hash.size() * 2][]; - int index = 0; - for (final Entry entry : hash.entrySet()) { - params[index++] = entry.getKey(); - params[index++] = entry.getValue(); - } - sendCommand(XADD, xAddParams.getByteParams(key, params)); - } - - public void xlen(final byte[] key) { - sendCommand(XLEN, key); - } - - public void xrange(final byte[] key, final byte[] start, final byte[] end) { - sendCommand(XRANGE, key, start, end); - } - - /** - * @deprecated Use {@link #xrange(byte[], byte[], byte[], int)}. - */ - @Deprecated - public void xrange(final byte[] key, final byte[] start, final byte[] end, final long count) { - sendCommand(XRANGE, key, start, end, Keyword.COUNT.getRaw(), toByteArray(count)); - } - - public void xrange(final byte[] key, final byte[] start, final byte[] end, final int count) { - sendCommand(XRANGE, key, start, end, Keyword.COUNT.getRaw(), toByteArray(count)); - } - - public void xrevrange(final byte[] key, final byte[] end, final byte[] start) { - sendCommand(XREVRANGE, key, end, start); - } - - public void xrevrange(final byte[] key, final byte[] end, final byte[] start, final int count) { - sendCommand(XREVRANGE, key, end, start, Keyword.COUNT.getRaw(), toByteArray(count)); - } - - /** - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link #xread(redis.clients.jedis.params.XReadParams, java.util.Map.Entry...)}. - */ - @Deprecated - public void xread(final int count, final long block, final Map streams) { - final byte[][] params = new byte[3 + streams.size() * 2 + (block > 0 ? 2 : 0)][]; - - int streamsIndex = 0; - params[streamsIndex++] = Keyword.COUNT.getRaw(); - params[streamsIndex++] = toByteArray(count); - if (block > 0) { - params[streamsIndex++] = Keyword.BLOCK.getRaw(); - params[streamsIndex++] = toByteArray(block); - } - - params[streamsIndex++] = Keyword.STREAMS.getRaw(); - int idsIndex = streamsIndex + streams.size(); - - for (final Entry entry : streams.entrySet()) { - params[streamsIndex++] = entry.getKey(); - params[idsIndex++] = entry.getValue(); - } - - sendCommand(XREAD, params); - } - - public void xread(final XReadParams params, final Entry... streams) { - final byte[][] bparams = params.getByteParams(); - final int paramLength = bparams.length; - - final byte[][] args = new byte[paramLength + 1 + streams.length * 2][]; - System.arraycopy(bparams, 0, args, 0, paramLength); - - args[paramLength] = Keyword.STREAMS.getRaw(); - int keyIndex = paramLength + 1; - int idsIndex = keyIndex + streams.length; - for (final Entry entry : streams) { - args[keyIndex++] = entry.getKey(); - args[idsIndex++] = entry.getValue(); - } - - sendCommand(XREAD, args); - } - - public void xack(final byte[] key, final byte[] group, final byte[]... ids) { - final byte[][] params = new byte[2 + ids.length][]; - int index = 0; - params[index++] = key; - params[index++] = group; - for (final byte[] id : ids) { - params[index++] = id; - } - sendCommand(XACK, params); - } - - public void xgroupCreate(final byte[] key, final byte[] groupname, final byte[] id, - boolean makeStream) { - if (makeStream) { - sendCommand(XGROUP, Keyword.CREATE.getRaw(), key, groupname, id, Keyword.MKSTREAM.getRaw()); - } else { - sendCommand(XGROUP, Keyword.CREATE.getRaw(), key, groupname, id); - } - } - - public void xgroupSetID(final byte[] key, final byte[] groupname, final byte[] id) { - sendCommand(XGROUP, Keyword.SETID.getRaw(), key, groupname, id); - } - - public void xgroupDestroy(final byte[] key, final byte[] groupname) { - sendCommand(XGROUP, Keyword.DESTROY.getRaw(), key, groupname); - } - - public void xgroupDelConsumer(final byte[] key, final byte[] groupname, final byte[] consumerName) { - sendCommand(XGROUP, Keyword.DELCONSUMER.getRaw(), key, groupname, consumerName); - } - - public void xdel(final byte[] key, final byte[]... ids) { - final byte[][] params = new byte[1 + ids.length][]; - int index = 0; - params[index++] = key; - for (final byte[] id : ids) { - params[index++] = id; - } - sendCommand(XDEL, params); - } - - public void xtrim(byte[] key, long maxLen, boolean approximateLength) { - if (approximateLength) { - sendCommand(XTRIM, key, Keyword.MAXLEN.getRaw(), Protocol.BYTES_TILDE, toByteArray(maxLen)); - } else { - sendCommand(XTRIM, key, Keyword.MAXLEN.getRaw(), toByteArray(maxLen)); - } - } - - public void xtrim(byte[] key, XTrimParams params) { - sendCommand(XTRIM, params.getByteParams(key)); - } - - /** - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link BinaryClient#xreadGroup(byte..., byte..., redis.clients.jedis.params.XReadGroupParams, java.util.Map.Entry...)}. - */ - @Deprecated - public void xreadGroup(byte[] groupname, byte[] consumer, int count, long block, boolean noAck, - Map streams) { - - int optional = 0; - if (count > 0) { - optional += 2; - } - if (block > 0) { - optional += 2; - } - if (noAck) { - optional += 1; - } - - final byte[][] params = new byte[4 + optional + streams.size() * 2][]; - - int streamsIndex = 0; - params[streamsIndex++] = Keyword.GROUP.getRaw(); - params[streamsIndex++] = groupname; - params[streamsIndex++] = consumer; - if (count > 0) { - params[streamsIndex++] = Keyword.COUNT.getRaw(); - params[streamsIndex++] = toByteArray(count); - } - if (block > 0) { - params[streamsIndex++] = Keyword.BLOCK.getRaw(); - params[streamsIndex++] = toByteArray(block); - } - if (noAck) { - params[streamsIndex++] = Keyword.NOACK.getRaw(); - } - params[streamsIndex++] = Keyword.STREAMS.getRaw(); - - int idsIndex = streamsIndex + streams.size(); - for (final Entry entry : streams.entrySet()) { - params[streamsIndex++] = entry.getKey(); - params[idsIndex++] = entry.getValue(); - } - - sendCommand(XREADGROUP, params); - } - - public void xreadGroup(byte[] groupname, byte[] consumer, final XReadGroupParams params, - final Entry... streams) { - final byte[][] bparams = params.getByteParams(); - final int paramLength = bparams.length; - - final byte[][] args = new byte[3 + paramLength + 1 + streams.length * 2][]; - int index = 0; - args[index++] = Keyword.GROUP.getRaw(); - args[index++] = groupname; - args[index++] = consumer; - System.arraycopy(bparams, 0, args, index, paramLength); - index += paramLength; - - args[index++] = Keyword.STREAMS.getRaw(); - int keyIndex = index; - int idsIndex = keyIndex + streams.length; - for (final Entry entry : streams) { - args[keyIndex++] = entry.getKey(); - args[idsIndex++] = entry.getValue(); - } - - sendCommand(XREADGROUP, args); - } - - public void xpending(final byte[] key, final byte[] groupname) { - sendCommand(XPENDING, key, groupname); - } - - public void xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, - byte[] consumername) { - if (consumername == null) { - sendCommand(XPENDING, key, groupname, start, end, toByteArray(count)); - } else { - sendCommand(XPENDING, key, groupname, start, end, toByteArray(count), consumername); - } - } - - public void xpending(byte[] key, byte[] groupname, XPendingParams params) { - sendCommand(XPENDING, joinParameters(key, groupname, params.getByteParams())); - } - - public void xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, byte[][] ids) { - - List arguments = new ArrayList<>(10 + ids.length); - - arguments.add(key); - arguments.add(groupname); - arguments.add(consumername); - arguments.add(toByteArray(minIdleTime)); - - Collections.addAll(arguments, ids); - - if (newIdleTime > 0) { - arguments.add(Keyword.IDLE.getRaw()); - arguments.add(toByteArray(newIdleTime)); - } - if (retries > 0) { - arguments.add(Keyword.RETRYCOUNT.getRaw()); - arguments.add(toByteArray(retries)); - } - if (force) { - arguments.add(Keyword.FORCE.getRaw()); - } - sendCommand(XCLAIM, arguments.toArray(new byte[arguments.size()][])); - } - - private void xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, - XClaimParams params, byte[][] ids, boolean justId) { - final byte[][] bparams = params.getByteParams(); - final int paramLength = bparams.length; - final int idsLength = ids.length; - final byte[][] args = new byte[4 + paramLength + idsLength + (justId ? 1 : 0)][]; - int index = 0; - args[index++] = key; - args[index++] = groupname; - args[index++] = consumername; - args[index++] = toByteArray(minIdleTime); - System.arraycopy(ids, 0, args, index, idsLength); - index += idsLength; - System.arraycopy(bparams, 0, args, index, paramLength); - index += paramLength; - if (justId) { - args[index++] = Keyword.JUSTID.getRaw(); - } - sendCommand(XCLAIM, args); - } - - public void xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - xclaim(key, groupname, consumername, minIdleTime, params, ids, false); - } - - public void xclaimJustId(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - xclaim(key, groupname, consumername, minIdleTime, params, ids, true); - } - - public void xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - xautoclaim(key, groupName, consumerName, minIdleTime, start, params, false); - } - - private void xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params, boolean justId) { - List arguments = new ArrayList<>(); - - arguments.add(key); - arguments.add(groupName); - arguments.add(consumerName); - arguments.add(toByteArray(minIdleTime)); - arguments.add(start); - Collections.addAll(arguments, params.getByteParams()); - - if (justId) { - arguments.add(Keyword.JUSTID.getRaw()); - } - - sendCommand(XAUTOCLAIM, arguments.toArray(new byte[arguments.size()][])); - } - - public void xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - xautoclaim(key, groupName, consumerName, minIdleTime, start, params, true); - } - - public void xinfoStream(byte[] key) { - sendCommand(XINFO, Keyword.STREAM.getRaw(), key); - } - - public void xinfoGroup(byte[] key) { - sendCommand(XINFO, Keyword.GROUPS.getRaw(), key); - } - - public void xinfoConsumers(byte[] key, byte[] group) { - sendCommand(XINFO, Keyword.CONSUMERS.getRaw(), key, group); - } - - private static byte[][] joinParameters(byte[] first, byte[][] rest) { - byte[][] result = new byte[rest.length + 1][]; - result[0] = first; - System.arraycopy(rest, 0, result, 1, rest.length); - return result; - } - - private static byte[][] joinParameters(byte[] first, byte[] second, byte[][] rest) { - byte[][] result = new byte[rest.length + 2][]; - result[0] = first; - result[1] = second; - System.arraycopy(rest, 0, result, 2, rest.length); - return result; - } -} diff --git a/src/main/java/redis/clients/jedis/BinaryJedis.java b/src/main/java/redis/clients/jedis/BinaryJedis.java deleted file mode 100644 index 2e70188813..0000000000 --- a/src/main/java/redis/clients/jedis/BinaryJedis.java +++ /dev/null @@ -1,5061 +0,0 @@ -package redis.clients.jedis; - -import static redis.clients.jedis.Protocol.toByteArray; - -import java.io.Closeable; -import java.io.Serializable; -import java.net.URI; -import java.util.AbstractMap; -import java.util.AbstractSet; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - -import redis.clients.jedis.args.*; -import redis.clients.jedis.commands.AdvancedBinaryJedisCommands; -import redis.clients.jedis.commands.BasicCommands; -import redis.clients.jedis.commands.BinaryJedisCommands; -import redis.clients.jedis.commands.BinaryScriptingCommands; -import redis.clients.jedis.commands.MultiKeyBinaryCommands; -import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.exceptions.InvalidURIException; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.LCSMatchResult; -import redis.clients.jedis.util.JedisURIHelper; - -public class BinaryJedis implements BasicCommands, BinaryJedisCommands, MultiKeyBinaryCommands, - AdvancedBinaryJedisCommands, BinaryScriptingCommands, Closeable { - - protected final Client client; - protected Transaction transaction = null; - protected Pipeline pipeline = null; - protected static final byte[][] DUMMY_ARRAY = new byte[0][]; - - public BinaryJedis() { - client = new Client(); - } - - /** - * @deprecated This constructor will not support a host string in future. It will accept only a - * uri string. {@link JedisURIHelper#isValid(java.net.URI)} can used before this. If this - * constructor was being used with a host, it can be replaced with - * {@link #BinaryJedis(java.lang.String, int)} with the host and {@link Protocol#DEFAULT_PORT}. - * @param uriString - */ - @Deprecated - public BinaryJedis(final String uriString) { - URI uri = URI.create(uriString); - if (JedisURIHelper.isValid(uri)) { - client = createClientFromURI(uri); - initializeFromURI(uri); - } else { - client = new Client(uriString); - } - } - - public BinaryJedis(final HostAndPort hp) { - this(hp, DefaultJedisClientConfig.builder().build()); - } - - public BinaryJedis(final String host, final int port) { - client = new Client(host, port); - } - - public BinaryJedis(final String host, final int port, final JedisClientConfig config) { - this(new HostAndPort(host, port), config); - } - - public BinaryJedis(final HostAndPort hostPort, final JedisClientConfig config) { - client = new Client(hostPort, config); - initializeFromClientConfig(config); - } - - private void initializeFromClientConfig(JedisClientConfig config) { - try { - connect(); - String password = config.getPassword(); - if (password != null) { - String user = config.getUser(); - if (user != null) { - auth(user, password); - } else { - auth(password); - } - } - int dbIndex = config.getDatabase(); - if (dbIndex > 0) { - select(dbIndex); - } - String clientName = config.getClientName(); - if (clientName != null) { - // TODO: need to figure out something without encoding - clientSetname(redis.clients.jedis.util.SafeEncoder.encode(clientName)); - } - } catch (JedisException je) { - try { - if (isConnected()) { - quit(); - } - disconnect(); - } catch (RuntimeException e) { - // - } - throw je; - } - } - - public BinaryJedis(final String host, final int port, final boolean ssl) { - this(host, port, DefaultJedisClientConfig.builder().ssl(ssl).build()); - } - - public BinaryJedis(final String host, final int port, final boolean ssl, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - this(host, port, DefaultJedisClientConfig.builder().ssl(ssl) - .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) - .hostnameVerifier(hostnameVerifier).build()); - } - - public BinaryJedis(final String host, final int port, final int timeout) { - this(host, port, timeout, timeout); - } - - public BinaryJedis(final String host, final int port, final int timeout, final boolean ssl) { - this(host, port, timeout, timeout, ssl); - } - - public BinaryJedis(final String host, final int port, final int timeout, final boolean ssl, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - this(host, port, timeout, timeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - } - - public BinaryJedis(final String host, final int port, final int connectionTimeout, - final int soTimeout) { - this(host, port, DefaultJedisClientConfig.builder() - .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).build()); - } - - public BinaryJedis(final String host, final int port, final int connectionTimeout, - final int soTimeout, final int infiniteSoTimeout) { - this(host, port, DefaultJedisClientConfig.builder() - .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) - .blockingSocketTimeoutMillis(infiniteSoTimeout).build()); - } - - public BinaryJedis(final String host, final int port, final int connectionTimeout, - final int soTimeout, final boolean ssl) { - this(host, port, DefaultJedisClientConfig.builder() - .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl) - .build()); - } - - public BinaryJedis(final String host, final int port, final int connectionTimeout, - final int soTimeout, final boolean ssl, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(host, port, DefaultJedisClientConfig.builder() - .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl) - .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) - .hostnameVerifier(hostnameVerifier).build()); - } - - public BinaryJedis(final String host, final int port, final int connectionTimeout, - final int soTimeout, final int infiniteSoTimeout, final boolean ssl, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - this(host, port, DefaultJedisClientConfig.builder() - .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) - .blockingSocketTimeoutMillis(infiniteSoTimeout).ssl(ssl) - .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) - .hostnameVerifier(hostnameVerifier).build()); - } - - public BinaryJedis(final JedisShardInfo shardInfo) { - this(shardInfo.getHost(), shardInfo.getPort(), DefaultJedisClientConfig.builder() - .connectionTimeoutMillis(shardInfo.getConnectionTimeout()) - .socketTimeoutMillis(shardInfo.getSoTimeout()).user(shardInfo.getUser()) - .password(shardInfo.getPassword()).database(shardInfo.getDb()) - .ssl(shardInfo.getSsl()).sslSocketFactory(shardInfo.getSslSocketFactory()) - .sslParameters(shardInfo.getSslParameters()) - .hostnameVerifier(shardInfo.getHostnameVerifier()).build()); - } - - public BinaryJedis(URI uri) { - client = createClientFromURI(uri); - initializeFromURI(uri); - } - - public BinaryJedis(URI uri, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(uri, DefaultJedisClientConfig.builder().sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); - } - - public BinaryJedis(final URI uri, final int timeout) { - this(uri, timeout, timeout); - } - - public BinaryJedis(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); - } - - public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout) { - this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).build()); - } - - public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); - } - - public BinaryJedis(final URI uri, final int connectionTimeout, final int soTimeout, - final int infiniteSoTimeout, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) - .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) - .hostnameVerifier(hostnameVerifier).build()); - } - - public BinaryJedis(final URI uri, JedisClientConfig config) { - if (!JedisURIHelper.isValid(uri)) { - throw new InvalidURIException(String.format( - "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); - } - client = new Client(new HostAndPort(uri.getHost(), uri.getPort()), DefaultJedisClientConfig - .builder().connectionTimeoutMillis(config.getConnectionTimeoutMillis()) - .socketTimeoutMillis(config.getSocketTimeoutMillis()) - .blockingSocketTimeoutMillis(config.getBlockingSocketTimeoutMillis()) - .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) - .database(JedisURIHelper.getDBIndex(uri)).clientName(config.getClientName()) - .ssl(JedisURIHelper.isRedisSSLScheme(uri)) - .sslSocketFactory(config.getSslSocketFactory()) - .sslParameters(config.getSslParameters()) - .hostnameVerifier(config.getHostnameVerifier()).build()); - initializeFromURI(uri); - } - - private static Client createClientFromURI(URI uri) { - if (!JedisURIHelper.isValid(uri)) { - throw new InvalidURIException(String.format( - "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); - } - return new Client(new HostAndPort(uri.getHost(), uri.getPort()), DefaultJedisClientConfig - .builder().ssl(JedisURIHelper.isRedisSSLScheme(uri)).build()); - } - - private void initializeFromURI(URI uri) { - String password = JedisURIHelper.getPassword(uri); - if (password != null) { - String user = JedisURIHelper.getUser(uri); - if (user != null) { - auth(user, password); - } else { - auth(password); - } - } - int dbIndex = JedisURIHelper.getDBIndex(uri); - if (dbIndex > 0) { - select(dbIndex); - } - } - - /** - * @deprecated This constructor will be removed in future major release. - * - * Use {@link BinaryJedis#BinaryJedis(redis.clients.jedis.JedisSocketFactory, redis.clients.jedis.JedisClientConfig)}. - */ - @Deprecated - public BinaryJedis(final JedisSocketFactory jedisSocketFactory) { - client = new Client(jedisSocketFactory); - } - - public BinaryJedis(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) { - client = new Client(jedisSocketFactory); - initializeFromClientConfig(clientConfig); - } - - @Override - public String toString() { - return "BinaryJedis{" + client + '}'; - } - - public boolean isConnected() { - return client.isConnected(); - } - - public boolean isBroken() { - return client.isBroken(); - } - - public void connect() { - client.connect(); - } - - public void disconnect() { - client.disconnect(); - } - - public void resetState() { - if (isConnected()) { - if (transaction != null) { - transaction.close(); - } - - if (pipeline != null) { - pipeline.close(); - } - - client.resetState(); - } - - transaction = null; - pipeline = null; - } - - @Override - public void close() { - client.close(); - } - - @Override - public int getDB() { - return client.getDB(); - } - - /** - * COPY source destination [DB destination-db] [REPLACE] - * - * @param srcKey the source key. - * @param dstKey the destination key. - * @param db - * @param replace - */ - @Override - public boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) { - checkIsInMultiOrPipeline(); - client.copy(srcKey, dstKey, db, replace); - return BuilderFactory.BOOLEAN.build(client.getOne()); - } - - /** - * COPY source destination [DB destination-db] [REPLACE] - * - * @param srcKey the source key. - * @param dstKey the destination key. - * @param replace - */ - @Override - public boolean copy(byte[] srcKey, byte[] dstKey, boolean replace) { - checkIsInMultiOrPipeline(); - client.copy(srcKey, dstKey, replace); - return BuilderFactory.BOOLEAN.build(client.getOne()); - } - - /** - * @return PONG - */ - @Override - public String ping() { - checkIsInMultiOrPipeline(); - client.ping(); - return client.getStatusCodeReply(); - } - - /** - * Works same as {@link #ping()} but returns argument message instead of PONG. - * @param message - * @return message - */ - public byte[] ping(final byte[] message) { - checkIsInMultiOrPipeline(); - client.ping(message); - return client.getBinaryBulkReply(); - } - - /** - * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 - * GB). - *

- * Time complexity: O(1) - * @param key - * @param value - * @return Status code reply - */ - @Override - public String set(final byte[] key, final byte[] value) { - checkIsInMultiOrPipeline(); - client.set(key, value); - return client.getStatusCodeReply(); - } - - /** - * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 - * GB). - * @param key - * @param value - * @param params - * @return Status code reply - */ - @Override - public String set(final byte[] key, final byte[] value, final SetParams params) { - checkIsInMultiOrPipeline(); - client.set(key, value, params); - return client.getStatusCodeReply(); - } - - /** - * Get the value of the specified key. If the key does not exist the special value 'nil' is - * returned. If the value stored at key is not a string an error is returned because GET can only - * handle string values. - *

- * Time complexity: O(1) - * @param key - * @return Bulk reply - */ - @Override - public byte[] get(final byte[] key) { - checkIsInMultiOrPipeline(); - client.get(key); - return client.getBinaryBulkReply(); - } - - /** - * Get the value of key and delete the key. This command is similar to GET, except for the fact - * that it also deletes the key on success (if and only if the key's value type is a string). - *

- * Time complexity: O(1) - * @param key - * @return the value of key - * @since Redis 6.2 - */ - @Override - public byte[] getDel(final byte[] key) { - checkIsInMultiOrPipeline(); - client.getDel(key); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] getEx(final byte[] key, final GetExParams params) { - checkIsInMultiOrPipeline(); - client.getEx(key, params); - return client.getBinaryBulkReply(); - } - - /** - * Ask the server to silently close the connection. - */ - @Override - public String quit() { - checkIsInMultiOrPipeline(); - client.quit(); - String quitReturn = client.getStatusCodeReply(); - client.disconnect(); - return quitReturn; - } - - /** - * Test if the specified keys exist. The command returns the number of keys exist. - * Time complexity: O(N) - * @param keys - * @return Integer reply, specifically: an integer greater than 0 if one or more keys exist, - * 0 if none of the specified keys exist. - */ - @Override - public long exists(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.exists(keys); - return client.getIntegerReply(); - } - - /** - * Test if the specified key exists. The command returns true if the key exists, otherwise false is - * returned. Note that even keys set with an empty string as value will return true. Time - * complexity: O(1) - * @param key - * @return Boolean reply, true if the key exists, otherwise false - */ - @Override - public boolean exists(final byte[] key) { - checkIsInMultiOrPipeline(); - client.exists(key); - return client.getIntegerReply() == 1; - } - - /** - * Remove the specified keys. If a given key does not exist no operation is performed for this - * key. The command returns the number of keys removed. Time complexity: O(1) - * @param keys - * @return Integer reply, specifically: an integer greater than 0 if one or more keys were removed - * 0 if none of the specified key existed - */ - @Override - public long del(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.del(keys); - return client.getIntegerReply(); - } - - @Override - public long del(final byte[] key) { - checkIsInMultiOrPipeline(); - client.del(key); - return client.getIntegerReply(); - } - - /** - * This command is very similar to DEL: it removes the specified keys. Just like DEL a key is - * ignored if it does not exist. However the command performs the actual memory reclaiming in a - * different thread, so it is not blocking, while DEL is. This is where the command name comes - * from: the command just unlinks the keys from the keyspace. The actual removal will happen later - * asynchronously. - *

- * Time complexity: O(1) for each key removed regardless of its size. Then the command does O(N) - * work in a different thread in order to reclaim memory, where N is the number of allocations the - * deleted objects where composed of. - * @param keys - * @return Integer reply: The number of keys that were unlinked - */ - @Override - public long unlink(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.unlink(keys); - return client.getIntegerReply(); - } - - @Override - public long unlink(final byte[] key) { - checkIsInMultiOrPipeline(); - client.unlink(key); - return client.getIntegerReply(); - } - - /** - * Return the type of the value stored at key in form of a string. The type can be one of "none", - * "string", "list", "set". "none" is returned if the key does not exist. Time complexity: O(1) - * @param key - * @return Status code reply, specifically: "none" if the key does not exist "string" if the key - * contains a String value "list" if the key contains a List value "set" if the key - * contains a Set value "zset" if the key contains a Sorted Set value "hash" if the key - * contains a Hash value - */ - @Override - public String type(final byte[] key) { - checkIsInMultiOrPipeline(); - client.type(key); - return client.getStatusCodeReply(); - } - - /** - * Delete all the keys of the currently selected DB. This command never fails. - * @return Status code reply - */ - @Override - public String flushDB() { - checkIsInMultiOrPipeline(); - client.flushDB(); - return client.getStatusCodeReply(); - } - - /** - * Delete all the keys of the currently selected DB. This command never fails. - * @param flushMode - * @return Status code reply - */ - @Override - public String flushDB(FlushMode flushMode) { - checkIsInMultiOrPipeline(); - client.flushDB(flushMode); - return client.getStatusCodeReply(); - } - - /** - * Returns all the keys matching the glob-style pattern as space separated strings. For example if - * you have in the database the keys "foo" and "foobar" the command "KEYS foo*" will return - * "foo foobar". - *

- * Note that while the time complexity for this operation is O(n) the constant times are pretty - * low. For example Redis running on an entry level laptop can scan a 1 million keys database in - * 40 milliseconds. Still it's better to consider this one of the slow commands that may ruin - * the DB performance if not used with care. - *

- * In other words this command is intended only for debugging and special operations like creating - * a script to change the DB schema. Don't use it in your normal code. Use Redis Sets in order to - * group together a subset of objects. - *

- * Glob style patterns examples: - *

    - *
  • h?llo will match hello hallo hhllo - *
  • h*llo will match hllo heeeello - *
  • h[ae]llo will match hello and hallo, but not hillo - *
- *

- * Use \ to escape special chars if you want to match them verbatim. - *

- * Time complexity: O(n) (with n being the number of keys in the DB, and assuming keys and pattern - * of limited length) - * @param pattern - * @return Multi bulk reply - */ - @Override - public Set keys(final byte[] pattern) { - checkIsInMultiOrPipeline(); - client.keys(pattern); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * Return a randomly selected key from the currently selected DB. - *

- * Time complexity: O(1) - * @return Single line reply, specifically the randomly selected key or an empty string is the - * database is empty - */ - @Override - public byte[] randomBinaryKey() { - checkIsInMultiOrPipeline(); - client.randomKey(); - return client.getBinaryBulkReply(); - } - - /** - * Atomically renames the key oldkey to newkey. If the source and destination name are the same an - * error is returned. If newkey already exists it is overwritten. - *

- * Time complexity: O(1) - * @param oldkey - * @param newkey - * @return Status code reply - */ - @Override - public String rename(final byte[] oldkey, final byte[] newkey) { - checkIsInMultiOrPipeline(); - client.rename(oldkey, newkey); - return client.getStatusCodeReply(); - } - - /** - * Rename oldkey into newkey but fails if the destination key newkey already exists. - *

- * Time complexity: O(1) - * @param oldkey - * @param newkey - * @return Integer reply, specifically: 1 if the key was renamed 0 if the target key already exist - */ - @Override - public long renamenx(final byte[] oldkey, final byte[] newkey) { - checkIsInMultiOrPipeline(); - client.renamenx(oldkey, newkey); - return client.getIntegerReply(); - } - - /** - * Return the number of keys in the currently selected database. - * @return Integer reply - */ - @Override - public long dbSize() { - checkIsInMultiOrPipeline(); - client.dbSize(); - return client.getIntegerReply(); - } - - /** - * Set a timeout on the specified key. After the timeout the key will be automatically deleted by - * the server. A key with an associated timeout is said to be volatile in Redis terminology. - *

- * Volatile keys are stored on disk like the other keys, the timeout is persistent too like all the - * other aspects of the dataset. Saving a dataset containing expires and stopping the server does - * not stop the flow of time as Redis stores on disk the time when the key will no longer be - * available as Unix time, and not the remaining seconds. - *

- * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire - * set. It is also possible to undo the expire at all turning the key into a normal key using the - * {@link #persist(byte[]) PERSIST} command. - *

- * Time complexity: O(1) - * @see Expire Command - * @param key - * @param seconds - * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since - * the key already has an associated timeout (this may happen only in Redis versions < - * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. - */ - @Override - public long expire(final byte[] key, final long seconds) { - checkIsInMultiOrPipeline(); - client.expire(key, seconds); - return client.getIntegerReply(); - } - - /** - * EXPIREAT works exactly like {@link #expire(byte[], int) EXPIRE} but instead to get the number of - * seconds representing the Time To Live of the key as a second argument (that is a relative way - * of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of - * seconds elapsed since 1 Gen 1970). - *

- * EXPIREAT was introduced in order to implement the Append Only File persistence mode so that - * EXPIRE commands are automatically translated into EXPIREAT commands for the append only file. - * Of course EXPIREAT can also used by programmers that need a way to simply specify that a given - * key should expire at a given time in the future. - *

- * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire - * set. It is also possible to undo the expire at all turning the key into a normal key using the - * {@link #persist(byte[]) PERSIST} command. - *

- * Time complexity: O(1) - * @see Expire Command - * @param key - * @param unixTime - * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since - * the key already has an associated timeout (this may happen only in Redis versions < - * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. - */ - @Override - public long expireAt(final byte[] key, final long unixTime) { - checkIsInMultiOrPipeline(); - client.expireAt(key, unixTime); - return client.getIntegerReply(); - } - - /** - * The TTL command returns the remaining time to live in seconds of a key that has an - * {@link #expire(byte[], int) EXPIRE} set. This introspection capability allows a Redis client to - * check how many seconds a given key will continue to be part of the dataset. - * @param key - * @return Integer reply, returns the remaining time to live in seconds of a key that has an - * EXPIRE. If the Key does not exists or does not have an associated expire, -1 is - * returned. - */ - @Override - public long ttl(final byte[] key) { - checkIsInMultiOrPipeline(); - client.ttl(key); - return client.getIntegerReply(); - } - - /** - * Alters the last access time of a key(s). A key is ignored if it does not exist. - * Time complexity: O(N) where N is the number of keys that will be touched. - * @param keys - * @return Integer reply: The number of keys that were touched. - */ - @Override - public long touch(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.touch(keys); - return client.getIntegerReply(); - } - - @Override - public long touch(final byte[] key) { - checkIsInMultiOrPipeline(); - client.touch(key); - return client.getIntegerReply(); - } - - /** - * Select the DB with having the specified zero-based numeric index. For default every new client - * connection is automatically selected to DB 0. - * @param index - * @return Status code reply - */ - @Override - public String select(final int index) { - checkIsInMultiOrPipeline(); - client.select(index); - String statusCodeReply = client.getStatusCodeReply(); - client.setDb(index); - - return statusCodeReply; - } - - @Override - public String swapDB(final int index1, final int index2) { - checkIsInMultiOrPipeline(); - client.swapDB(index1, index2); - return client.getStatusCodeReply(); - } - - /** - * Move the specified key from the currently selected DB to the specified destination DB. Note - * that this command returns 1 only if the key was successfully moved, and 0 if the target key was - * already there or if the source key was not found at all, so it is possible to use MOVE as a - * locking primitive. - * @param key - * @param dbIndex - * @return Integer reply, specifically: 1 if the key was moved 0 if the key was not moved because - * already present on the target DB or was not found in the current DB. - */ - @Override - public long move(final byte[] key, final int dbIndex) { - checkIsInMultiOrPipeline(); - client.move(key, dbIndex); - return client.getIntegerReply(); - } - - /** - * Delete all the keys of all the existing databases, not just the currently selected one. This - * command never fails. - * @return Status code reply - */ - @Override - public String flushAll() { - checkIsInMultiOrPipeline(); - client.flushAll(); - return client.getStatusCodeReply(); - } - - /** - * Delete all the keys of all the existing databases, not just the currently selected one. This - * command never fails. - * @param flushMode - * @return Status code reply - */ - @Override - public String flushAll(FlushMode flushMode) { - checkIsInMultiOrPipeline(); - client.flushAll(flushMode); - return client.getStatusCodeReply(); - } - - /** - * GETSET is an atomic set this value and return the old value command. Set key to the string - * value and return the old value stored at key. The string can't be longer than 1073741824 bytes - * (1 GB). - *

- * Time complexity: O(1) - * @param key - * @param value - * @return Bulk reply - */ - @Override - public byte[] getSet(final byte[] key, final byte[] value) { - checkIsInMultiOrPipeline(); - client.getSet(key, value); - return client.getBinaryBulkReply(); - } - - /** - * Get the values of all the specified keys. If one or more keys don't exist or is not of type - * String, a 'nil' value is returned instead of the value of the specified key, but the operation - * never fails. - *

- * Time complexity: O(1) for every key - * @param keys - * @return Multi bulk reply - */ - @Override - public List mget(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.mget(keys); - return client.getBinaryMultiBulkReply(); - } - - /** - * SETNX works exactly like {@link #set(byte[], byte[]) SET} with the only difference that if the - * key already exists no operation is performed. SETNX actually means "SET if Not eXists". - *

- * Time complexity: O(1) - * @param key - * @param value - * @return Integer reply, specifically: 1 if the key was set 0 if the key was not set - */ - @Override - public long setnx(final byte[] key, final byte[] value) { - checkIsInMultiOrPipeline(); - client.setnx(key, value); - return client.getIntegerReply(); - } - - /** - * The command is exactly equivalent to the following group of commands: - * {@link #set(byte[], byte[]) SET} + {@link #expire(byte[], int) EXPIRE}. The operation is - * atomic. - *

- * Time complexity: O(1) - * @param key - * @param seconds - * @param value - * @return Status code reply - */ - @Override - public String setex(final byte[] key, final long seconds, final byte[] value) { - checkIsInMultiOrPipeline(); - client.setex(key, seconds, value); - return client.getStatusCodeReply(); - } - - /** - * Set the the respective keys to the respective values. MSET will replace old values with new - * values, while {@link BinaryJedis#msetnx(byte[]...) MSETNX} will not perform any operation at all even if - * just a single key already exists. - *

- * Because of this semantic MSETNX can be used in order to set different keys representing - * different fields of an unique logic object in a way that ensures that either all the fields or - * none at all are set. - *

- * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B - * are modified, another client talking to Redis can either see the changes to both A and B at - * once, or no modification at all. - * @see BinaryJedis#msetnx(byte[]...) - * @param keysvalues - * @return Status code reply Basically +OK as MSET can't fail - */ - @Override - public String mset(final byte[]... keysvalues) { - checkIsInMultiOrPipeline(); - client.mset(keysvalues); - return client.getStatusCodeReply(); - } - - /** - * Set the the respective keys to the respective values. {@link BinaryJedis#mset(byte[]...) MSET} will - * replace old values with new values, while MSETNX will not perform any operation at all even if - * just a single key already exists. - *

- * Because of this semantic MSETNX can be used in order to set different keys representing - * different fields of an unique logic object in a way that ensures that either all the fields or - * none at all are set. - *

- * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B - * are modified, another client talking to Redis can either see the changes to both A and B at - * once, or no modification at all. - * @see BinaryJedis#mset(byte[]...) - * @param keysvalues - * @return Integer reply, specifically: 1 if the all the keys were set 0 if no key was set (at - * least one key already existed) - */ - @Override - public long msetnx(final byte[]... keysvalues) { - checkIsInMultiOrPipeline(); - client.msetnx(keysvalues); - return client.getIntegerReply(); - } - - /** - * DECRBY work just like {@link #decr(byte[]) INCR} but instead to decrement by 1 the decrement is - * integer. - *

- * INCR commands are limited to 64 bit signed integers. - *

- * Note: this is actually a string operation, that is, in Redis there are not "integer" types. - * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, - * and then converted back as a string. - *

- * Time complexity: O(1) - * @see #incr(byte[]) - * @see #decr(byte[]) - * @see #incrBy(byte[], long) - * @param key - * @param decrement - * @return Integer reply, this commands will reply with the new value of key after the increment. - */ - @Override - public long decrBy(final byte[] key, final long decrement) { - checkIsInMultiOrPipeline(); - client.decrBy(key, decrement); - return client.getIntegerReply(); - } - - /** - * Decrement the number stored at key by one. If the key does not exist or contains a value of a - * wrong type, set the key to the value of "0" before to perform the decrement operation. - *

- * INCR commands are limited to 64 bit signed integers. - *

- * Note: this is actually a string operation, that is, in Redis there are not "integer" types. - * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, - * and then converted back as a string. - *

- * Time complexity: O(1) - * @see #incr(byte[]) - * @see #incrBy(byte[], long) - * @see #decrBy(byte[], long) - * @param key - * @return Integer reply, this commands will reply with the new value of key after the increment. - */ - @Override - public long decr(final byte[] key) { - checkIsInMultiOrPipeline(); - client.decr(key); - return client.getIntegerReply(); - } - - /** - * INCRBY work just like {@link #incr(byte[]) INCR} but instead to increment by 1 the increment is - * integer. - *

- * INCR commands are limited to 64 bit signed integers. - *

- * Note: this is actually a string operation, that is, in Redis there are not "integer" types. - * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, - * and then converted back as a string. - *

- * Time complexity: O(1) - * @see #incr(byte[]) - * @see #decr(byte[]) - * @see #decrBy(byte[], long) - * @param key - * @param increment - * @return Integer reply, this commands will reply with the new value of key after the increment. - */ - @Override - public long incrBy(final byte[] key, final long increment) { - checkIsInMultiOrPipeline(); - client.incrBy(key, increment); - return client.getIntegerReply(); - } - - /** - * INCRBYFLOAT work just like {@link #incrBy(byte[], long)} INCRBY} but increments by floats - * instead of integers. - *

- * INCRBYFLOAT commands are limited to double precision floating point values. - *

- * Note: this is actually a string operation, that is, in Redis there are not "double" types. - * Simply the string stored at the key is parsed as a base double precision floating point value, - * incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a - * negative value will work as expected. - *

- * Time complexity: O(1) - * @see #incr(byte[]) - * @see #decr(byte[]) - * @see #decrBy(byte[], long) - * @param key the key to increment - * @param increment the value to increment by - * @return Integer reply, this commands will reply with the new value of key after the increment. - */ - @Override - public double incrByFloat(final byte[] key, final double increment) { - checkIsInMultiOrPipeline(); - client.incrByFloat(key, increment); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - /** - * Increment the number stored at key by one. If the key does not exist or contains a value of a - * wrong type, set the key to the value of "0" before to perform the increment operation. - *

- * INCR commands are limited to 64 bit signed integers. - *

- * Note: this is actually a string operation, that is, in Redis there are not "integer" types. - * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, - * and then converted back as a string. - *

- * Time complexity: O(1) - * @see #incrBy(byte[], long) - * @see #decr(byte[]) - * @see #decrBy(byte[], long) - * @param key - * @return Integer reply, this commands will reply with the new value of key after the increment. - */ - @Override - public long incr(final byte[] key) { - checkIsInMultiOrPipeline(); - client.incr(key); - return client.getIntegerReply(); - } - - /** - * If the key already exists and is a string, this command appends the provided value at the end - * of the string. If the key does not exist it is created and set as an empty string, so APPEND - * will be very similar to SET in this special case. - *

- * Time complexity: O(1). The amortized time complexity is O(1) assuming the appended value is - * small and the already present value is of any size, since the dynamic string library used by - * Redis will double the free space available on every reallocation. - * @param key - * @param value - * @return Integer reply, specifically the total length of the string after the append operation. - */ - @Override - public long append(final byte[] key, final byte[] value) { - checkIsInMultiOrPipeline(); - client.append(key, value); - return client.getIntegerReply(); - } - - /** - * Return a subset of the string from offset start to offset end (both offsets are inclusive). - * Negative offsets can be used in order to provide an offset starting from the end of the string. - * So -1 means the last char, -2 the penultimate and so forth. - *

- * The function handles out of range requests without raising an error, but just limiting the - * resulting range to the actual length of the string. - *

- * Time complexity: O(start+n) (with start being the start index and n the total length of the - * requested range). Note that the lookup part of this command is O(1) so for small strings this - * is actually an O(1) command. - * @param key - * @param start - * @param end - * @return Bulk reply - */ - @Override - public byte[] substr(final byte[] key, final int start, final int end) { - checkIsInMultiOrPipeline(); - client.substr(key, start, end); - return client.getBinaryBulkReply(); - } - - /** - * Set the specified hash field to the specified value. - *

- * If key does not exist, a new key holding a hash is created. - *

- * Time complexity: O(1) - * @param key - * @param field - * @param value - * @return If the field already exists, and the HSET just produced an update of the value, 0 is - * returned, otherwise if a new field is created 1 is returned. - */ - @Override - public long hset(final byte[] key, final byte[] field, final byte[] value) { - checkIsInMultiOrPipeline(); - client.hset(key, field, value); - return client.getIntegerReply(); - } - - @Override - public long hset(final byte[] key, final Map hash) { - checkIsInMultiOrPipeline(); - client.hset(key, hash); - return client.getIntegerReply(); - } - - /** - * If key holds a hash, retrieve the value associated to the specified field. - *

- * If the field is not found or the key does not exist, a special 'nil' value is returned. - *

- * Time complexity: O(1) - * @param key - * @param field - * @return Bulk reply - */ - @Override - public byte[] hget(final byte[] key, final byte[] field) { - checkIsInMultiOrPipeline(); - client.hget(key, field); - return client.getBinaryBulkReply(); - } - - /** - * Set the specified hash field to the specified value if the field not exists. Time - * complexity: O(1) - * @param key - * @param field - * @param value - * @return If the field already exists, 0 is returned, otherwise if a new field is created 1 is - * returned. - */ - @Override - public long hsetnx(final byte[] key, final byte[] field, final byte[] value) { - checkIsInMultiOrPipeline(); - client.hsetnx(key, field, value); - return client.getIntegerReply(); - } - - /** - * Set the respective fields to the respective values. HMSET replaces old values with new values. - *

- * If key does not exist, a new key holding a hash is created. - *

- * Time complexity: O(N) (with N being the number of fields) - * @param key - * @param hash - * @return Always OK because HMSET can't fail - */ - @Override - public String hmset(final byte[] key, final Map hash) { - checkIsInMultiOrPipeline(); - client.hmset(key, hash); - return client.getStatusCodeReply(); - } - - /** - * Retrieve the values associated to the specified fields. - *

- * If some of the specified fields do not exist, nil values are returned. Non existing keys are - * considered like empty hashes. - *

- * Time complexity: O(N) (with N being the number of fields) - * @param key - * @param fields - * @return Multi Bulk Reply specifically a list of all the values associated with the specified - * fields, in the same order of the request. - */ - @Override - public List hmget(final byte[] key, final byte[]... fields) { - checkIsInMultiOrPipeline(); - client.hmget(key, fields); - return client.getBinaryMultiBulkReply(); - } - - /** - * Increment the number stored at field in the hash at key by value. If key does not exist, a new - * key holding a hash is created. If field does not exist or holds a string, the value is set to 0 - * before applying the operation. Since the value argument is signed you can use this command to - * perform both increments and decrements. - *

- * The range of values supported by HINCRBY is limited to 64 bit signed integers. - *

- * Time complexity: O(1) - * @param key - * @param field - * @param value - * @return Integer reply The new value at field after the increment operation. - */ - @Override - public long hincrBy(final byte[] key, final byte[] field, final long value) { - checkIsInMultiOrPipeline(); - client.hincrBy(key, field, value); - return client.getIntegerReply(); - } - - /** - * Increment the number stored at field in the hash at key by a double precision floating point - * value. If key does not exist, a new key holding a hash is created. If field does not exist or - * holds a string, the value is set to 0 before applying the operation. Since the value argument - * is signed you can use this command to perform both increments and decrements. - *

- * The range of values supported by HINCRBYFLOAT is limited to double precision floating point - * values. - *

- * Time complexity: O(1) - * @param key - * @param field - * @param value - * @return Double precision floating point reply The new value at field after the increment - * operation. - */ - @Override - public double hincrByFloat(final byte[] key, final byte[] field, final double value) { - checkIsInMultiOrPipeline(); - client.hincrByFloat(key, field, value); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - /** - * Test for existence of a specified field in a hash. Time complexity: O(1) - * @param key - * @param field - * @return Return true if the hash stored at key contains the specified field. Return false if the key is - * not found or the field is not present. - */ - @Override - public boolean hexists(final byte[] key, final byte[] field) { - checkIsInMultiOrPipeline(); - client.hexists(key, field); - return client.getIntegerReply() == 1; - } - - /** - * Remove the specified field from an hash stored at key. - *

- * Time complexity: O(1) - * @param key - * @param fields - * @return If the field was present in the hash it is deleted and 1 is returned, otherwise 0 is - * returned and no operation is performed. - */ - @Override - public long hdel(final byte[] key, final byte[]... fields) { - checkIsInMultiOrPipeline(); - client.hdel(key, fields); - return client.getIntegerReply(); - } - - /** - * Return the number of items in a hash. - *

- * Time complexity: O(1) - * @param key - * @return The number of entries (fields) contained in the hash stored at key. If the specified - * key does not exist, 0 is returned assuming an empty hash. - */ - @Override - public long hlen(final byte[] key) { - checkIsInMultiOrPipeline(); - client.hlen(key); - return client.getIntegerReply(); - } - - /** - * Return all the fields in a hash. - *

- * Time complexity: O(N), where N is the total number of entries - * @param key - * @return All the fields names contained into a hash. - */ - @Override - public Set hkeys(final byte[] key) { - checkIsInMultiOrPipeline(); - client.hkeys(key); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * Return all the values in a hash. - *

- * Time complexity: O(N), where N is the total number of entries - * @param key - * @return All the fields values contained into a hash. - */ - @Override - public List hvals(final byte[] key) { - checkIsInMultiOrPipeline(); - client.hvals(key); - return client.getBinaryMultiBulkReply(); - } - - /** - * Return all the fields and associated values in a hash. - *

- * Time complexity: O(N), where N is the total number of entries - * @param key - * @return All the fields and values contained into a hash. - */ - @Override - public Map hgetAll(final byte[] key) { - checkIsInMultiOrPipeline(); - client.hgetAll(key); - return BuilderFactory.BYTE_ARRAY_MAP.build(client.getBinaryMultiBulkReply()); - } - - /** - * Get one random field from a hash. - *

- * Time complexity: O(N), where N is the number of fields returned - * @param key - * @return one random field from a hash. - */ - @Override - public byte[] hrandfield(final byte[] key) { - checkIsInMultiOrPipeline(); - client.hrandfield(key); - return client.getBinaryBulkReply(); - } - - /** - * Get multiple random fields from a hash. - *

- * Time complexity: O(N), where N is the number of fields returned - * @param key - * @return multiple random fields from a hash. - */ - @Override - public List hrandfield(final byte[] key, final long count) { - checkIsInMultiOrPipeline(); - client.hrandfield(key, count); - return client.getBinaryMultiBulkReply(); - } - - /** - * Get one or multiple random fields with values from a hash. - *

- * Time complexity: O(N), where N is the number of fields returned - * @param key - * @return one or multiple random fields with values from a hash. - */ - @Override - public Map hrandfieldWithValues(final byte[] key, final long count) { - checkIsInMultiOrPipeline(); - client.hrandfieldWithValues(key, count); - return BuilderFactory.BYTE_ARRAY_MAP.build(client.getBinaryMultiBulkReply()); - } - - /** - * Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key - * does not exist an empty list is created just before the append operation. If the key exists but - * is not a List an error is returned. - *

- * Time complexity: O(1) - * @param key - * @param strings - * @return Integer reply, specifically, the number of elements inside the list after the push - * operation. - */ - @Override - public long rpush(final byte[] key, final byte[]... strings) { - checkIsInMultiOrPipeline(); - client.rpush(key, strings); - return client.getIntegerReply(); - } - - /** - * Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key - * does not exist an empty list is created just before the append operation. If the key exists but - * is not a List an error is returned. - *

- * Time complexity: O(1) - * @param key - * @param strings - * @return Integer reply, specifically, the number of elements inside the list after the push - * operation. - */ - @Override - public long lpush(final byte[] key, final byte[]... strings) { - checkIsInMultiOrPipeline(); - client.lpush(key, strings); - return client.getIntegerReply(); - } - - /** - * Return the length of the list stored at the specified key. If the key does not exist zero is - * returned (the same behaviour as for empty lists). If the value stored at key is not a list an - * error is returned. - *

- * Time complexity: O(1) - * @param key - * @return The length of the list. - */ - @Override - public long llen(final byte[] key) { - checkIsInMultiOrPipeline(); - client.llen(key); - return client.getIntegerReply(); - } - - /** - * Return the specified elements of the list stored at the specified key. Start and end are - * zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and - * so on. - *

- * For example LRANGE foobar 0 2 will return the first three elements of the list. - *

- * start and end can also be negative numbers indicating offsets from the end of the list. For - * example -1 is the last element of the list, -2 the penultimate element and so on. - *

- * Consistency with range functions in various programming languages - *

- * Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will return 11 elements, - * that is, rightmost item is included. This may or may not be consistent with behavior of - * range-related functions in your programming language of choice (think Ruby's Range.new, - * Array#slice or Python's range() function). - *

- * LRANGE behavior is consistent with one of Tcl. - *

- * Out-of-range indexes - *

- * Indexes out of range will not produce an error: if start is over the end of the list, or start - * > end, an empty list is returned. If end is over the end of the list Redis will threat it - * just like the last element of the list. - *

- * Time complexity: O(start+n) (with n being the length of the range and start being the start - * offset) - * @param key - * @param start - * @param stop - * @return Multi bulk reply, specifically a list of elements in the specified range. - */ - @Override - public List lrange(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.lrange(key, start, stop); - return client.getBinaryMultiBulkReply(); - } - - /** - * Trim an existing list so that it will contain only the specified range of elements specified. - * Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the - * next element and so on. - *

- * For example LTRIM foobar 0 2 will modify the list stored at foobar key so that only the first - * three elements of the list will remain. - *

- * start and end can also be negative numbers indicating offsets from the end of the list. For - * example -1 is the last element of the list, -2 the penultimate element and so on. - *

- * Indexes out of range will not produce an error: if start is over the end of the list, or start - * > end, an empty list is left as value. If end over the end of the list Redis will threat it - * just like the last element of the list. - *

- * Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example: - *

- * {@code lpush("mylist", "someelement"); ltrim("mylist", 0, 99); * } - *

- * The above two commands will push elements in the list taking care that the list will not grow - * without limits. This is very useful when using Redis to store logs for example. It is important - * to note that when used in this way LTRIM is an O(1) operation because in the average case just - * one element is removed from the tail of the list. - *

- * Time complexity: O(n) (with n being len of list - len of range) - * @param key - * @param start - * @param stop - * @return Status code reply - */ - @Override - public String ltrim(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.ltrim(key, start, stop); - return client.getStatusCodeReply(); - } - - /** - * Return the specified element of the list stored at the specified key. 0 is the first element, 1 - * the second and so on. Negative indexes are supported, for example -1 is the last element, -2 - * the penultimate and so on. - *

- * If the value stored at key is not of list type an error is returned. If the index is out of - * range a 'nil' reply is returned. - *

- * Note that even if the average time complexity is O(n) asking for the first or the last element - * of the list is O(1). - *

- * Time complexity: O(n) (with n being the length of the list) - * @param key - * @param index - * @return Bulk reply, specifically the requested element - */ - @Override - public byte[] lindex(final byte[] key, final long index) { - checkIsInMultiOrPipeline(); - client.lindex(key, index); - return client.getBinaryBulkReply(); - } - - /** - * Set a new value as the element at index position of the List at key. - *

- * Out of range indexes will generate an error. - *

- * Similarly to other list commands accepting indexes, the index can be negative to access - * elements starting from the end of the list. So -1 is the last element, -2 is the penultimate, - * and so forth. - *

- * Time complexity: - *

- * O(N) (with N being the length of the list), setting the first or last elements of the list is - * O(1). - * @see #lindex(byte[], long) - * @param key - * @param index - * @param value - * @return Status code reply - */ - @Override - public String lset(final byte[] key, final long index, final byte[] value) { - checkIsInMultiOrPipeline(); - client.lset(key, index, value); - return client.getStatusCodeReply(); - } - - /** - * Remove the first count occurrences of the value element from the list. If count is zero all the - * elements are removed. If count is negative elements are removed from tail to head, instead to - * go from head to tail that is the normal behaviour. So for example LREM with count -2 and hello - * as value to remove against the list (a,b,c,hello,x,hello,hello) will leave the list - * (a,b,c,hello,x). The number of removed elements is returned as an integer, see below for more - * information about the returned value. Note that non existing keys are considered like empty - * lists by LREM, so LREM against non existing keys will always return 0. - *

- * Time complexity: O(N) (with N being the length of the list) - * @param key - * @param count - * @param value - * @return Integer Reply, specifically: The number of removed elements if the operation succeeded - */ - @Override - public long lrem(final byte[] key, final long count, final byte[] value) { - checkIsInMultiOrPipeline(); - client.lrem(key, count, value); - return client.getIntegerReply(); - } - - /** - * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example - * if the list contains the elements "a","b","c" LPOP will return "a" and the list will become - * "b","c". - *

- * If the key does not exist or the list is already empty the special value 'nil' is returned. - * @see #rpop(byte[]) - * @param key - * @return Bulk reply - */ - @Override - public byte[] lpop(final byte[] key) { - checkIsInMultiOrPipeline(); - client.lpop(key); - return client.getBinaryBulkReply(); - } - - @Override - public List lpop(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.lpop(key, count); - return client.getBinaryMultiBulkReply(); - } - - /** - * Returns the index of the first matching element inside a redis list. If the element is found, - * its index (the zero-based position in the list) is returned. Otherwise, if no match is found, - * 'nil' is returned. - *

- * Time complexity: O(N) where N is the number of elements in the list - * @see #lpos(byte[], byte[]) - * @param key - * @param element - * @return Integer Reply, specifically: The index of first matching element in the list. Value will - * be 'nil' when the element is not present in the list. - */ - @Override - public Long lpos(final byte[] key, final byte[] element) { - checkIsInMultiOrPipeline(); - client.lpos(key, element); - return client.getIntegerReply(); - } - - /** - * In case there are multiple matches Rank option specifies the "rank" of the element to return. - * A rank of 1 returns the first match, 2 to return the second match, and so forth. - * If list `foo` has elements ("a","b","c","1","2","3","c","c"), The function call to get the - * index of second occurrence of "c" will be as follows lpos("foo","c", LPosParams.lPosParams().rank(2)). - *

- * Maxlen option compares the element provided only with a given maximum number of list items. - * A value of 1000 will make sure that the command performs only 1000 comparisons. The - * comparison is made for the first part or the last part depending on the fact we use a positive or - * negative rank. - * Following is how we could use the Maxlen option lpos("foo", "b", LPosParams.lPosParams().rank(1).maxlen(2)). - * @see #lpos(byte[], byte[], LPosParams) - * @param key - * @param element - * @param params - * @return Integer Reply - */ - @Override - public Long lpos(final byte[] key, final byte[] element, final LPosParams params) { - checkIsInMultiOrPipeline(); - client.lpos(key, element, params); - return client.getIntegerReply(); - } - - /** - * Count will return list of position of all the first N matching elements. It is possible to - * specify 0 as the number of matches, as a way to tell the command we want all the matches - * found returned as an array of indexes. When count is used and no match is found, an empty list - * is returned. - *

- * Time complexity: O(N) where N is the number of elements in the list - * @see #lpos(byte[], byte[], LPosParams, long) - * @param key - * @param element - * @param params - * @param count - * @return Returns value will be a list containing position of the matching elements inside the list. - */ - @Override - public List lpos(final byte[] key, final byte[] element, final LPosParams params, - final long count) { - checkIsInMultiOrPipeline(); - client.lpos(key, element, params, count); - return client.getIntegerMultiBulkReply(); - } - - /** - * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example - * if the list contains the elements "a","b","c" LPOP will return "a" and the list will become - * "b","c". - *

- * If the key does not exist or the list is already empty the special value 'nil' is returned. - * @see #lpop(byte[]) - * @param key - * @return Bulk reply - */ - @Override - public byte[] rpop(final byte[] key) { - checkIsInMultiOrPipeline(); - client.rpop(key); - return client.getBinaryBulkReply(); - } - - @Override - public List rpop(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.rpop(key, count); - return client.getBinaryMultiBulkReply(); - } - - /** - * Atomically return and remove the last (tail) element of the srckey list, and push the element - * as the first (head) element of the dstkey list. For example if the source list contains the - * elements "a","b","c" and the destination list contains the elements "foo","bar" after an - * RPOPLPUSH command the content of the two lists will be "a","b" and "c","foo","bar". - *

- * If the key does not exist or the list is already empty the special value 'nil' is returned. If - * the srckey and dstkey are the same the operation is equivalent to removing the last element - * from the list and pushing it as first element of the list, so it's a "list rotation" command. - *

- * Time complexity: O(1) - * @param srckey - * @param dstkey - * @return Bulk reply - */ - @Override - public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) { - checkIsInMultiOrPipeline(); - client.rpoplpush(srckey, dstkey); - return client.getBinaryBulkReply(); - } - - /** - * Add the specified member to the set value stored at key. If member is already a member of the - * set no operation is performed. If key does not exist a new set with the specified member as - * sole member is created. If the key exists but does not hold a set value an error is returned. - *

- * Time complexity O(1) - * @param key - * @param members - * @return Integer reply, specifically: 1 if the new element was added 0 if the element was - * already a member of the set - */ - @Override - public long sadd(final byte[] key, final byte[]... members) { - checkIsInMultiOrPipeline(); - client.sadd(key, members); - return client.getIntegerReply(); - } - - /** - * Return all the members (elements) of the set value stored at key. This is just syntax glue for - * {@link #sinter(byte[]...)} SINTER}. - *

- * Time complexity O(N) - * @param key the key of the set - * @return Multi bulk reply - */ - @Override - public Set smembers(final byte[] key) { - checkIsInMultiOrPipeline(); - client.smembers(key); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * Remove the specified member from the set value stored at key. If member was not a member of the - * set no operation is performed. If key does not hold a set value an error is returned. - *

- * Time complexity O(1) - * @param key the key of the set - * @param member the set member to remove - * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was - * not a member of the set - */ - @Override - public long srem(final byte[] key, final byte[]... member) { - checkIsInMultiOrPipeline(); - client.srem(key, member); - return client.getIntegerReply(); - } - - /** - * Remove a random element from a Set returning it as return value. If the Set is empty or the key - * does not exist, a nil object is returned. - *

- * The {@link #srandmember(byte[])} command does a similar work but the returned element is not - * removed from the Set. - *

- * Time complexity O(1) - * @param key - * @return Bulk reply - */ - @Override - public byte[] spop(final byte[] key) { - checkIsInMultiOrPipeline(); - client.spop(key); - return client.getBinaryBulkReply(); - } - - @Override - public Set spop(final byte[] key, final long count) { - checkIsInMultiOrPipeline(); - client.spop(key, count); - List members = client.getBinaryMultiBulkReply(); - if (members == null) return null; - return SetFromList.of(members); - } - - /** - * Move the specified member from the set at srckey to the set at dstkey. This operation is - * atomic, in every given moment the element will appear to be in the source or destination set - * for accessing clients. - *

- * If the source set does not exist or does not contain the specified element no operation is - * performed and zero is returned, otherwise the element is removed from the source set and added - * to the destination set. On success one is returned, even if the element was already present in - * the destination set. - *

- * An error is raised if the source or destination keys contain a non Set value. - *

- * Time complexity O(1) - * @param srckey - * @param dstkey - * @param member - * @return Integer reply, specifically: 1 if the element was moved 0 if the element was not found - * on the first set and no operation was performed - */ - @Override - public long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { - checkIsInMultiOrPipeline(); - client.smove(srckey, dstkey, member); - return client.getIntegerReply(); - } - - /** - * Return the set cardinality (number of elements). If the key does not exist 0 is returned, like - * for empty sets. - * @param key - * @return Integer reply, specifically: the cardinality (number of elements) of the set as an - * integer. - */ - @Override - public long scard(final byte[] key) { - checkIsInMultiOrPipeline(); - client.scard(key); - return client.getIntegerReply(); - } - - /** - * Return true if member is a member of the set stored at key, otherwise false is returned. - *

- * Time complexity O(1) - * @param key - * @param member - * @return Boolean reply, specifically: true if the element is a member of the set false if the element - * is not a member of the set OR if the key does not exist - */ - @Override - public boolean sismember(final byte[] key, final byte[] member) { - checkIsInMultiOrPipeline(); - client.sismember(key, member); - return client.getIntegerReply() == 1; - } - - /** - * Returns whether each member is a member of the set stored at key. - *

- * Time complexity O(N) where N is the number of elements being checked for membership - * @param key - * @param members - * @return List representing the membership of the given elements, in the same order as they are requested. - */ - @Override - public List smismember(final byte[] key, final byte[]... members) { - checkIsInMultiOrPipeline(); - client.smismember(key, members); - return BuilderFactory.BOOLEAN_LIST.build(client.getIntegerMultiBulkReply()); - } - - /** - * Return the members of a set resulting from the intersection of all the sets hold at the - * specified keys. Like in {@link #lrange(byte[], long, long)} LRANGE} the result is sent to the - * client as a multi-bulk reply (see the protocol specification for more information). If just a - * single key is specified, then this command produces the same result as - * {@link #smembers(byte[]) SMEMBERS}. Actually SMEMBERS is just syntax sugar for SINTER. - *

- * Non existing keys are considered like empty sets, so if one of the keys is missing an empty set - * is returned (since the intersection with an empty set always is an empty set). - *

- * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the - * number of sets - * @param keys - * @return Multi bulk reply, specifically the list of common elements. - */ - @Override - public Set sinter(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.sinter(keys); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * This commanad works exactly like {@link #sinter(byte[]...) SINTER} but instead of being returned - * the resulting set is stored as dstkey. - *

- * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the - * number of sets - * @param dstkey - * @param keys - * @return Status code reply - */ - @Override - public long sinterstore(final byte[] dstkey, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.sinterstore(dstkey, keys); - return client.getIntegerReply(); - } - - /** - * Return the members of a set resulting from the union of all the sets hold at the specified - * keys. Like in {@link #lrange(byte[], long, long)} LRANGE} the result is sent to the client as a - * multi-bulk reply (see the protocol specification for more information). If just a single key is - * specified, then this command produces the same result as {@link #smembers(byte[]) SMEMBERS}. - *

- * Non existing keys are considered like empty sets. - *

- * Time complexity O(N) where N is the total number of elements in all the provided sets - * @param keys - * @return Multi bulk reply, specifically the list of common elements. - */ - @Override - public Set sunion(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.sunion(keys); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * This command works exactly like {@link #sunion(byte[]...) SUNION} but instead of being returned - * the resulting set is stored as dstkey. Any existing value in dstkey will be over-written. - *

- * Time complexity O(N) where N is the total number of elements in all the provided sets - * @param dstkey - * @param keys - * @return Status code reply - */ - @Override - public long sunionstore(final byte[] dstkey, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.sunionstore(dstkey, keys); - return client.getIntegerReply(); - } - - /** - * Return the difference between the Set stored at key1 and all the Sets key2, ..., keyN - *

- * Example: - * - *

-   * key1 = [x, a, b, c]
-   * key2 = [c]
-   * key3 = [a, d]
-   * SDIFF key1,key2,key3 => [x, b]
-   * 
- * - * Non existing keys are considered like empty sets. - *

- * Time complexity: - *

- * O(N) with N being the total number of elements of all the sets - * @param keys - * @return Return the members of a set resulting from the difference between the first set - * provided and all the successive sets. - */ - @Override - public Set sdiff(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.sdiff(keys); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * This command works exactly like {@link BinaryJedis#sdiff(byte[]...) SDIFF} but instead of being returned - * the resulting set is stored in dstkey. - * @param dstkey - * @param keys - * @return Status code reply - */ - @Override - public long sdiffstore(final byte[] dstkey, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.sdiffstore(dstkey, keys); - return client.getIntegerReply(); - } - - /** - * Return a random element from a Set, without removing the element. If the Set is empty or the - * key does not exist, a nil object is returned. - *

- * The SPOP command does a similar work but the returned element is popped (removed) from the Set. - *

- * Time complexity O(1) - * @param key - * @return Bulk reply - */ - @Override - public byte[] srandmember(final byte[] key) { - checkIsInMultiOrPipeline(); - client.srandmember(key); - return client.getBinaryBulkReply(); - } - - @Override - public List srandmember(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.srandmember(key, count); - return client.getBinaryMultiBulkReply(); - } - - /** - * Add the specified member having the specified score to the sorted set stored at key. If member - * is already a member of the sorted set the score is updated, and the element reinserted in the - * right position to ensure sorting. If key does not exist a new sorted set with the specified - * member as sole member is created. If the key exists but does not hold a sorted set value an - * error is returned. - *

- * The score value can be the string representation of a double precision floating point number. - *

- * Time complexity O(log(N)) with N being the number of elements in the sorted set - * @param key - * @param score - * @param member - * @return Integer reply, specifically: 1 if the new element was added 0 if the element was - * already a member of the sorted set and the score was updated - */ - @Override - public long zadd(final byte[] key, final double score, final byte[] member) { - checkIsInMultiOrPipeline(); - client.zadd(key, score, member); - return client.getIntegerReply(); - } - - @Override - public long zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { - checkIsInMultiOrPipeline(); - client.zadd(key, score, member, params); - return client.getIntegerReply(); - } - - @Override - public long zadd(final byte[] key, final Map scoreMembers) { - checkIsInMultiOrPipeline(); - client.zadd(key, scoreMembers); - return client.getIntegerReply(); - } - - @Override - public long zadd(final byte[] key, final Map scoreMembers, final ZAddParams params) { - checkIsInMultiOrPipeline(); - client.zadd(key, scoreMembers, params); - return client.getIntegerReply(); - } - - @Override - public Double zaddIncr(final byte[] key, final double score, final byte[] member, final ZAddParams params) { - checkIsInMultiOrPipeline(); - client.zaddIncr(key, score, member, params); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - @Override - public Set zrange(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.zrange(key, start, stop); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * Remove the specified member from the sorted set value stored at key. If member was not a member - * of the set no operation is performed. If key does not not hold a set value an error is - * returned. - *

- * Time complexity O(log(N)) with N being the number of elements in the sorted set - * @param key - * @param members - * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was - * not a member of the set - */ - @Override - public long zrem(final byte[] key, final byte[]... members) { - checkIsInMultiOrPipeline(); - client.zrem(key, members); - return client.getIntegerReply(); - } - - /** - * If member already exists in the sorted set adds the increment to its score and updates the - * position of the element in the sorted set accordingly. If member does not already exist in the - * sorted set it is added with increment as score (that is, like if the previous score was - * virtually zero). If key does not exist a new sorted set with the specified member as sole - * member is created. If the key exists but does not hold a sorted set value an error is returned. - *

- * The score value can be the string representation of a double precision floating point number. - * It's possible to provide a negative value to perform a decrement. - *

- * For an introduction to sorted sets check the Introduction to Redis data types page. - *

- * Time complexity O(log(N)) with N being the number of elements in the sorted set - * @param key - * @param increment - * @param member - * @return The new score - */ - @Override - public double zincrby(final byte[] key, final double increment, final byte[] member) { - checkIsInMultiOrPipeline(); - client.zincrby(key, increment, member); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - @Override - public Double zincrby(final byte[] key, final double increment, final byte[] member, - final ZIncrByParams params) { - checkIsInMultiOrPipeline(); - client.zincrby(key, increment, member, params); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - /** - * Return the rank (or index) or member in the sorted set at key, with scores being ordered from - * low to high. - *

- * When the given member does not exist in the sorted set, the special value 'nil' is returned. - * The returned rank (or index) of the member is 0-based for both commands. - *

- * Time complexity: - *

- * O(log(N)) - * @see #zrevrank(byte[], byte[]) - * @param key - * @param member - * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer - * reply if the element exists. A nil bulk reply if there is no such element. - */ - @Override - public Long zrank(final byte[] key, final byte[] member) { - checkIsInMultiOrPipeline(); - client.zrank(key, member); - return client.getIntegerReply(); - } - - /** - * Return the rank (or index) or member in the sorted set at key, with scores being ordered from - * high to low. - *

- * When the given member does not exist in the sorted set, the special value 'nil' is returned. - * The returned rank (or index) of the member is 0-based for both commands. - *

- * Time complexity: - *

- * O(log(N)) - * @see #zrank(byte[], byte[]) - * @param key - * @param member - * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer - * reply if the element exists. A nil bulk reply if there is no such element. - */ - @Override - public Long zrevrank(final byte[] key, final byte[] member) { - checkIsInMultiOrPipeline(); - client.zrevrank(key, member); - return client.getIntegerReply(); - } - - @Override - public Set zrevrange(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.zrevrange(key, start, stop); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrangeWithScores(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.zrangeWithScores(key, start, stop); - return getTupledSet(); - } - - @Override - public Set zrevrangeWithScores(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.zrevrangeWithScores(key, start, stop); - return getTupledSet(); - } - - @Override - public byte[] zrandmember(final byte[] key) { - checkIsInMultiOrPipeline(); - client.zrandmember(key); - return client.getBinaryBulkReply(); - } - - @Override - public Set zrandmember(final byte[] key, final long count) { - checkIsInMultiOrPipeline(); - client.zrandmember(key, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrandmemberWithScores(final byte[] key, final long count) { - checkIsInMultiOrPipeline(); - client.zrandmemberWithScores(key, count); - return getTupledSet(); - } - - /** - * Return the sorted set cardinality (number of elements). If the key does not exist 0 is - * returned, like for empty sorted sets. - *

- * Time complexity O(1) - * @param key - * @return the cardinality (number of elements) of the set as an integer. - */ - @Override - public long zcard(final byte[] key) { - checkIsInMultiOrPipeline(); - client.zcard(key); - return client.getIntegerReply(); - } - - /** - * Return the score of the specified element of the sorted set at key. If the specified element - * does not exist in the sorted set, or the key does not exist at all, a special 'nil' value is - * returned. - *

- * Time complexity: O(1) - * @param key - * @param member - * @return the score - */ - @Override - public Double zscore(final byte[] key, final byte[] member) { - checkIsInMultiOrPipeline(); - client.zscore(key, member); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - /** - * Returns the scores associated with the specified members in the sorted set stored at key. - * For every member that does not exist in the sorted set, a nil value is returned. - *

- * Time complexity: O(N) where N is the number of members being requested. - * @param key - * @param members - * @return the scores - */ - @Override - public List zmscore(final byte[] key, final byte[]... members) { - checkIsInMultiOrPipeline(); - client.zmscore(key, members); - return BuilderFactory.DOUBLE_LIST.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Tuple zpopmax(final byte[] key) { - checkIsInMultiOrPipeline(); - client.zpopmax(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zpopmax(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.zpopmax(key, count); - return getTupledSet(); - } - - @Override - public Tuple zpopmin(final byte[] key) { - checkIsInMultiOrPipeline(); - client.zpopmin(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zpopmin(final byte[] key, final int count) { - checkIsInMultiOrPipeline(); - client.zpopmin(key, count); - return getTupledSet(); - } - - public Transaction multi() { - client.multi(); - client.getOne(); // expected OK - transaction = new Transaction(client); - return transaction; - } - - protected void checkIsInMultiOrPipeline() { - if (client.isInMulti()) { - throw new IllegalStateException( - "Cannot use Jedis when in Multi. Please use Transaction or reset jedis state."); - } else if (pipeline != null && pipeline.hasPipelinedResponse()) { - throw new IllegalStateException( - "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state."); - } - } - - @Override - public String watch(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.watch(keys); - return client.getStatusCodeReply(); - } - - @Override - public String unwatch() { - checkIsInMultiOrPipeline(); - client.unwatch(); - return client.getStatusCodeReply(); - } - - /** - * Sort a Set or a List. - *

- * Sort the elements contained in the List, Set, or Sorted Set value at key. By default sorting is - * numeric with elements being compared as double precision floating point numbers. This is the - * simplest form of SORT. - * @see #sort(byte[], byte[]) - * @see #sort(byte[], SortingParams) - * @see #sort(byte[], SortingParams, byte[]) - * @param key - * @return Assuming the Set/List at key contains a list of numbers, the return value will be the - * list of numbers ordered from the smallest to the biggest number. - */ - @Override - public List sort(final byte[] key) { - checkIsInMultiOrPipeline(); - client.sort(key); - return client.getBinaryMultiBulkReply(); - } - - /** - * Sort a Set or a List accordingly to the specified parameters. - *

- * examples: - *

- * Given are the following sets and key/values: - * - *

-   * x = [1, 2, 3]
-   * y = [a, b, c]
-   *
-   * k1 = z
-   * k2 = y
-   * k3 = x
-   *
-   * w1 = 9
-   * w2 = 8
-   * w3 = 7
-   * 
- * - * Sort Order: - * - *
-   * sort(x) or sort(x, sp.asc())
-   * -> [1, 2, 3]
-   *
-   * sort(x, sp.desc())
-   * -> [3, 2, 1]
-   *
-   * sort(y)
-   * -> [c, a, b]
-   *
-   * sort(y, sp.alpha())
-   * -> [a, b, c]
-   *
-   * sort(y, sp.alpha().desc())
-   * -> [c, a, b]
-   * 
- * - * Limit (e.g. for Pagination): - * - *
-   * sort(x, sp.limit(0, 2))
-   * -> [1, 2]
-   *
-   * sort(y, sp.alpha().desc().limit(1, 2))
-   * -> [b, a]
-   * 
- * - * Sorting by external keys: - * - *
-   * sort(x, sb.by(w*))
-   * -> [3, 2, 1]
-   *
-   * sort(x, sb.by(w*).desc())
-   * -> [1, 2, 3]
-   * 
- * - * Getting external keys: - * - *
-   * sort(x, sp.by(w*).get(k*))
-   * -> [x, y, z]
-   *
-   * sort(x, sp.by(w*).get(#).get(k*))
-   * -> [3, x, 2, y, 1, z]
-   * 
- * @see #sort(byte[]) - * @see #sort(byte[], SortingParams, byte[]) - * @param key - * @param sortingParameters - * @return a list of sorted elements. - */ - @Override - public List sort(final byte[] key, final SortingParams sortingParameters) { - checkIsInMultiOrPipeline(); - client.sort(key, sortingParameters); - return client.getBinaryMultiBulkReply(); - } - - /** - * Sort a Set or a List accordingly to the specified parameters and store the result at dstkey. - * @see #sort(byte[], SortingParams) - * @see #sort(byte[]) - * @see #sort(byte[], byte[]) - * @param key - * @param sortingParameters - * @param dstkey - * @return The number of elements of the list at dstkey. - */ - @Override - public long sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { - checkIsInMultiOrPipeline(); - client.sort(key, sortingParameters, dstkey); - return client.getIntegerReply(); - } - - /** - * Sort a Set or a List and Store the Result at dstkey. - *

- * Sort the elements contained in the List, Set, or Sorted Set value at key and store the result - * at dstkey. By default sorting is numeric with elements being compared as double precision - * floating point numbers. This is the simplest form of SORT. - * @see #sort(byte[]) - * @see #sort(byte[], SortingParams) - * @see #sort(byte[], SortingParams, byte[]) - * @param key - * @param dstkey - * @return The number of elements of the list at dstkey. - */ - @Override - public long sort(final byte[] key, final byte[] dstkey) { - checkIsInMultiOrPipeline(); - client.sort(key, dstkey); - return client.getIntegerReply(); - } - - /** - * Pop an element from a list, push it to another list and return it - * @param srcKey - * @param dstKey - * @param from - * @param to - */ - @Override - public byte[] lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { - checkIsInMultiOrPipeline(); - client.lmove(srcKey, dstKey, from, to); - return client.getBinaryBulkReply(); - } - - /** - * Pop an element from a list, push it to another list and return it; or block until one is available - * @param srcKey - * @param dstKey - * @param from - * @param to - * @param timeout - */ - @Override - public byte[] blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { - checkIsInMultiOrPipeline(); - client.blmove(srcKey, dstKey, from, to, timeout); - client.setTimeoutInfinite(); - try { - return client.getBinaryBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - /** - * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking - * versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty - * lists. - *

- * The following is a description of the exact semantic. We describe BLPOP but the two commands - * are identical, the only difference is that BLPOP pops the element from the left (head) of the - * list, and BRPOP pops from the right (tail). - *

- * Non blocking behavior - *

- * When BLPOP is called, if at least one of the specified keys contain a non empty list, an - * element is popped from the head of the list and returned to the caller together with the name - * of the key (BLPOP returns a two elements array, the first element is the key, the second the - * popped value). - *

- * Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0 - * against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP - * guarantees to return an element from the list stored at list2 (since it is the first non empty - * list starting from the left). - *

- * Blocking behavior - *

- * If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other - * client performs a LPUSH or an RPUSH operation against one of the lists. - *

- * Once new data is present on one of the lists, the client finally returns with the name of the - * key unblocking it and the popped value. - *

- * When blocking, if a non-zero timeout is specified, the client will unblock returning a nil - * special value if the specified amount of seconds passed without a push operation against at - * least one of the specified keys. - *

- * The timeout argument is interpreted as an integer value. A timeout of zero means instead to - * block forever. - *

- * Multiple clients blocking for the same keys - *

- * Multiple clients can block for the same key. They are put into a queue, so the first to be - * served will be the one that started to wait earlier, in a first-blpopping first-served fashion. - *

- * blocking POP inside a MULTI/EXEC transaction - *

- * BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies - * in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis - * transaction). - *

- * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil - * reply, exactly what happens when the timeout is reached. If you like science fiction, think at - * it like if inside MULTI/EXEC the time will flow at infinite speed :) - *

- * Time complexity: O(1) - * @param timeout - * @param keys - * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the - * unblocking key and the popped value. - *

- * When a non-zero timeout is specified, and the BLPOP operation timed out, the return - * value is a nil multi bulk reply. Most client values will return false or nil - * accordingly to the programming language used. - */ - @Override - public List blpop(final int timeout, final byte[]... keys) { - return blpop(getKeysAndTimeout(timeout, keys)); - } - - @Override - public List blpop(final double timeout, final byte[]... keys) { - return blpop(getKeysAndTimeout(timeout, keys)); - } - - /** - * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking - * versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty - * lists. - *

- * The following is a description of the exact semantic. We describe BLPOP but the two commands - * are identical, the only difference is that BLPOP pops the element from the left (head) of the - * list, and BRPOP pops from the right (tail). - *

- * Non blocking behavior - *

- * When BLPOP is called, if at least one of the specified keys contain a non empty list, an - * element is popped from the head of the list and returned to the caller together with the name - * of the key (BLPOP returns a two elements array, the first element is the key, the second the - * popped value). - *

- * Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0 - * against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP - * guarantees to return an element from the list stored at list2 (since it is the first non empty - * list starting from the left). - *

- * Blocking behavior - *

- * If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other - * client performs a LPUSH or an RPUSH operation against one of the lists. - *

- * Once new data is present on one of the lists, the client finally returns with the name of the - * key unblocking it and the popped value. - *

- * When blocking, if a non-zero timeout is specified, the client will unblock returning a nil - * special value if the specified amount of seconds passed without a push operation against at - * least one of the specified keys. - *

- * The timeout argument is interpreted as an integer value. A timeout of zero means instead to - * block forever. - *

- * Multiple clients blocking for the same keys - *

- * Multiple clients can block for the same key. They are put into a queue, so the first to be - * served will be the one that started to wait earlier, in a first-blpopping first-served fashion. - *

- * blocking POP inside a MULTI/EXEC transaction - *

- * BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies - * in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis - * transaction). - *

- * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil - * reply, exactly what happens when the timeout is reached. If you like science fiction, think at - * it like if inside MULTI/EXEC the time will flow at infinite speed :) - *

- * Time complexity: O(1) - * @param timeout - * @param keys - * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the - * unblocking key and the popped value. - *

- * When a non-zero timeout is specified, and the BLPOP operation timed out, the return - * value is a nil multi bulk reply. Most client values will return false or nil - * accordingly to the programming language used. - */ - @Override - public List brpop(final int timeout, final byte[]... keys) { - return brpop(getKeysAndTimeout(timeout, keys)); - } - - @Override - public List brpop(final double timeout, final byte[]... keys) { - return brpop(getKeysAndTimeout(timeout, keys)); - } - - @Override - public List blpop(final byte[]... args) { - checkIsInMultiOrPipeline(); - client.blpop(args); - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public List brpop(final byte[]... args) { - checkIsInMultiOrPipeline(); - client.brpop(args); - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - private byte[][] getKeysAndTimeout(int timeout, byte[][] keys) { - int size = keys.length; - final byte[][] args = new byte[size + 1][]; - System.arraycopy(keys, 0, args, 0, size); - args[size] = Protocol.toByteArray(timeout); - return args; - } - - private byte[][] getKeysAndTimeout(double timeout, byte[][] keys) { - int size = keys.length; - final byte[][] args = new byte[size + 1][]; - System.arraycopy(keys, 0, args, 0, size); - args[size] = Protocol.toByteArray(timeout); - return args; - } - - @Override - public List bzpopmax(final double timeout, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.bzpopmax(timeout, keys); - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public List bzpopmin(final double timeout, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.bzpopmin(timeout, keys); - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - /** - * Request for authentication in a password protected Redis server. A Redis server can be - * instructed to require a password before to allow clients to issue commands. This is done using - * the requirepass directive in the Redis configuration file. If the password given by the client - * is correct the server replies with an OK status code reply and starts accepting commands from - * the client. Otherwise an error is returned and the clients needs to try a new password. Note - * that for the high performance nature of Redis it is possible to try a lot of passwords in - * parallel in very short time, so make sure to generate a strong and very long password so that - * this attack is infeasible. - * @param password - * @return Status code reply - */ - @Override - public String auth(final String password) { - checkIsInMultiOrPipeline(); - client.auth(password); - return client.getStatusCodeReply(); - } - - /** - * Request for authentication with a Redis Server that is using ACL where user are authenticated with - * username and password. - * See https://redis.io/topics/acl - * @param user - * @param password - * @return OK - */ - @Override - public String auth(final String user, final String password) { - checkIsInMultiOrPipeline(); - client.auth(user, password); - return client.getStatusCodeReply(); - } - - public Pipeline pipelined() { - pipeline = new Pipeline(); - pipeline.setClient(client); - return pipeline; - } - - @Override - public long zcount(final byte[] key, final double min, final double max) { - checkIsInMultiOrPipeline(); - client.zcount(key, min, max); - return client.getIntegerReply(); - } - - @Override - public long zcount(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zcount(key, min, max); - return client.getIntegerReply(); - } - - @Override - public Set zdiff(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zdiff(keys); - return BuilderFactory.BYTE_ARRAY_ZSET.build(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zdiffWithScores(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zdiffWithScores(keys); - return getTupledSet(); - } - - @Override - public long zdiffStore(final byte[] dstkey, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zdiffStore(dstkey, keys); - return client.getIntegerReply(); - } - - /** - * Return the all the elements in the sorted set at key with a score between min and max - * (including elements with score equal to min or max). - *

- * The elements having the same score are returned sorted lexicographically as ASCII strings (this - * follows from a property of Redis sorted sets and does not involve further computation). - *

- * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible - * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large - * the commands needs to traverse the list for offset elements and this adds up to the O(M) - * figure. - *

- * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the - * actual elements in the specified interval, it just returns the number of matching elements. - *

- * Exclusive intervals and infinity - *

- * min and max can be -inf and +inf, so that you are not required to know what's the greatest or - * smallest element in order to take, for instance, elements "up to a given value". - *

- * Also while the interval is for default closed (inclusive) it's possible to specify open - * intervals prefixing the score with a "(" character, so for instance: - *

- * {@code ZRANGEBYSCORE zset (1.3 5} - *

- * Will return all the values with score > 1.3 and <= 5, while for instance: - *

- * {@code ZRANGEBYSCORE zset (5 (10} - *

- * Will return all the values with score > 5 and < 10 (5 and 10 excluded). - *

- * Time complexity: - *

- * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of - * elements returned by the command, so if M is constant (for instance you always ask for the - * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(byte[], double, double) - * @see #zrangeByScore(byte[], double, double, int, int) - * @see #zrangeByScoreWithScores(byte[], double, double) - * @see #zrangeByScoreWithScores(byte[], double, double, int, int) - * @see #zcount(byte[], double, double) - * @param key - * @param min - * @param max - * @return Multi bulk reply specifically a list of elements in the specified score range. - */ - @Override - public Set zrangeByScore(final byte[] key, final double min, final double max) { - checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * Return the all the elements in the sorted set at key with a score between min and max - * (including elements with score equal to min or max). - *

- * The elements having the same score are returned sorted lexicographically as ASCII strings (this - * follows from a property of Redis sorted sets and does not involve further computation). - *

- * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible - * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large - * the commands needs to traverse the list for offset elements and this adds up to the O(M) - * figure. - *

- * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the - * actual elements in the specified interval, it just returns the number of matching elements. - *

- * Exclusive intervals and infinity - *

- * min and max can be -inf and +inf, so that you are not required to know what's the greatest or - * smallest element in order to take, for instance, elements "up to a given value". - *

- * Also while the interval is for default closed (inclusive) it's possible to specify open - * intervals prefixing the score with a "(" character, so for instance: - *

- * {@code ZRANGEBYSCORE zset (1.3 5} - *

- * Will return all the values with score > 1.3 and <= 5, while for instance: - *

- * {@code ZRANGEBYSCORE zset (5 (10} - *

- * Will return all the values with score > 5 and < 10 (5 and 10 excluded). - *

- * Time complexity: - *

- * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of - * elements returned by the command, so if M is constant (for instance you always ask for the - * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(byte[], double, double) - * @see #zrangeByScore(byte[], double, double, int, int) - * @see #zrangeByScoreWithScores(byte[], double, double) - * @see #zrangeByScoreWithScores(byte[], double, double, int, int) - * @see #zcount(byte[], double, double) - * @param key - * @param min - * @param max - * @param offset - * @param count - * @return Multi bulk reply specifically a list of elements in the specified score range. - */ - @Override - public Set zrangeByScore(final byte[] key, final double min, final double max, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max, offset, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max, offset, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - /** - * Return the all the elements in the sorted set at key with a score between min and max - * (including elements with score equal to min or max). - *

- * The elements having the same score are returned sorted lexicographically as ASCII strings (this - * follows from a property of Redis sorted sets and does not involve further computation). - *

- * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible - * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large - * the commands needs to traverse the list for offset elements and this adds up to the O(M) - * figure. - *

- * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the - * actual elements in the specified interval, it just returns the number of matching elements. - *

- * Exclusive intervals and infinity - *

- * min and max can be -inf and +inf, so that you are not required to know what's the greatest or - * smallest element in order to take, for instance, elements "up to a given value". - *

- * Also while the interval is for default closed (inclusive) it's possible to specify open - * intervals prefixing the score with a "(" character, so for instance: - *

- * {@code ZRANGEBYSCORE zset (1.3 5} - *

- * Will return all the values with score > 1.3 and <= 5, while for instance: - *

- * {@code ZRANGEBYSCORE zset (5 (10} - *

- * Will return all the values with score > 5 and < 10 (5 and 10 excluded). - *

- * Time complexity: - *

- * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of - * elements returned by the command, so if M is constant (for instance you always ask for the - * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(byte[], double, double) - * @see #zrangeByScore(byte[], double, double, int, int) - * @see #zrangeByScoreWithScores(byte[], double, double) - * @see #zrangeByScoreWithScores(byte[], double, double, int, int) - * @see #zcount(byte[], double, double) - * @param key - * @param min - * @param max - * @return Multi bulk reply specifically a list of elements in the specified score range. - */ - @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max) { - checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max); - return getTupledSet(); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max); - return getTupledSet(); - } - - /** - * Return the all the elements in the sorted set at key with a score between min and max - * (including elements with score equal to min or max). - *

- * The elements having the same score are returned sorted lexicographically as ASCII strings (this - * follows from a property of Redis sorted sets and does not involve further computation). - *

- * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible - * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large - * the commands needs to traverse the list for offset elements and this adds up to the O(M) - * figure. - *

- * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the - * actual elements in the specified interval, it just returns the number of matching elements. - *

- * Exclusive intervals and infinity - *

- * min and max can be -inf and +inf, so that you are not required to know what's the greatest or - * smallest element in order to take, for instance, elements "up to a given value". - *

- * Also while the interval is for default closed (inclusive) it's possible to specify open - * intervals prefixing the score with a "(" character, so for instance: - *

- * {@code ZRANGEBYSCORE zset (1.3 5} - *

- * Will return all the values with score > 1.3 and <= 5, while for instance: - *

- * {@code ZRANGEBYSCORE zset (5 (10} - *

- * Will return all the values with score > 5 and < 10 (5 and 10 excluded). - *

- * Time complexity: - *

- * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of - * elements returned by the command, so if M is constant (for instance you always ask for the - * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(byte[], double, double) - * @see #zrangeByScore(byte[], double, double, int, int) - * @see #zrangeByScoreWithScores(byte[], double, double) - * @see #zrangeByScoreWithScores(byte[], double, double, int, int) - * @see #zcount(byte[], double, double) - * @param key - * @param min - * @param max - * @param offset - * @param count - * @return Multi bulk reply specifically a list of elements in the specified score range. - */ - @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max, offset, count); - return getTupledSet(); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max, offset, count); - return getTupledSet(); - } - - protected Set getTupledSet() { - List membersWithScores = client.getBinaryMultiBulkReply(); - // If response from Redis nil, we should return null. - if (membersWithScores == null) { - return null; - } - if (membersWithScores.isEmpty()) { - return Collections.emptySet(); - } - Set set = new LinkedHashSet<>(membersWithScores.size() / 2, 1.0f); - Iterator iterator = membersWithScores.iterator(); - while (iterator.hasNext()) { - set.add(new Tuple(iterator.next(), BuilderFactory.DOUBLE.build(iterator.next()))); - } - return set; - } - - @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min, offset, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min, offset, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min); - return getTupledSet(); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min, final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min, offset, count); - return getTupledSet(); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min); - return getTupledSet(); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min, offset, count); - return getTupledSet(); - } - - /** - * Remove all elements in the sorted set at key with rank between start and end. Start and end are - * 0-based with rank 0 being the element with the lowest score. Both start and end can be negative - * numbers, where they indicate offsets starting at the element with the highest rank. For - * example: -1 is the element with the highest score, -2 the element with the second highest score - * and so forth. - *

- * Time complexity: O(log(N))+O(M) with N being the number of elements in the sorted set - * and M the number of elements removed by the operation - * @param key - * @param start - * @param stop - */ - @Override - public long zremrangeByRank(final byte[] key, final long start, final long stop) { - checkIsInMultiOrPipeline(); - client.zremrangeByRank(key, start, stop); - return client.getIntegerReply(); - } - - /** - * Remove all the elements in the sorted set at key with a score between min and max (including - * elements with score equal to min or max). - *

- * Time complexity: - *

- * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of - * elements removed by the operation - * @param key - * @param min - * @param max - * @return Integer reply, specifically the number of elements removed. - */ - @Override - public long zremrangeByScore(final byte[] key, final double min, final double max) { - checkIsInMultiOrPipeline(); - client.zremrangeByScore(key, min, max); - return client.getIntegerReply(); - } - - @Override - public long zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zremrangeByScore(key, min, max); - return client.getIntegerReply(); - } - - /** - * Add multiple sorted sets, This command is similar to ZUNIONSTORE, but instead of storing the - * resulting sorted set, it is returned to the client. - * @param params - * @param keys - */ - @Override - public Set zunion(final ZParams params, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zunion(params, keys); - return BuilderFactory.BYTE_ARRAY_ZSET.build(client.getBinaryMultiBulkReply()); - } - - /** - * Add multiple sorted sets with scores, This command is similar to ZUNIONSTORE, but instead of storing the - * resulting sorted set, it is returned to the client. - * @param params - * @param keys - */ - @Override - public Set zunionWithScores(final ZParams params, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zunionWithScores(params, keys); - return BuilderFactory.TUPLE_ZSET.build(client.getBinaryMultiBulkReply()); - } - - /** - * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at - * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys - * and the other (optional) arguments. - *

- * As the terms imply, the {@link #zinterstore(byte[], byte[]...)} ZINTERSTORE} command requires - * an element to be present in each of the given inputs to be inserted in the result. The {@link - * #zunionstore(byte[], byte[]...)} command inserts all elements across all inputs. - *

- * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means - * that the score of each element in the sorted set is first multiplied by this weight before - * being passed to the aggregation. When this option is not given, all weights default to 1. - *

- * With the AGGREGATE option, it's possible to specify how the results of the union or - * intersection are aggregated. This option defaults to SUM, where the score of an element is - * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the - * resulting set will contain the minimum or maximum score of an element across the inputs where - * it exists. - *

- * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input - * sorted sets, and M being the number of elements in the resulting sorted set - * @param dstkey - * @param sets - * @return Integer reply, specifically the number of elements in the sorted set at dstkey - */ - @Override - public long zunionstore(final byte[] dstkey, final byte[]... sets) { - checkIsInMultiOrPipeline(); - client.zunionstore(dstkey, sets); - return client.getIntegerReply(); - } - - /** - * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at - * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys - * and the other (optional) arguments. - *

- * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an - * element to be present in each of the given inputs to be inserted in the result. The {@link - * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. - *

- * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means - * that the score of each element in the sorted set is first multiplied by this weight before - * being passed to the aggregation. When this option is not given, all weights default to 1. - *

- * With the AGGREGATE option, it's possible to specify how the results of the union or - * intersection are aggregated. This option defaults to SUM, where the score of an element is - * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the - * resulting set will contain the minimum or maximum score of an element across the inputs where - * it exists. - *

- * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input - * sorted sets, and M being the number of elements in the resulting sorted set - * @param dstkey - * @param sets - * @param params - * @return Integer reply, specifically the number of elements in the sorted set at dstkey - */ - @Override - public long zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { - checkIsInMultiOrPipeline(); - client.zunionstore(dstkey, params, sets); - return client.getIntegerReply(); - } - - /** - * Intersect multiple sorted sets, This command is similar to ZINTERSTORE, but instead of storing - * the resulting sorted set, it is returned to the client. - * @param params - * @param keys - */ - @Override - public Set zinter(final ZParams params, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zinter(params, keys); - return BuilderFactory.BYTE_ARRAY_ZSET.build(client.getBinaryMultiBulkReply()); - } - - /** - * Intersect multiple sorted sets, This command is similar to ZINTERSTORE, but instead of storing - * the resulting sorted set, it is returned to the client. - * @param params - * @param keys - */ - @Override - public Set zinterWithScores(final ZParams params, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.zinterWithScores(params, keys); - return BuilderFactory.TUPLE_ZSET.build(client.getBinaryMultiBulkReply()); - } - - /** - * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at - * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys - * and the other (optional) arguments. - *

- * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an - * element to be present in each of the given inputs to be inserted in the result. The {@link - * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. - *

- * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means - * that the score of each element in the sorted set is first multiplied by this weight before - * being passed to the aggregation. When this option is not given, all weights default to 1. - *

- * With the AGGREGATE option, it's possible to specify how the results of the union or - * intersection are aggregated. This option defaults to SUM, where the score of an element is - * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the - * resulting set will contain the minimum or maximum score of an element across the inputs where - * it exists. - *

- * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input - * sorted sets, and M being the number of elements in the resulting sorted set - * @param dstkey - * @param sets - * @return Integer reply, specifically the number of elements in the sorted set at dstkey - */ - @Override - public long zinterstore(final byte[] dstkey, final byte[]... sets) { - checkIsInMultiOrPipeline(); - client.zinterstore(dstkey, sets); - return client.getIntegerReply(); - } - - /** - * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at - * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys - * and the other (optional) arguments. - *

- * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an - * element to be present in each of the given inputs to be inserted in the result. The {@link - * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. - *

- * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means - * that the score of each element in the sorted set is first multiplied by this weight before - * being passed to the aggregation. When this option is not given, all weights default to 1. - *

- * With the AGGREGATE option, it's possible to specify how the results of the union or - * intersection are aggregated. This option defaults to SUM, where the score of an element is - * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the - * resulting set will contain the minimum or maximum score of an element across the inputs where - * it exists. - *

- * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input - * sorted sets, and M being the number of elements in the resulting sorted set - * @param dstkey - * @param sets - * @param params - * @return Integer reply, specifically the number of elements in the sorted set at dstkey - */ - @Override - public long zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { - checkIsInMultiOrPipeline(); - client.zinterstore(dstkey, params, sets); - return client.getIntegerReply(); - } - - @Override - public long zlexcount(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zlexcount(key, min, max); - return client.getIntegerReply(); - } - - @Override - public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zrangeByLex(key, min, max); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrangeByLex(key, min, max, offset, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { - checkIsInMultiOrPipeline(); - client.zrevrangeByLex(key, max, min); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - checkIsInMultiOrPipeline(); - client.zrevrangeByLex(key, max, min, offset, count); - return SetFromList.of(client.getBinaryMultiBulkReply()); - } - - @Override - public long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - checkIsInMultiOrPipeline(); - client.zremrangeByLex(key, min, max); - return client.getIntegerReply(); - } - - /** - * Synchronously save the DB on disk. - *

- * Save the whole dataset on disk (this means that all the databases are saved, as well as keys - * with an EXPIRE set (the expire is preserved). The server hangs while the saving is not - * completed, no connection is served in the meanwhile. An OK code is returned when the DB was - * fully stored in disk. - *

- * The background variant of this command is {@link #bgsave() BGSAVE} that is able to perform the - * saving in the background while the server continues serving other clients. - *

- * @return Status code reply - */ - @Override - public String save() { - client.save(); - return client.getStatusCodeReply(); - } - - /** - * Asynchronously save the DB on disk. - *

- * Save the DB in background. The OK code is immediately returned. Redis forks, the parent - * continues to server the clients, the child saves the DB on disk then exit. A client my be able - * to check if the operation succeeded using the LASTSAVE command. - * @return Status code reply - */ - @Override - public String bgsave() { - client.bgsave(); - return client.getStatusCodeReply(); - } - - /** - * Rewrite the append only file in background when it gets too big. Please for detailed - * information about the Redis Append Only File check the Append Only File Howto. - *

- * BGREWRITEAOF rewrites the Append Only File in background when it gets too big. The Redis Append - * Only File is a Journal, so every operation modifying the dataset is logged in the Append Only - * File (and replayed at startup). This means that the Append Only File always grows. In order to - * rebuild its content the BGREWRITEAOF creates a new version of the append only file starting - * directly form the dataset in memory in order to guarantee the generation of the minimal number - * of commands needed to rebuild the database. - *

- * @return Status code reply - */ - @Override - public String bgrewriteaof() { - client.bgrewriteaof(); - return client.getStatusCodeReply(); - } - - /** - * Return the UNIX time stamp of the last successfully saving of the dataset on disk. - *

- * Return the UNIX TIME of the last DB save executed with success. A client may check if a - * {@link #bgsave() BGSAVE} command succeeded reading the LASTSAVE value, then issuing a BGSAVE - * command and checking at regular intervals every N seconds if LASTSAVE changed. - * @return Integer reply, specifically an UNIX time stamp. - */ - @Override - public long lastsave() { - client.lastsave(); - return client.getIntegerReply(); - } - - /** - * Synchronously save the DB on disk, then shutdown the server. - *

- * Stop all the clients, save the DB, then quit the server. This commands makes sure that the DB - * is switched off without the lost of any data. This is not guaranteed if the client uses simply - * {@link #save() SAVE} and then {@link #quit() QUIT} because other clients may alter the DB data - * between the two commands. - * @return {@code null} - * @throws JedisException with the status code reply on error. On success nothing is thrown since - * the server quits and the connection is closed. - */ - @Override - public String shutdown() throws JedisException { - client.shutdown(); - String status; - try { - status = client.getStatusCodeReply(); - throw new JedisException(status); - } catch (JedisConnectionException jce) { - // expected - status = null; - } - return status; - } - - @Override - public void shutdown(final SaveMode saveMode) throws JedisException { - client.shutdown(saveMode); - try { - throw new JedisException(client.getStatusCodeReply()); - } catch (JedisConnectionException jce) { - // expected - } - } - - /** - * Provide information and statistics about the server. - *

- * The info command returns different information and statistics about the server in an format - * that's simple to parse by computers and easy to read by humans. - *

- * Format of the returned String: - *

- * All the fields are in the form field:value - * - *

-   * edis_version:0.07
-   * connected_clients:1
-   * connected_slaves:0
-   * used_memory:3187
-   * changes_since_last_save:0
-   * last_save_time:1237655729
-   * total_connections_received:1
-   * total_commands_processed:1
-   * uptime_in_seconds:25
-   * uptime_in_days:0
-   * 
- * - * Notes - *

- * used_memory is returned in bytes, and is the total number of bytes allocated by the program - * using malloc. - *

- * uptime_in_days is redundant since the uptime in seconds contains already the full uptime - * information, this field is only mainly present for humans. - *

- * changes_since_last_save does not refer to the number of key changes, but to the number of - * operations that produced some kind of change in the dataset. - *

- * @return Bulk reply - */ - @Override - public String info() { - client.info(); - return client.getBulkReply(); - } - - @Override - public String info(final String section) { - client.info(section); - return client.getBulkReply(); - } - - /** - * Dump all the received requests in real time. - *

- * MONITOR is a debugging command that outputs the whole sequence of commands received by the - * Redis server. is very handy in order to understand what is happening into the database. This - * command is used directly via telnet. - * @param jedisMonitor - */ - public void monitor(final JedisMonitor jedisMonitor) { - client.monitor(); - client.getStatusCodeReply(); - jedisMonitor.proceed(client); - } - - /** - * Change the replication settings. - *

- * The SLAVEOF command can change the replication settings of a slave on the fly. If a Redis - * server is already acting as slave, the command SLAVEOF NO ONE will turn off the replication - * turning the Redis server into a MASTER. In the proper form SLAVEOF hostname port will make the - * server a slave of the specific server listening at the specified hostname and port. - *

- * If a server is already a slave of some master, SLAVEOF hostname port will stop the replication - * against the old server and start the synchronization against the new one discarding the old - * dataset. - *

- * The form SLAVEOF no one will stop replication turning the server into a MASTER but will not - * discard the replication. So if the old master stop working it is possible to turn the slave - * into a master and set the application to use the new master in read/write. Later when the other - * Redis server will be fixed it can be configured in order to work as slave. - *

- * @param host - * @param port - * @return Status code reply - */ - @Override - public String slaveof(final String host, final int port) { - client.slaveof(host, port); - return client.getStatusCodeReply(); - } - - @Override - public String slaveofNoOne() { - client.slaveofNoOne(); - return client.getStatusCodeReply(); - } - - @Override - public List roleBinary() { - checkIsInMultiOrPipeline(); - client.role(); - return BuilderFactory.RAW_OBJECT_LIST.build(client.getOne()); - } - - /** - * Retrieve the configuration of a running Redis server. Not all the configuration parameters are - * supported. - *

- * CONFIG GET returns the current configuration parameters. This sub command only accepts a single - * argument, that is glob style pattern. All the configuration parameters matching this parameter - * are reported as a list of key-value pairs. - *

- * Example: - * - *

-   * $ redis-cli config get '*'
-   * 1. "dbfilename"
-   * 2. "dump.rdb"
-   * 3. "requirepass"
-   * 4. (nil)
-   * 5. "masterauth"
-   * 6. (nil)
-   * 7. "maxmemory"
-   * 8. "0\n"
-   * 9. "appendfsync"
-   * 10. "everysec"
-   * 11. "save"
-   * 12. "3600 1 300 100 60 10000"
-   *
-   * $ redis-cli config get 'm*'
-   * 1. "masterauth"
-   * 2. (nil)
-   * 3. "maxmemory"
-   * 4. "0\n"
-   * 
- * @param pattern - * @return Bulk reply. - */ - @Override - public List configGet(final byte[] pattern) { - checkIsInMultiOrPipeline(); - client.configGet(pattern); - return client.getBinaryMultiBulkReply(); - } - - /** - * Reset the stats returned by INFO - */ - @Override - public String configResetStat() { - checkIsInMultiOrPipeline(); - client.configResetStat(); - return client.getStatusCodeReply(); - } - - /** - * The CONFIG REWRITE command rewrites the redis.conf file the server was started with, applying - * the minimal changes needed to make it reflect the configuration currently used by the server, - * which may be different compared to the original one because of the use of the CONFIG SET - * command. - *

- * The rewrite is performed in a very conservative way: - *

    - *
  • Comments and the overall structure of the original redis.conf are preserved as much as - * possible.
  • - *
  • If an option already exists in the old redis.conf file, it will be rewritten at the same - * position (line number).
  • - *
  • If an option was not already present, but it is set to its default value, it is not added - * by the rewrite process.
  • - *
  • If an option was not already present, but it is set to a non-default value, it is appended - * at the end of the file.
  • - *
  • Non used lines are blanked. For instance if you used to have multiple save directives, but - * the current configuration has fewer or none as you disabled RDB persistence, all the lines will - * be blanked.
  • - *
- *

- * CONFIG REWRITE is also able to rewrite the configuration file from scratch if the original one - * no longer exists for some reason. However if the server was started without a configuration - * file at all, the CONFIG REWRITE will just return an error. - * @return OK when the configuration was rewritten properly. Otherwise an error is returned. - */ - @Override - public String configRewrite() { - checkIsInMultiOrPipeline(); - client.configRewrite(); - return client.getStatusCodeReply(); - } - - /** - * Alter the configuration of a running Redis server. Not all the configuration parameters are - * supported. - *

- * The list of configuration parameters supported by CONFIG SET can be obtained issuing a - * {@link #configGet(byte[]) CONFIG GET *} command. - *

- * The configuration set using CONFIG SET is immediately loaded by the Redis server that will - * start acting as specified starting from the next command. - *

- * Parameters value format - *

- * The value of the configuration parameter is the same as the one of the same parameter in the - * Redis configuration file, with the following exceptions: - *

- *

    - *
  • The save parameter is a list of space-separated integers. Every pair of integers specify - * the time and number of changes limit to trigger a save. For instance the command CONFIG SET - * save "3600 10 60 10000" will configure the server to issue a background saving of the RDB file - * every 3600 seconds if there are at least 10 changes in the dataset, and every 60 seconds if - * there are at least 10000 changes. To completely disable automatic snapshots just set the - * parameter as an empty string. - *
  • All the integer parameters representing memory are returned and accepted only using bytes - * as unit. - *
- * @param parameter - * @param value - * @return Status code reply - */ - @Override - public String configSet(final byte[] parameter, final byte[] value) { - checkIsInMultiOrPipeline(); - client.configSet(parameter, value); - return client.getStatusCodeReply(); - } - - @Override - public long strlen(final byte[] key) { - checkIsInMultiOrPipeline(); - client.strlen(key); - return client.getIntegerReply(); - } - - @Override - public LCSMatchResult strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params) { - checkIsInMultiOrPipeline(); - client.strAlgoLCSKeys(keyA, keyB, params); - return BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER.build(client.getOne()); - } - - @Override - public LCSMatchResult strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params) { - checkIsInMultiOrPipeline(); - client.strAlgoLCSStrings(strA, strB, params); - return BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER.build(client.getOne()); - } - - @Override - public long lpushx(final byte[] key, final byte[]... string) { - checkIsInMultiOrPipeline(); - client.lpushx(key, string); - return client.getIntegerReply(); - } - - /** - * Undo a {@link #expire(byte[], int) expire} at turning the expire key into a normal key. - *

- * Time complexity: O(1) - * @param key - * @return Integer reply, specifically: 1: the key is now persist. 0: the key is not persist (only - * happens when key not set). - */ - @Override - public long persist(final byte[] key) { - checkIsInMultiOrPipeline(); - client.persist(key); - return client.getIntegerReply(); - } - - @Override - public long rpushx(final byte[] key, final byte[]... string) { - checkIsInMultiOrPipeline(); - client.rpushx(key, string); - return client.getIntegerReply(); - } - - @Override - public byte[] echo(final byte[] string) { - checkIsInMultiOrPipeline(); - client.echo(string); - return client.getBinaryBulkReply(); - } - - @Override - public long linsert(final byte[] key, final ListPosition where, final byte[] pivot, - final byte[] value) { - checkIsInMultiOrPipeline(); - client.linsert(key, where, pivot, value); - return client.getIntegerReply(); - } - - @Override - public String debug(final DebugParams params) { - client.debug(params); - return client.getStatusCodeReply(); - } - - public Client getClient() { - return client; - } - - /** - * Pop a value from a list, push it to another list and return it; or block until one is available - * @param source - * @param destination - * @param timeout - * @return the element - */ - @Override - public byte[] brpoplpush(final byte[] source, final byte[] destination, final int timeout) { - checkIsInMultiOrPipeline(); - client.brpoplpush(source, destination, timeout); - client.setTimeoutInfinite(); - try { - return client.getBinaryBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - /** - * Sets or clears the bit at offset in the string value stored at key - * @param key - * @param offset - * @param value - */ - @Override - public boolean setbit(final byte[] key, final long offset, final boolean value) { - checkIsInMultiOrPipeline(); - client.setbit(key, offset, value); - return client.getIntegerReply() == 1; - } - - @Override - @Deprecated - public Boolean setbit(final byte[] key, final long offset, final byte[] value) { - checkIsInMultiOrPipeline(); - client.setbit(key, offset, value); - return client.getIntegerReply() == 1; - } - - /** - * Returns the bit value at offset in the string value stored at key - * @param key - * @param offset - */ - @Override - public boolean getbit(final byte[] key, final long offset) { - checkIsInMultiOrPipeline(); - client.getbit(key, offset); - return client.getIntegerReply() == 1; - } - - public Long bitpos(final byte[] key, final boolean value) { - return bitpos(key, value, new BitPosParams()); - } - - public Long bitpos(final byte[] key, final boolean value, final BitPosParams params) { - checkIsInMultiOrPipeline(); - client.bitpos(key, value, params); - return client.getIntegerReply(); - } - - @Override - public long setrange(final byte[] key, final long offset, final byte[] value) { - checkIsInMultiOrPipeline(); - client.setrange(key, offset, value); - return client.getIntegerReply(); - } - - @Override - public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) { - checkIsInMultiOrPipeline(); - client.getrange(key, startOffset, endOffset); - return client.getBinaryBulkReply(); - } - - @Override - public Long publish(final byte[] channel, final byte[] message) { - checkIsInMultiOrPipeline(); - client.publish(channel, message); - return client.getIntegerReply(); - } - - @Override - public void subscribe(BinaryJedisPubSub jedisPubSub, final byte[]... channels) { - client.setTimeoutInfinite(); - try { - jedisPubSub.proceed(client, channels); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public void psubscribe(BinaryJedisPubSub jedisPubSub, final byte[]... patterns) { - client.setTimeoutInfinite(); - try { - jedisPubSub.proceedWithPatterns(client, patterns); - } finally { - client.rollbackTimeout(); - } - } - - /** - * Evaluates scripts using the Lua interpreter built into Redis starting from version 2.6.0. - *

- * @param script - * @param keys - * @param args - * @return Script result - */ - @Override - public Object eval(final byte[] script, final List keys, final List args) { - return eval(script, toByteArray(keys.size()), getParamsWithBinary(keys, args)); - } - - protected static byte[][] getParamsWithBinary(List keys, List args) { - final int keyCount = keys.size(); - final int argCount = args.size(); - byte[][] params = new byte[keyCount + argCount][]; - - for (int i = 0; i < keyCount; i++) - params[i] = keys.get(i); - - for (int i = 0; i < argCount; i++) - params[keyCount + i] = args.get(i); - - return params; - } - - @Override - @Deprecated - public Object eval(final byte[] script, final byte[] keyCount, final byte[]... params) { - checkIsInMultiOrPipeline(); - client.eval(script, keyCount, params); - return client.getOne(); - } - - @Override - public Object eval(final byte[] script, final int keyCount, final byte[]... params) { - return eval(script, toByteArray(keyCount), params); - } - - @Override - public Object eval(final byte[] script) { - return eval(script, 0); - } - - @Override - public Object evalsha(final byte[] sha1) { - return evalsha(sha1, 0); - } - - @Override - public Object evalsha(final byte[] sha1, final List keys, final List args) { - return evalsha(sha1, keys.size(), getParamsWithBinary(keys, args)); - } - - @Override - public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { - checkIsInMultiOrPipeline(); - client.evalsha(sha1, keyCount, params); - return client.getOne(); - } - - @Override - public String scriptFlush() { - client.scriptFlush(); - return client.getStatusCodeReply(); - } - - @Override - public String scriptFlush(final FlushMode flushMode) { - client.scriptFlush(flushMode); - return client.getStatusCodeReply(); - } - - public Long scriptExists(final byte[] sha1) { - byte[][] a = new byte[1][]; - a[0] = sha1; - return scriptExists(a).get(0); - } - - @Override - public List scriptExists(final byte[]... sha1) { - client.scriptExists(sha1); - return client.getIntegerMultiBulkReply(); - } - - @Override - public byte[] scriptLoad(final byte[] script) { - client.scriptLoad(script); - return client.getBinaryBulkReply(); - } - - @Override - public String scriptKill() { - client.scriptKill(); - return client.getStatusCodeReply(); - } - - @Override - public String slowlogReset() { - client.slowlogReset(); - return client.getBulkReply(); - } - - @Override - public long slowlogLen() { - client.slowlogLen(); - return client.getIntegerReply(); - } - - @Override - public List slowlogGetBinary() { - client.slowlogGet(); - return client.getObjectMultiBulkReply(); - } - - @Override - public List slowlogGetBinary(final long entries) { - client.slowlogGet(entries); - return client.getObjectMultiBulkReply(); - } - - @Override - public Long objectRefcount(final byte[] key) { - client.objectRefcount(key); - return client.getIntegerReply(); - } - - @Override - public byte[] objectEncoding(final byte[] key) { - client.objectEncoding(key); - return client.getBinaryBulkReply(); - } - - @Override - public Long objectIdletime(final byte[] key) { - client.objectIdletime(key); - return client.getIntegerReply(); - } - - @Override - public List objectHelpBinary() { - client.objectHelp(); - return client.getBinaryMultiBulkReply(); - } - - @Override - public Long objectFreq(final byte[] key) { - client.objectFreq(key); - return client.getIntegerReply(); - } - - @Override - public long bitcount(final byte[] key) { - checkIsInMultiOrPipeline(); - client.bitcount(key); - return client.getIntegerReply(); - } - - @Override - public long bitcount(final byte[] key, final long start, final long end) { - checkIsInMultiOrPipeline(); - client.bitcount(key, start, end); - return client.getIntegerReply(); - } - - @Override - public long bitop(final BitOP op, final byte[] destKey, final byte[]... srcKeys) { - checkIsInMultiOrPipeline(); - client.bitop(op, destKey, srcKeys); - return client.getIntegerReply(); - } - - @Override - public byte[] dump(final byte[] key) { - checkIsInMultiOrPipeline(); - client.dump(key); - return client.getBinaryBulkReply(); - } - - @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { - checkIsInMultiOrPipeline(); - client.restore(key, ttl, serializedValue); - return client.getStatusCodeReply(); - } - - @Override - public String restoreReplace(final byte[] key, final long ttl, final byte[] serializedValue) { - checkIsInMultiOrPipeline(); - client.restoreReplace(key, ttl, serializedValue); - return client.getStatusCodeReply(); - } - - @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - checkIsInMultiOrPipeline(); - client.restore(key, ttl, serializedValue, params); - return client.getStatusCodeReply(); - } - - /** - * Set a timeout on the specified key. After the timeout the key will be automatically deleted by - * the server. A key with an associated timeout is said to be volatile in Redis terminology. - *

- * Volatile keys are stored on disk like the other keys, the timeout is persistent too like all - * the other aspects of the dataset. Saving a dataset containing expires and stopping the server - * does not stop the flow of time as Redis stores on disk the time when the key will no longer be - * available as Unix time, and not the remaining milliseconds. - *

- * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire - * set. It is also possible to undo the expire at all turning the key into a normal key using the - * {@link #persist(byte[]) PERSIST} command. - *

- * Time complexity: O(1) - * @see PEXPIRE Command - * @param key - * @param milliseconds - * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since - * the key already has an associated timeout (this may happen only in Redis versions < - * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. - */ - @Override - public long pexpire(final byte[] key, final long milliseconds) { - checkIsInMultiOrPipeline(); - client.pexpire(key, milliseconds); - return client.getIntegerReply(); - } - - @Override - public long pexpireAt(final byte[] key, final long millisecondsTimestamp) { - checkIsInMultiOrPipeline(); - client.pexpireAt(key, millisecondsTimestamp); - return client.getIntegerReply(); - } - - @Override - public long pttl(final byte[] key) { - checkIsInMultiOrPipeline(); - client.pttl(key); - return client.getIntegerReply(); - } - - /** - * PSETEX works exactly like {@link #setex(byte[], int, byte[])} with the sole difference that the - * expire time is specified in milliseconds instead of seconds. Time complexity: O(1) - * @param key - * @param milliseconds - * @param value - * @return Status code reply - */ - @Override - public String psetex(final byte[] key, final long milliseconds, final byte[] value) { - checkIsInMultiOrPipeline(); - client.psetex(key, milliseconds, value); - return client.getStatusCodeReply(); - } - - @Override - public byte[] memoryDoctorBinary() { - checkIsInMultiOrPipeline(); - client.memoryDoctor(); - return client.getBinaryBulkReply(); - } - - @Override - public Long memoryUsage(final byte[] key) { - checkIsInMultiOrPipeline(); - client.memoryUsage(key); - return client.getIntegerReply(); - } - - @Override - public Long memoryUsage(final byte[] key, final int samples) { - checkIsInMultiOrPipeline(); - client.memoryUsage(key, samples); - return client.getIntegerReply(); - } - - @Override - public String failover() { - return failover(null); - } - - @Override - public String failover(FailoverParams failoverParams) { - checkIsInMultiOrPipeline(); - client.failover(failoverParams); - client.setTimeoutInfinite(); - try { - return client.getStatusCodeReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public String failoverAbort() { - checkIsInMultiOrPipeline(); - client.failoverAbort(); - return client.getStatusCodeReply(); - } - - @Override - public byte[] aclWhoAmIBinary() { - checkIsInMultiOrPipeline(); - client.aclWhoAmI(); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] aclGenPassBinary() { - checkIsInMultiOrPipeline(); - client.aclGenPass(); - return client.getBinaryBulkReply(); - } - - @Override - public List aclListBinary() { - checkIsInMultiOrPipeline(); - client.aclList(); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List aclUsersBinary() { - checkIsInMultiOrPipeline(); - client.aclUsers(); - return client.getBinaryMultiBulkReply(); - } - - @Override - public AccessControlUser aclGetUser(byte[] name) { - checkIsInMultiOrPipeline(); - client.aclGetUser(name); - return BuilderFactory.ACCESS_CONTROL_USER.build(client.getObjectMultiBulkReply()); - } - - @Override - public String aclSetUser(byte[] name) { - checkIsInMultiOrPipeline(); - client.aclSetUser(name); - return client.getStatusCodeReply(); - } - - @Override - public String aclSetUser(byte[] name, byte[]... keys) { - checkIsInMultiOrPipeline(); - client.aclSetUser(name, keys); - return client.getStatusCodeReply(); - } - - @Override - public long aclDelUser(byte[] name) { - checkIsInMultiOrPipeline(); - client.aclDelUser(name); - return client.getIntegerReply(); - } - - @Override - public List aclCatBinary() { - checkIsInMultiOrPipeline(); - client.aclCat(); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List aclCat(byte[] category) { - checkIsInMultiOrPipeline(); - client.aclCat(category); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List aclLogBinary() { - checkIsInMultiOrPipeline(); - client.aclLog(); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List aclLogBinary(int limit) { - checkIsInMultiOrPipeline(); - client.aclLog(limit); - return client.getBinaryMultiBulkReply(); - } - - @Override - public byte[] aclLog(byte[] options) { - checkIsInMultiOrPipeline(); - client.aclLog(options); - return client.getBinaryBulkReply(); - } - - @Override - public String aclLoad() { - checkIsInMultiOrPipeline(); - client.aclLoad(); - return client.getStatusCodeReply(); - } - - @Override - public String aclSave() { - checkIsInMultiOrPipeline(); - client.aclSave(); - return client.getStatusCodeReply(); - } - - @Override - public String clientKill(final byte[] ipPort) { - checkIsInMultiOrPipeline(); - this.client.clientKill(ipPort); - return this.client.getStatusCodeReply(); - } - - @Override - public String clientKill(final String ip, final int port) { - checkIsInMultiOrPipeline(); - this.client.clientKill(ip, port); - return this.client.getStatusCodeReply(); - } - - @Override - public long clientKill(ClientKillParams params) { - checkIsInMultiOrPipeline(); - this.client.clientKill(params); - return this.client.getIntegerReply(); - } - - @Override - public byte[] clientGetnameBinary() { - checkIsInMultiOrPipeline(); - client.clientGetname(); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] clientListBinary() { - checkIsInMultiOrPipeline(); - client.clientList(); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] clientListBinary(ClientType type) { - checkIsInMultiOrPipeline(); - client.clientList(type); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] clientListBinary(final long... clientIds) { - checkIsInMultiOrPipeline(); - client.clientList(clientIds); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] clientInfoBinary() { - checkIsInMultiOrPipeline(); - client.clientInfo(); - return client.getBinaryBulkReply(); - } - - @Override - public String clientSetname(final byte[] name) { - checkIsInMultiOrPipeline(); - client.clientSetname(name); - return client.getBulkReply(); - } - - @Override - public long clientId() { - checkIsInMultiOrPipeline(); - client.clientId(); - return client.getIntegerReply(); - } - - /** - * Unblock a client blocked in a blocking command from a different connection. - * @param clientId - * @param unblockType could be {@code null} by default the client is unblocked as if the timeout - * of the command was reached - */ - @Override - public long clientUnblock(final long clientId, final UnblockType unblockType) { - checkIsInMultiOrPipeline(); - client.clientUnblock(clientId, unblockType); - return client.getIntegerReply(); - } - - @Override - public String clientPause(final long timeout) { - checkIsInMultiOrPipeline(); - client.clientPause(timeout); - return client.getBulkReply(); - } - - @Override - public String clientPause(final long timeout, final ClientPauseMode mode) { - checkIsInMultiOrPipeline(); - client.clientPause(timeout, mode); - return client.getBulkReply(); - } - - public List time() { - checkIsInMultiOrPipeline(); - client.time(); - return client.getMultiBulkReply(); - } - - @Override - public String migrate(final String host, final int port, final byte[] key, - final int destinationDb, final int timeout) { - checkIsInMultiOrPipeline(); - client.migrate(host, port, key, destinationDb, timeout); - return client.getStatusCodeReply(); - } - - @Override - public String migrate(final String host, final int port, final int destinationDB, - final int timeout, final MigrateParams params, final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.migrate(host, port, destinationDB, timeout, params, keys); - return client.getStatusCodeReply(); - } - - @Override - public long waitReplicas(final int replicas, final long timeout) { - checkIsInMultiOrPipeline(); - client.waitReplicas(replicas, timeout); - return client.getIntegerReply(); - } - - @Override - public long pfadd(final byte[] key, final byte[]... elements) { - checkIsInMultiOrPipeline(); - client.pfadd(key, elements); - return client.getIntegerReply(); - } - - @Override - public long pfcount(final byte[] key) { - checkIsInMultiOrPipeline(); - client.pfcount(key); - return client.getIntegerReply(); - } - - @Override - public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) { - checkIsInMultiOrPipeline(); - client.pfmerge(destkey, sourcekeys); - return client.getStatusCodeReply(); - } - - @Override - public long pfcount(final byte[]... keys) { - checkIsInMultiOrPipeline(); - client.pfcount(keys); - return client.getIntegerReply(); - } - - @Override - public ScanResult scan(final byte[] cursor) { - return scan(cursor, new ScanParams()); - } - - @Override - public ScanResult scan(final byte[] cursor, final ScanParams params) { - return scan(cursor, params, (byte[]) null); - } - - @Override - public ScanResult scan(final byte[] cursor, final ScanParams params, final byte[] type) { - checkIsInMultiOrPipeline(); - client.scan(cursor, params, type); - List result = client.getObjectMultiBulkReply(); - byte[] newcursor = (byte[]) result.get(0); - List rawResults = (List) result.get(1); - return new ScanResult<>(newcursor, rawResults); - } - - @Override - public ScanResult> hscan(final byte[] key, final byte[] cursor) { - return hscan(key, cursor, new ScanParams()); - } - - @Override - public ScanResult> hscan(final byte[] key, final byte[] cursor, - final ScanParams params) { - checkIsInMultiOrPipeline(); - client.hscan(key, cursor, params); - List result = client.getObjectMultiBulkReply(); - byte[] newcursor = (byte[]) result.get(0); - List> results = new ArrayList<>(); - List rawResults = (List) result.get(1); - Iterator iterator = rawResults.iterator(); - while (iterator.hasNext()) { - results.add(new AbstractMap.SimpleEntry<>(iterator.next(), iterator.next())); - } - return new ScanResult<>(newcursor, results); - } - - @Override - public ScanResult sscan(final byte[] key, final byte[] cursor) { - return sscan(key, cursor, new ScanParams()); - } - - @Override - public ScanResult sscan(final byte[] key, final byte[] cursor, final ScanParams params) { - checkIsInMultiOrPipeline(); - client.sscan(key, cursor, params); - List result = client.getObjectMultiBulkReply(); - byte[] newcursor = (byte[]) result.get(0); - List rawResults = (List) result.get(1); - return new ScanResult<>(newcursor, rawResults); - } - - @Override - public ScanResult zscan(final byte[] key, final byte[] cursor) { - return zscan(key, cursor, new ScanParams()); - } - - @Override - public ScanResult zscan(final byte[] key, final byte[] cursor, final ScanParams params) { - checkIsInMultiOrPipeline(); - client.zscan(key, cursor, params); - List result = client.getObjectMultiBulkReply(); - byte[] newcursor = (byte[]) result.get(0); - List results = new ArrayList<>(); - List rawResults = (List) result.get(1); - Iterator iterator = rawResults.iterator(); - while (iterator.hasNext()) { - results.add(new Tuple(iterator.next(), BuilderFactory.DOUBLE.build(iterator.next()))); - } - return new ScanResult<>(newcursor, results); - } - - @Override - public long geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { - checkIsInMultiOrPipeline(); - client.geoadd(key, longitude, latitude, member); - return client.getIntegerReply(); - } - - @Override - public long geoadd(final byte[] key, final Map memberCoordinateMap) { - checkIsInMultiOrPipeline(); - client.geoadd(key, memberCoordinateMap); - return client.getIntegerReply(); - } - - @Override - public long geoadd(final byte[] key, final GeoAddParams params, final Map memberCoordinateMap) { - checkIsInMultiOrPipeline(); - client.geoadd(key, params, memberCoordinateMap); - return client.getIntegerReply(); - } - - @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2) { - checkIsInMultiOrPipeline(); - client.geodist(key, member1, member2); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { - checkIsInMultiOrPipeline(); - client.geodist(key, member1, member2, unit); - return BuilderFactory.DOUBLE.build(client.getOne()); - } - - @Override - public List geohash(final byte[] key, final byte[]... members) { - checkIsInMultiOrPipeline(); - client.geohash(key, members); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List geopos(final byte[] key, final byte[]... members) { - checkIsInMultiOrPipeline(); - client.geopos(key, members); - return BuilderFactory.GEO_COORDINATE_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - checkIsInMultiOrPipeline(); - client.georadius(key, longitude, latitude, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public List georadiusReadonly(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - checkIsInMultiOrPipeline(); - client.georadiusReadonly(key, longitude, latitude, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - checkIsInMultiOrPipeline(); - client.georadius(key, longitude, latitude, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public long georadiusStore(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - checkIsInMultiOrPipeline(); - client.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam); - return client.getIntegerReply(); - } - - @Override - public List georadiusReadonly(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - checkIsInMultiOrPipeline(); - client.georadiusReadonly(key, longitude, latitude, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public List georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - checkIsInMultiOrPipeline(); - client.georadiusByMember(key, member, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public List georadiusByMemberReadonly(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - checkIsInMultiOrPipeline(); - client.georadiusByMemberReadonly(key, member, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public List georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - checkIsInMultiOrPipeline(); - client.georadiusByMember(key, member, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - @Override - public long georadiusByMemberStore(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit, final GeoRadiusParam param, final GeoRadiusStoreParam storeParam) { - checkIsInMultiOrPipeline(); - client.georadiusByMemberStore(key, member, radius, unit, param, storeParam); - return client.getIntegerReply(); - } - - @Override - public List georadiusByMemberReadonly(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - checkIsInMultiOrPipeline(); - client.georadiusByMemberReadonly(key, member, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); - } - - /** - * A decorator to implement Set from List. Assume that given List do not contains duplicated - * values. The resulting set displays the same ordering, concurrency, and performance - * characteristics as the backing list. This class should be used only for Redis commands which - * return Set result. - * @param - */ - protected static class SetFromList extends AbstractSet implements Serializable { - private static final long serialVersionUID = -2850347066962734052L; - private final List list; - - private SetFromList(List list) { - this.list = list; - } - - @Override - public void clear() { - list.clear(); - } - - @Override - public int size() { - return list.size(); - } - - @Override - public boolean isEmpty() { - return list.isEmpty(); - } - - @Override - public boolean contains(Object o) { - return list.contains(o); - } - - @Override - public boolean remove(Object o) { - return list.remove(o); - } - - @Override - public boolean add(E e) { - return !contains(e) && list.add(e); - } - - @Override - public Iterator iterator() { - return list.iterator(); - } - - @Override - public Object[] toArray() { - return list.toArray(); - } - - @Override - public T[] toArray(T[] a) { - return list.toArray(a); - } - - @Override - public String toString() { - return list.toString(); - } - - @Override - public int hashCode() { - return list.hashCode(); - } - - @Override - public boolean equals(Object o) { - if (o == null) return false; - if (o == this) return true; - if (!(o instanceof Set)) return false; - - Collection c = (Collection) o; - if (c.size() != size()) { - return false; - } - - return containsAll(c); - } - - @Override - public boolean containsAll(Collection c) { - return list.containsAll(c); - } - - @Override - public boolean removeAll(Collection c) { - return list.removeAll(c); - } - - @Override - public boolean retainAll(Collection c) { - return list.retainAll(c); - } - - protected static SetFromList of(List list) { - if (list == null) { - return null; - } - return new SetFromList<>(list); - } - } - - @Override - public List bitfield(final byte[] key, final byte[]... arguments) { - checkIsInMultiOrPipeline(); - client.bitfield(key, arguments); - return client.getIntegerMultiBulkReply(); - } - - @Override - public List bitfieldReadonly(byte[] key, final byte[]... arguments) { - checkIsInMultiOrPipeline(); - client.bitfieldReadonly(key, arguments); - return client.getIntegerMultiBulkReply(); - } - - @Override - public long hstrlen(final byte[] key, final byte[] field) { - checkIsInMultiOrPipeline(); - client.hstrlen(key, field); - return client.getIntegerReply(); - } - - @Override - public List xread(int count, long block, Map streams) { - checkIsInMultiOrPipeline(); - client.xread(count, block, streams); - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public List xread(XReadParams xReadParams, Entry... streams) { - checkIsInMultiOrPipeline(); - client.xread(xReadParams, streams); - - if (!xReadParams.hasBlock()) { - return client.getBinaryMultiBulkReply(); - } - - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public List xreadGroup(byte[] groupname, byte[] consumer, int count, long block, - boolean noAck, Map streams) { - checkIsInMultiOrPipeline(); - client.xreadGroup(groupname, consumer, count, block, noAck, streams); - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public List xreadGroup(byte[] groupname, byte[] consumer, - XReadGroupParams xReadGroupParams, Entry... streams) { - checkIsInMultiOrPipeline(); - client.xreadGroup(groupname, consumer, xReadGroupParams, streams); - - if (!xReadGroupParams.hasBlock()) { - return client.getBinaryMultiBulkReply(); - } - - client.setTimeoutInfinite(); - try { - return client.getBinaryMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } - } - - @Override - public byte[] xadd(byte[] key, byte[] id, Map hash, long maxLen, - boolean approximateLength) { - checkIsInMultiOrPipeline(); - client.xadd(key, id, hash, maxLen, approximateLength); - return client.getBinaryBulkReply(); - } - - @Override - public byte[] xadd(final byte[] key, final Map hash, final XAddParams params) { - checkIsInMultiOrPipeline(); - client.xadd(key, hash, params); - return client.getBinaryBulkReply(); - } - - @Override - public long xlen(byte[] key) { - checkIsInMultiOrPipeline(); - client.xlen(key); - return client.getIntegerReply(); - } - - @Override - public List xrange(byte[] key, byte[] start, byte[] end) { - checkIsInMultiOrPipeline(); - client.xrange(key, start, end); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List xrange(byte[] key, byte[] start, byte[] end, int count) { - checkIsInMultiOrPipeline(); - client.xrange(key, start, end, count); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List xrevrange(byte[] key, byte[] end, byte[] start) { - checkIsInMultiOrPipeline(); - client.xrevrange(key, end, start); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List xrevrange(byte[] key, byte[] end, byte[] start, int count) { - checkIsInMultiOrPipeline(); - client.xrevrange(key, end, start, count); - return client.getBinaryMultiBulkReply(); - } - - @Override - public long xack(byte[] key, byte[] group, byte[]... ids) { - checkIsInMultiOrPipeline(); - client.xack(key, group, ids); - return client.getIntegerReply(); - } - - @Override - public String xgroupCreate(byte[] key, byte[] consumer, byte[] id, boolean makeStream) { - checkIsInMultiOrPipeline(); - client.xgroupCreate(key, consumer, id, makeStream); - return client.getStatusCodeReply(); - } - - @Override - public String xgroupSetID(byte[] key, byte[] consumer, byte[] id) { - checkIsInMultiOrPipeline(); - client.xgroupSetID(key, consumer, id); - return client.getStatusCodeReply(); - } - - @Override - public long xgroupDestroy(byte[] key, byte[] consumer) { - checkIsInMultiOrPipeline(); - client.xgroupDestroy(key, consumer); - return client.getIntegerReply(); - } - - @Override - public long xgroupDelConsumer(byte[] key, byte[] consumer, byte[] consumerName) { - checkIsInMultiOrPipeline(); - client.xgroupDelConsumer(key, consumer, consumerName); - return client.getIntegerReply(); - } - - @Override - public long xdel(byte[] key, byte[]... ids) { - checkIsInMultiOrPipeline(); - client.xdel(key, ids); - return client.getIntegerReply(); - } - - @Override - public long xtrim(byte[] key, long maxLen, boolean approximateLength) { - checkIsInMultiOrPipeline(); - client.xtrim(key, maxLen, approximateLength); - return client.getIntegerReply(); - } - - @Override - public long xtrim(byte[] key, XTrimParams params) { - checkIsInMultiOrPipeline(); - client.xtrim(key, params); - return client.getIntegerReply(); - } - - @Override - public List xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, - byte[] consumername) { - checkIsInMultiOrPipeline(); - client.xpending(key, groupname, start, end, count, consumername); - return client.getObjectMultiBulkReply(); - } - - @Override - public Object xpending(final byte[] key, final byte[] groupname) { - checkIsInMultiOrPipeline(); - client.xpending(key, groupname); - return client.getOne(); - } - - @Override - public List xpending(final byte[] key, final byte[] groupname, final XPendingParams params) { - checkIsInMultiOrPipeline(); - client.xpending(key, groupname, params); - return client.getObjectMultiBulkReply(); - } - - @Override - public List xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, byte[]... ids) { - checkIsInMultiOrPipeline(); - client.xclaim(key, groupname, consumername, minIdleTime, newIdleTime, retries, force, ids); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - checkIsInMultiOrPipeline(); - client.xclaim(key, group, consumername, minIdleTime, params, ids); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - checkIsInMultiOrPipeline(); - client.xclaimJustId(key, group, consumername, minIdleTime, params, ids); - return client.getBinaryMultiBulkReply(); - } - - @Override - public List xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - checkIsInMultiOrPipeline(); - client.xautoclaim(key, groupName, consumerName, minIdleTime, start, params); - return client.getObjectMultiBulkReply(); - } - - @Override - public List xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - checkIsInMultiOrPipeline(); - client.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params); - return client.getObjectMultiBulkReply(); - } - - @Override - public StreamInfo xinfoStream(byte[] key) { - checkIsInMultiOrPipeline(); - client.xinfoStream(key); - return BuilderFactory.STREAM_INFO.build(client.getOne()); - } - - @Override - public Object xinfoStreamBinary(byte[] key) { - checkIsInMultiOrPipeline(); - client.xinfoStream(key); - return client.getOne(); - } - - @Override - public List xinfoGroup(byte[] key) { - checkIsInMultiOrPipeline(); - client.xinfoGroup(key); - return BuilderFactory.STREAM_GROUP_INFO_LIST.build(client.getBinaryMultiBulkReply()); - } - - @Override - public List xinfoGroupBinary(byte[] key) { - checkIsInMultiOrPipeline(); - client.xinfoGroup(key); - return client.getObjectMultiBulkReply(); - } - - @Override - public List xinfoConsumers(byte[] key, byte[] group) { - checkIsInMultiOrPipeline(); - client.xinfoConsumers(key, group); - return BuilderFactory.STREAM_CONSUMERS_INFO_LIST.build(client.getBinaryMultiBulkReply()); - } - - @Override - public List xinfoConsumersBinary(byte[] key, byte[] group) { - checkIsInMultiOrPipeline(); - client.xinfoConsumers(key, group); - return client.getObjectMultiBulkReply(); - } - - public Object sendCommand(ProtocolCommand cmd, byte[]... args) { - checkIsInMultiOrPipeline(); - client.sendCommand(cmd, args); - return client.getOne(); - } - - public Object sendBlockingCommand(ProtocolCommand cmd, byte[]... args) { - checkIsInMultiOrPipeline(); - client.sendCommand(cmd, args); - client.setTimeoutInfinite(); - try { - return client.getOne(); - } finally { - client.rollbackTimeout(); - } - } - - public Object sendCommand(ProtocolCommand cmd) { - return sendCommand(cmd, DUMMY_ARRAY); - } -} diff --git a/src/main/java/redis/clients/jedis/BinaryJedisCluster.java b/src/main/java/redis/clients/jedis/BinaryJedisCluster.java deleted file mode 100644 index 7d8f2c86d1..0000000000 --- a/src/main/java/redis/clients/jedis/BinaryJedisCluster.java +++ /dev/null @@ -1,2909 +0,0 @@ -package redis.clients.jedis; - -import redis.clients.jedis.args.*; -import redis.clients.jedis.commands.BinaryJedisClusterCommands; -import redis.clients.jedis.commands.JedisClusterBinaryScriptingCommands; -import redis.clients.jedis.commands.MultiKeyBinaryJedisClusterCommands; -import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.LCSMatchResult; -import redis.clients.jedis.util.JedisClusterHashTagUtil; -import redis.clients.jedis.util.KeyMergeUtil; -import redis.clients.jedis.util.SafeEncoder; - -import java.io.Closeable; -import java.time.Duration; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - -public class BinaryJedisCluster implements BinaryJedisClusterCommands, - MultiKeyBinaryJedisClusterCommands, JedisClusterBinaryScriptingCommands, Closeable { - - public static final int HASHSLOTS = 16384; - - /** - * Default timeout in milliseconds. - */ - public static final int DEFAULT_TIMEOUT = 2000; - public static final int DEFAULT_MAX_ATTEMPTS = 5; - - protected int maxAttempts; - - /** - * After this amount of time there will be no more retries and the operation will be failed. - * - * Defaults to {@code soTimeout * maxAttempts}. - */ - protected Duration maxTotalRetriesDuration; - - protected JedisClusterConnectionHandler connectionHandler; - - public BinaryJedisCluster(Set nodes) { - this(nodes, DEFAULT_TIMEOUT); - } - - public BinaryJedisCluster(Set nodes, int timeout) { - this(nodes, timeout, DEFAULT_MAX_ATTEMPTS, new GenericObjectPoolConfig()); - } - - public BinaryJedisCluster(Set jedisClusterNode, int timeout, int maxAttempts, - final GenericObjectPoolConfig poolConfig) { - this(jedisClusterNode, timeout, timeout, maxAttempts, poolConfig); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, poolConfig); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, null, poolConfig); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String password, String clientName, - GenericObjectPoolConfig poolConfig) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, - poolConfig); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String user, String password, String clientName, - GenericObjectPoolConfig poolConfig) { - this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - connectionTimeout, soTimeout, user, password, clientName); - this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = Duration.ofMillis((long) soTimeout * maxAttempts); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int infiniteSoTimeout, int maxAttempts, String user, String password, - String clientName, GenericObjectPoolConfig poolConfig) { - this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - connectionTimeout, soTimeout, infiniteSoTimeout, user, password, clientName); - this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = Duration.ofMillis((long) soTimeout * maxAttempts); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl) { - this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, - poolConfig, ssl); - } - - public BinaryJedisCluster(Set jedisClusterNode, int connectionTimeout, - int soTimeout, int maxAttempts, String user, String password, String clientName, - GenericObjectPoolConfig poolConfig, boolean ssl) { - this(jedisClusterNode, - DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).user(user).password(password).clientName(clientName) - .ssl(ssl).build(), - maxAttempts, poolConfig); - } - - public BinaryJedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, - int maxAttempts, GenericObjectPoolConfig poolConfig) { - this(jedisClusterNode, clientConfig, maxAttempts, - Duration.ofMillis((long) clientConfig.getSocketTimeoutMillis() * maxAttempts), poolConfig); - } - - public BinaryJedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, - int maxAttempts, Duration maxTotalRetriesDuration, GenericObjectPoolConfig poolConfig) { - this.connectionHandler = new JedisSlotBasedConnectionHandler(jedisClusterNode, poolConfig, - clientConfig); - this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = maxTotalRetriesDuration; - } - - @Override - public void close() { - if (connectionHandler != null) { - connectionHandler.close(); - } - } - - public Map getClusterNodes() { - return connectionHandler.getNodes(); - } - - public Jedis getConnectionFromSlot(int slot) { - return this.connectionHandler.getConnectionFromSlot(slot); - } - - @Override - public boolean copy(byte[] srcKey, byte[] dstKey, boolean replace) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.copy(srcKey, dstKey, replace); - } - }.runBinary(2, srcKey, dstKey); - } - - @Override - public String set(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.set(key, value); - } - }.runBinary(key); - } - - @Override - public String set(final byte[] key, final byte[] value, final SetParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.set(key, value, params); - } - }.runBinary(key); - } - - @Override - public byte[] get(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.get(key); - } - }.runBinary(key); - } - - @Override - public byte[] getDel(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.getDel(key); - } - }.runBinary(key); - } - - @Override - public byte[] getEx(byte[] key, GetExParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.getEx(key, params); - } - }.runBinary(key); - } - - @Override - public long exists(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.exists(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public boolean exists(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.exists(key); - } - }.runBinary(key); - } - - @Override - public long persist(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.persist(key); - } - }.runBinary(key); - } - - @Override - public String type(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.type(key); - } - }.runBinary(key); - } - - @Override - public byte[] dump(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.dump(key); - } - }.runBinary(key); - } - - @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.restore(key, ttl, serializedValue); - } - }.runBinary(key); - } - - @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.restore(key, ttl, serializedValue, params); - } - }.runBinary(key); - } - - @Override - public long expire(final byte[] key, final long seconds) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.expire(key, seconds); - } - }.runBinary(key); - } - - @Override - public long pexpire(final byte[] key, final long milliseconds) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pexpire(key, milliseconds); - } - }.runBinary(key); - } - - @Override - public long expireAt(final byte[] key, final long unixTime) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.expireAt(key, unixTime); - } - }.runBinary(key); - } - - @Override - public long pexpireAt(final byte[] key, final long millisecondsTimestamp) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pexpireAt(key, millisecondsTimestamp); - } - }.runBinary(key); - } - - @Override - public long ttl(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.ttl(key); - } - }.runBinary(key); - } - - @Override - public long pttl(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pttl(key); - } - }.runBinary(key); - } - - @Override - public long touch(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.touch(key); - } - }.runBinary(key); - } - - @Override - public long touch(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.touch(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public boolean setbit(final byte[] key, final long offset, final boolean value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.setbit(key, offset, value); - } - }.runBinary(key); - } - - @Override - public Boolean setbit(final byte[] key, final long offset, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.setbit(key, offset, value); - } - }.runBinary(key); - } - - @Override - public boolean getbit(final byte[] key, final long offset) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.getbit(key, offset); - } - }.runBinary(key); - } - - @Override - public long setrange(final byte[] key, final long offset, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.setrange(key, offset, value); - } - }.runBinary(key); - } - - @Override - public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.getrange(key, startOffset, endOffset); - } - }.runBinary(key); - } - - @Override - public byte[] getSet(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.getSet(key, value); - } - }.runBinary(key); - } - - @Override - public long setnx(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.setnx(key, value); - } - }.runBinary(key); - } - - @Override - public String psetex(final byte[] key, final long milliseconds, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.psetex(key, milliseconds, value); - } - }.runBinary(key); - } - - @Override - public String setex(final byte[] key, final long seconds, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.setex(key, seconds, value); - } - }.runBinary(key); - } - - @Override - public long decrBy(final byte[] key, final long decrement) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.decrBy(key, decrement); - } - }.runBinary(key); - } - - @Override - public long decr(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.decr(key); - } - }.runBinary(key); - } - - @Override - public long incrBy(final byte[] key, final long increment) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.incrBy(key, increment); - } - }.runBinary(key); - } - - @Override - public double incrByFloat(final byte[] key, final double increment) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.incrByFloat(key, increment); - } - }.runBinary(key); - } - - @Override - public long incr(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.incr(key); - } - }.runBinary(key); - } - - @Override - public long append(final byte[] key, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.append(key, value); - } - }.runBinary(key); - } - - @Override - public byte[] substr(final byte[] key, final int start, final int end) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.substr(key, start, end); - } - }.runBinary(key); - } - - @Override - public long hset(final byte[] key, final byte[] field, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hset(key, field, value); - } - }.runBinary(key); - } - - @Override - public long hset(final byte[] key, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hset(key, hash); - } - }.runBinary(key); - } - - @Override - public byte[] hget(final byte[] key, final byte[] field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.hget(key, field); - } - }.runBinary(key); - } - - @Override - public long hsetnx(final byte[] key, final byte[] field, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hsetnx(key, field, value); - } - }.runBinary(key); - } - - @Override - public String hmset(final byte[] key, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.hmset(key, hash); - } - }.runBinary(key); - } - - @Override - public List hmget(final byte[] key, final byte[]... fields) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.hmget(key, fields); - } - }.runBinary(key); - } - - @Override - public long hincrBy(final byte[] key, final byte[] field, final long value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hincrBy(key, field, value); - } - }.runBinary(key); - } - - @Override - public double hincrByFloat(final byte[] key, final byte[] field, final double value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.hincrByFloat(key, field, value); - } - }.runBinary(key); - } - - @Override - public boolean hexists(final byte[] key, final byte[] field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.hexists(key, field); - } - }.runBinary(key); - } - - @Override - public long hdel(final byte[] key, final byte[]... field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hdel(key, field); - } - }.runBinary(key); - } - - @Override - public long hlen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hlen(key); - } - }.runBinary(key); - } - - @Override - public Set hkeys(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.hkeys(key); - } - }.runBinary(key); - } - - @Override - public List hvals(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.hvals(key); - } - }.runBinary(key); - } - - @Override - public Map hgetAll(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Map execute(Jedis connection) { - return connection.hgetAll(key); - } - }.runBinary(key); - } - - @Override - public byte[] hrandfield(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.hrandfield(key); - } - }.runBinary(key); - } - - @Override - public List hrandfield(final byte[] key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.hrandfield(key, count); - } - }.runBinary(key); - } - - @Override - public Map hrandfieldWithValues(final byte[] key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Map execute(Jedis connection) { - return connection.hrandfieldWithValues(key, count); - } - }.runBinary(key); - } - - @Override - public long rpush(final byte[] key, final byte[]... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.rpush(key, args); - } - }.runBinary(key); - } - - @Override - public long lpush(final byte[] key, final byte[]... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpush(key, args); - } - }.runBinary(key); - } - - @Override - public long llen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.llen(key); - } - }.runBinary(key); - } - - @Override - public List lrange(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.lrange(key, start, stop); - } - }.runBinary(key); - } - - @Override - public String ltrim(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.ltrim(key, start, stop); - } - }.runBinary(key); - } - - @Override - public byte[] lindex(final byte[] key, final long index) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.lindex(key, index); - } - }.runBinary(key); - } - - @Override - public String lset(final byte[] key, final long index, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.lset(key, index, value); - } - }.runBinary(key); - } - - @Override - public long lrem(final byte[] key, final long count, final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lrem(key, count, value); - } - }.runBinary(key); - } - - @Override - public byte[] lpop(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.lpop(key); - } - }.runBinary(key); - } - - @Override - public List lpop(final byte[] key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.lpop(key, count); - } - }.runBinary(key); - } - - @Override - public Long lpos(final byte[] key, final byte[] element) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpos(key, element); - } - }.runBinary(key); - } - - @Override - public Long lpos(final byte[] key, final byte[] element, final LPosParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpos(key, element, params); - } - }.runBinary(key); - } - - @Override - public List lpos(final byte[] key, final byte[] element, final LPosParams params, - final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.lpos(key, element, params, count); - } - }.runBinary(key); - } - - @Override - public byte[] rpop(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.rpop(key); - } - }.runBinary(key); - } - - @Override - public List rpop(final byte[] key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.rpop(key, count); - } - }.runBinary(key); - } - - @Override - public long sadd(final byte[] key, final byte[]... member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sadd(key, member); - } - }.runBinary(key); - } - - @Override - public Set smembers(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.smembers(key); - } - }.runBinary(key); - } - - @Override - public long srem(final byte[] key, final byte[]... member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.srem(key, member); - } - }.runBinary(key); - } - - @Override - public byte[] spop(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.spop(key); - } - }.runBinary(key); - } - - @Override - public Set spop(final byte[] key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.spop(key, count); - } - }.runBinary(key); - } - - @Override - public long scard(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.scard(key); - } - }.runBinary(key); - } - - @Override - public boolean sismember(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.sismember(key, member); - } - }.runBinary(key); - } - - @Override - public List smismember(final byte[] key, final byte[]... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.smismember(key, members); - } - }.runBinary(key); - } - - @Override - public byte[] srandmember(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.srandmember(key); - } - }.runBinary(key); - } - - @Override - public long strlen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.strlen(key); - } - }.runBinary(key); - } - - @Override - public LCSMatchResult strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public LCSMatchResult execute(Jedis connection) { - return connection.strAlgoLCSKeys(keyA, keyB, params); - } - }.runBinary(2, keyA, keyB); - } - - @Override - public LCSMatchResult strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public LCSMatchResult execute(Jedis connection) { - return connection.strAlgoLCSStrings(strA, strB, params); - } - }.runWithAnyNode(); - } - - @Override - public long zadd(final byte[] key, final double score, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, score, member); - } - }.runBinary(key); - } - - @Override - public long zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, score, member, params); - } - }.runBinary(key); - } - - @Override - public long zadd(final byte[] key, final Map scoreMembers) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, scoreMembers); - } - }.runBinary(key); - } - - @Override - public long zadd(final byte[] key, final Map scoreMembers, final ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, scoreMembers, params); - } - }.runBinary(key); - } - - @Override - public Double zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zaddIncr(key, score, member, params); - } - }.runBinary(key); - } - - @Override - public Set zdiff(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zdiff(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public Set zdiffWithScores(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zdiffWithScores(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long zdiffStore(final byte[] dstkey, final byte[]... keys) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zdiffStore(dstkey, keys); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public Set zrange(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrange(key, start, stop); - } - }.runBinary(key); - } - - @Override - public long zrem(final byte[] key, final byte[]... members) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zrem(key, members); - } - }.runBinary(key); - } - - @Override - public double zincrby(final byte[] key, final double increment, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zincrby(key, increment, member); - } - }.runBinary(key); - } - - @Override - public Double zincrby(final byte[] key, final double increment, final byte[] member, - final ZIncrByParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zincrby(key, increment, member, params); - } - }.runBinary(key); - } - - @Override - public Long zrank(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zrank(key, member); - } - }.runBinary(key); - } - - @Override - public Long zrevrank(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zrevrank(key, member); - } - }.runBinary(key); - } - - @Override - public Set zrevrange(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrange(key, start, stop); - } - }.runBinary(key); - } - - @Override - public Set zrangeWithScores(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeWithScores(key, start, stop); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeWithScores(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeWithScores(key, start, stop); - } - }.runBinary(key); - } - - @Override - public byte[] zrandmember(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.zrandmember(key); - } - }.runBinary(key); - } - - @Override - public Set zrandmember(final byte[] key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrandmember(key, count); - } - }.runBinary(key); - } - - @Override - public Set zrandmemberWithScores(final byte[] key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrandmemberWithScores(key, count); - } - }.runBinary(key); - } - - @Override - public long zcard(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zcard(key); - } - }.runBinary(key); - } - - @Override - public Double zscore(final byte[] key, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zscore(key, member); - } - }.runBinary(key); - } - - @Override - public List zmscore(final byte[] key, final byte[]... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.zmscore(key, members); - } - }.runBinary(key); - } - - @Override - public Tuple zpopmax(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Tuple execute(Jedis connection) { - return connection.zpopmax(key); - } - }.runBinary(key); - } - - @Override - public Set zpopmax(final byte[] key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zpopmax(key, count); - } - }.runBinary(key); - } - - @Override - public Tuple zpopmin(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Tuple execute(Jedis connection) { - return connection.zpopmin(key); - } - }.runBinary(key); - } - - @Override - public Set zpopmin(final byte[] key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zpopmin(key, count); - } - }.runBinary(key); - } - - @Override - public List sort(final byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.sort(key); - } - }.runBinary(key); - } - - @Override - public List sort(final byte[] key, final SortingParams sortingParameters) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.sort(key, sortingParameters); - } - }.runBinary(key); - } - - @Override - public long zcount(final byte[] key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zcount(key, min, max); - } - }.runBinary(key); - } - - @Override - public long zcount(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zcount(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScore(final byte[] key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScore(final byte[] key, final double min, final double max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min); - } - }.runBinary(key); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - }.runBinary(key); - } - - @Override - public long zremrangeByRank(final byte[] key, final long start, final long stop) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByRank(key, start, stop); - } - }.runBinary(key); - } - - @Override - public long zremrangeByScore(final byte[] key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByScore(key, min, max); - } - }.runBinary(key); - } - - @Override - public long zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByScore(key, min, max); - } - }.runBinary(key); - } - - @Override - public long linsert(final byte[] key, final ListPosition where, final byte[] pivot, - final byte[] value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.linsert(key, where, pivot, value); - } - }.runBinary(key); - } - - @Override - public long lpushx(final byte[] key, final byte[]... arg) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpushx(key, arg); - } - }.runBinary(key); - } - - @Override - public long rpushx(final byte[] key, final byte[]... arg) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.rpushx(key, arg); - } - }.runBinary(key); - } - - @Override - public long del(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.del(key); - } - }.runBinary(key); - } - - @Override - public long unlink(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.unlink(key); - } - }.runBinary(key); - } - - @Override - public long unlink(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.unlink(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public byte[] echo(final byte[] arg) { - // note that it'll be run from arbitary node - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.echo(arg); - } - }.runBinary(arg); - } - - @Override - public long bitcount(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitcount(key); - } - }.runBinary(key); - } - - @Override - public long bitcount(final byte[] key, final long start, final long end) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitcount(key, start, end); - } - }.runBinary(key); - } - - @Override - public long pfadd(final byte[] key, final byte[]... elements) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pfadd(key, elements); - } - }.runBinary(key); - } - - @Override - public long pfcount(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pfcount(key); - } - }.runBinary(key); - } - - @Override - public List srandmember(final byte[] key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.srandmember(key, count); - } - }.runBinary(key); - } - - @Override - public long zlexcount(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zlexcount(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByLex(key, min, max); - } - }.runBinary(key); - } - - @Override - public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByLex(key, min, max, offset, count); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByLex(key, max, min); - } - }.runBinary(key); - } - - @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByLex(key, max, min, offset, count); - } - }.runBinary(key); - } - - @Override - public long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByLex(key, min, max); - } - }.runBinary(key); - } - - @Override - public Object eval(final byte[] script, final byte[] keyCount, final byte[]... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script, keyCount, params); - } - }.runBinary(Integer.parseInt(SafeEncoder.encode(keyCount)), params); - } - - @Override - public Object eval(final byte[] script, final int keyCount, final byte[]... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script, keyCount, params); - } - }.runBinary(keyCount, params); - } - - @Override - public Object eval(final byte[] script, final List keys, final List args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script, keys, args); - } - }.runBinary(keys.size(), keys.toArray(new byte[keys.size()][])); - } - - @Override - public Object eval(final byte[] script, final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script); - } - }.runBinary(sampleKey); - } - - @Override - public Object evalsha(final byte[] sha1, final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.evalsha(sha1); - } - }.runBinary(sampleKey); - } - - @Override - public Object evalsha(final byte[] sha1, final List keys, final List args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.evalsha(sha1, keys, args); - } - }.runBinary(keys.size(), keys.toArray(new byte[keys.size()][])); - } - - @Override - public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.evalsha(sha1, keyCount, params); - } - }.runBinary(keyCount, params); - } - - @Override - public List scriptExists(final byte[] sampleKey, final byte[]... sha1) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.scriptExists(sha1); - } - }.runBinary(sampleKey); - } - - @Override - public byte[] scriptLoad(final byte[] script, final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.scriptLoad(script); - } - }.runBinary(sampleKey); - } - - @Override - public String scriptFlush(final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.scriptFlush(); - } - }.runBinary(sampleKey); - } - - @Override - public String scriptFlush(final byte[] sampleKey, final FlushMode flushMode) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.scriptFlush(flushMode); - } - }.runBinary(sampleKey); - } - - @Override - public String scriptKill(final byte[] sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.scriptKill(); - } - }.runBinary(sampleKey); - } - - @Override - public long del(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.del(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public byte[] lmove(final byte[] srcKey, final byte[] dstKey, final ListDirection from, - final ListDirection to) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.lmove(srcKey, dstKey, from, to); - } - }.runBinary(2, srcKey, dstKey); - } - - @Override - public byte[] blmove(final byte[] srcKey, final byte[] dstKey, final ListDirection from, - final ListDirection to, final double timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.blmove(srcKey, dstKey, from, to, timeout); - } - }.runBinary(2, srcKey, dstKey); - } - - @Override - public List blpop(final int timeout, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.blpop(timeout, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public List blpop(final double timeout, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.blpop(timeout, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public List brpop(final int timeout, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.brpop(timeout, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public List brpop(final double timeout, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.brpop(timeout, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public List bzpopmax(double timeout, byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.bzpopmax(timeout, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public List bzpopmin(double timeout, byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.bzpopmin(timeout, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public List mget(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.mget(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public String mset(final byte[]... keysvalues) { - byte[][] keys = new byte[keysvalues.length / 2][]; - - for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { - keys[keyIdx] = keysvalues[keyIdx * 2]; - } - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.mset(keysvalues); - } - }.runBinary(keys.length, keys); - } - - @Override - public long msetnx(final byte[]... keysvalues) { - byte[][] keys = new byte[keysvalues.length / 2][]; - - for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { - keys[keyIdx] = keysvalues[keyIdx * 2]; - } - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.msetnx(keysvalues); - } - }.runBinary(keys.length, keys); - } - - @Override - public String rename(final byte[] oldkey, final byte[] newkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.rename(oldkey, newkey); - } - }.runBinary(2, oldkey, newkey); - } - - @Override - public long renamenx(final byte[] oldkey, final byte[] newkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.renamenx(oldkey, newkey); - } - }.runBinary(2, oldkey, newkey); - } - - @Override - public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.rpoplpush(srckey, dstkey); - } - }.runBinary(2, srckey, dstkey); - } - - @Override - public Set sdiff(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.sdiff(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long sdiffstore(final byte[] dstkey, final byte[]... keys) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sdiffstore(dstkey, keys); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public Set sinter(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.sinter(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long sinterstore(final byte[] dstkey, final byte[]... keys) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sinterstore(dstkey, keys); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.smove(srckey, dstkey, member); - } - }.runBinary(2, srckey, dstkey); - } - - @Override - public long sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sort(key, sortingParameters, dstkey); - } - }.runBinary(2, key, dstkey); - } - - @Override - public long sort(final byte[] key, final byte[] dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sort(key, dstkey); - } - }.runBinary(2, key, dstkey); - } - - @Override - public Set sunion(final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.sunion(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long sunionstore(final byte[] dstkey, final byte[]... keys) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sunionstore(dstkey, keys); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public Set zinter(final ZParams params, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zinter(params, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public Set zinterWithScores(final ZParams params, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zinterWithScores(params, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long zinterstore(final byte[] dstkey, final byte[]... sets) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zinterstore(dstkey, sets); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public long zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zinterstore(dstkey, params, sets); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public Set zunion(final ZParams params, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zunion(params, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public Set zunionWithScores(final ZParams params, final byte[]... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zunionWithScores(params, keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long zunionstore(final byte[] dstkey, final byte[]... sets) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zunionstore(dstkey, sets); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public long zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { - byte[][] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zunionstore(dstkey, params, sets); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public byte[] brpoplpush(final byte[] source, final byte[] destination, final int timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.brpoplpush(source, destination, timeout); - } - }.runBinary(2, source, destination); - } - - @Override - public Long publish(final byte[] channel, final byte[] message) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.publish(channel, message); - } - }.runWithAnyNode(); - } - - @Override - public void subscribe(final BinaryJedisPubSub jedisPubSub, final byte[]... channels) { - new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Integer execute(Jedis connection) { - connection.subscribe(jedisPubSub, channels); - return 0; - } - }.runWithAnyNode(); - } - - @Override - public void psubscribe(final BinaryJedisPubSub jedisPubSub, final byte[]... patterns) { - new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Integer execute(Jedis connection) { - connection.psubscribe(jedisPubSub, patterns); - return 0; - } - }.runWithAnyNode(); - } - - @Override - public long bitop(final BitOP op, final byte[] destKey, final byte[]... srcKeys) { - byte[][] wholeKeys = KeyMergeUtil.merge(destKey, srcKeys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitop(op, destKey, srcKeys); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) { - byte[][] wholeKeys = KeyMergeUtil.merge(destkey, sourcekeys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.pfmerge(destkey, sourcekeys); - } - }.runBinary(wholeKeys.length, wholeKeys); - } - - @Override - public long pfcount(final byte[]... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pfcount(keys); - } - }.runBinary(keys.length, keys); - } - - @Override - public long geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.geoadd(key, longitude, latitude, member); - } - }.runBinary(key); - } - - @Override - public long geoadd(final byte[] key, final Map memberCoordinateMap) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.geoadd(key, memberCoordinateMap); - } - }.runBinary(key); - } - - @Override - public long geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.geoadd(key, params, memberCoordinateMap); - } - }.runBinary(key); - } - - @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.geodist(key, member1, member2); - } - }.runBinary(key); - } - - @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.geodist(key, member1, member2, unit); - } - }.runBinary(key); - } - - @Override - public List geohash(final byte[] key, final byte[]... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.geohash(key, members); - } - }.runBinary(key); - } - - @Override - public List geopos(final byte[] key, final byte[]... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.geopos(key, members); - } - }.runBinary(key); - } - - @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadius(key, longitude, latitude, radius, unit); - } - }.runBinary(key); - } - - @Override - public List georadiusReadonly(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusReadonly(key, longitude, latitude, radius, unit); - } - }.runBinary(key); - } - - @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadius(key, longitude, latitude, radius, unit, param); - } - }.runBinary(key); - } - - @Override - public long georadiusStore(final byte[] key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - byte[][] keys = storeParam.getByteKeys(key); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam); - } - }.runBinary(keys.length, keys); - } - - @Override - public List georadiusReadonly(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusReadonly(key, longitude, latitude, radius, unit, param); - } - }.runBinary(key); - } - - @Override - public List georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMember(key, member, radius, unit); - } - }.runBinary(key); - } - - @Override - public List georadiusByMemberReadonly(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMemberReadonly(key, member, radius, unit); - } - }.runBinary(key); - } - - @Override - public List georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMember(key, member, radius, unit, param); - } - }.runBinary(key); - } - - @Override - public long georadiusByMemberStore(final byte[] key, final byte[] member, final double radius, - final GeoUnit unit, final GeoRadiusParam param, final GeoRadiusStoreParam storeParam) { - byte[][] keys = storeParam.getByteKeys(key); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.georadiusByMemberStore(key, member, radius, unit, param, storeParam); - } - }.runBinary(keys.length, keys); - } - - @Override - public List georadiusByMemberReadonly(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMemberReadonly(key, member, radius, unit, param); - } - }.runBinary(key); - } - - @Override - public String unwatch() { - throw new UnsupportedOperationException("UNWATCH is not supported in cluster mode."); - } - - @Override - public Set keys(final byte[] pattern) { - if (pattern == null || pattern.length == 0) { - throw new IllegalArgumentException(this.getClass().getSimpleName() - + " only supports KEYS commands with non-empty patterns"); - } - if (!JedisClusterHashTagUtil.isClusterCompliantMatchPattern(pattern)) { - throw new IllegalArgumentException( - this.getClass().getSimpleName() - + " only supports KEYS commands with patterns containing hash-tags " - + "( curly-brackets enclosed strings )"); - } - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.keys(pattern); - } - }.runBinary(pattern); - } - - @Override - public ScanResult scan(final byte[] cursor, final ScanParams params) { - return scan(cursor, params, null); - } - - @Override - public ScanResult scan(final byte[] cursor, final ScanParams params, final byte[] type) { - - byte[] matchPattern = null; - - if (params == null || (matchPattern = params.binaryMatch()) == null || matchPattern.length == 0) { - throw new IllegalArgumentException(BinaryJedisCluster.class.getSimpleName() - + " only supports SCAN commands with non-empty MATCH patterns"); - } - - if (!JedisClusterHashTagUtil.isClusterCompliantMatchPattern(matchPattern)) { - throw new IllegalArgumentException( - BinaryJedisCluster.class.getSimpleName() - + " only supports SCAN commands with MATCH patterns containing hash-tags" - + " ( curly-brackets enclosed strings )"); - } - - return new JedisClusterCommand>(connectionHandler, maxAttempts, - maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.scan(cursor, params, type); - } - }.runBinary(matchPattern); - } - - @Override - public ScanResult> hscan(final byte[] key, final byte[] cursor) { - return new JedisClusterCommand>>(connectionHandler, - maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult> execute(Jedis connection) { - return connection.hscan(key, cursor); - } - }.runBinary(key); - } - - @Override - public ScanResult> hscan(final byte[] key, final byte[] cursor, - final ScanParams params) { - return new JedisClusterCommand>>(connectionHandler, - maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult> execute(Jedis connection) { - return connection.hscan(key, cursor, params); - } - }.runBinary(key); - } - - @Override - public ScanResult sscan(final byte[] key, final byte[] cursor) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.sscan(key, cursor); - } - }.runBinary(key); - } - - @Override - public ScanResult sscan(final byte[] key, final byte[] cursor, final ScanParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.sscan(key, cursor, params); - } - }.runBinary(key); - } - - @Override - public ScanResult zscan(final byte[] key, final byte[] cursor) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.zscan(key, cursor); - } - }.runBinary(key); - } - - @Override - public ScanResult zscan(final byte[] key, final byte[] cursor, final ScanParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.zscan(key, cursor, params); - } - }.runBinary(key); - } - - @Override - public List bitfield(final byte[] key, final byte[]... arguments) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.bitfield(key, arguments); - } - }.runBinary(key); - } - - @Override - public List bitfieldReadonly(final byte[] key, final byte[]... arguments) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.bitfieldReadonly(key, arguments); - } - }.runBinary(key); - } - - @Override - public long hstrlen(final byte[] key, final byte[] field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hstrlen(key, field); - } - }.runBinary(key); - } - - @Override - public Long memoryUsage(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.memoryUsage(key); - } - }.runBinary(key); - } - - @Override - public Long memoryUsage(final byte[] key, final int samples) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.memoryUsage(key, samples); - } - }.runBinary(key); - } - - @Override - public byte[] xadd(final byte[] key, final byte[] id, final Map hash, - final long maxLen, final boolean approximateLength) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.xadd(key, id, hash, maxLen, approximateLength); - } - }.runBinary(key); - } - - @Override - public byte[] xadd(final byte[] key, final Map hash, final XAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.xadd(key, hash, params); - } - }.runBinary(key); - } - - @Override - public long xlen(final byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xlen(key); - } - }.runBinary(key); - } - - @Override - public List xrange(final byte[] key, final byte[] start, final byte[] end) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrange(key, start, end); - } - }.runBinary(key); - } - - @Override - public List xrange(final byte[] key, final byte[] start, final byte[] end, - final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrange(key, start, end, count); - } - }.runBinary(key); - } - - @Override - public List xrange(final byte[] key, final byte[] start, final byte[] end, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrange(key, start, end, count); - } - }.runBinary(key); - } - - @Override - public List xrevrange(final byte[] key, final byte[] end, final byte[] start) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrevrange(key, end, start); - } - }.runBinary(key); - } - - @Override - public List xrevrange(final byte[] key, final byte[] end, final byte[] start, - final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrevrange(key, end, start, count); - } - }.runBinary(key); - } - - @Override - public List xread(final int count, final long block, final Map streams) { - byte[][] keys = streams.keySet().toArray(new byte[streams.size()][]); - - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xread(count, block, streams); - } - }.runBinary(keys.length, keys); - } - - @Override - public List xread(final XReadParams xReadParams, final Entry... streams) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xread(xReadParams, streams); - } - }.runBinary(streams.length, getKeys(streams)); - } - - @Override - public long xack(final byte[] key, final byte[] group, final byte[]... ids) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xack(key, group, ids); - } - }.runBinary(key); - } - - @Override - public String xgroupCreate(final byte[] key, final byte[] consumer, final byte[] id, - final boolean makeStream) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.xgroupCreate(key, consumer, id, makeStream); - } - }.runBinary(key); - } - - @Override - public String xgroupSetID(final byte[] key, final byte[] consumer, final byte[] id) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.xgroupSetID(key, consumer, id); - } - }.runBinary(key); - } - - @Override - public long xgroupDestroy(final byte[] key, final byte[] consumer) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xgroupDestroy(key, consumer); - } - }.runBinary(key); - } - - @Override - public long xgroupDelConsumer(final byte[] key, final byte[] consumer, final byte[] consumerName) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xgroupDelConsumer(key, consumer, consumerName); - } - }.runBinary(key); - } - - @Override - public List xreadGroup(final byte[] groupname, final byte[] consumer, final int count, - final long block, final boolean noAck, final Map streams) { - - byte[][] keys = streams.keySet().toArray(new byte[streams.size()][]); - - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xreadGroup(groupname, consumer, count, block, noAck, streams); - } - }.runBinary(keys.length, keys); - } - - @Override - public List xreadGroup(final byte[] groupname, final byte[] consumer, final XReadGroupParams xReadGroupParams, - final Entry... streams) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xreadGroup(groupname, consumer, xReadGroupParams, streams); - } - }.runBinary(streams.length, getKeys(streams)); - } - - @Override - public long xdel(final byte[] key, final byte[]... ids) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xdel(key, ids); - } - }.runBinary(key); - } - - @Override - public long xtrim(final byte[] key, final long maxLen, final boolean approximateLength) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xtrim(key, maxLen, approximateLength); - } - }.runBinary(key); - } - - @Override - public long xtrim(final byte[] key, final XTrimParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xtrim(key, params); - } - }.runBinary(key); - } - - @Override - public List xpending(final byte[] key, final byte[] groupname, final byte[] start, - final byte[] end, final int count, final byte[] consumername) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xpending(key, groupname, start, end, count, consumername); - } - }.runBinary(key); - } - - @Override - public Object xpending(final byte[] key, final byte[] groupname) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.xpending(key, groupname); - } - }.runBinary(key); - } - - @Override - public List xpending(final byte[] key, final byte[] groupname, final XPendingParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xpending(key, groupname, params); - } - }.runBinary(key); - } - - @Override - public List xclaim(final byte[] key, final byte[] groupname, final byte[] consumername, - final long minIdleTime, final long newIdleTime, final int retries, final boolean force, - final byte[][] ids) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xclaim(key, groupname, consumername, minIdleTime, newIdleTime, retries, - force, ids); - } - }.runBinary(key); - } - - @Override - public List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xclaim(key, group, consumername, minIdleTime, params, ids); - } - }.runBinary(key); - } - - @Override - public List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xclaimJustId(key, group, consumername, minIdleTime, params, ids); - } - }.runBinary(key); - } - - @Override - public List xautoclaim(final byte[] key, final byte[] groupName, final byte[] consumerName, - final long minIdleTime, final byte[] start, XAutoClaimParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xautoclaim(key, groupName, consumerName, minIdleTime, start, params); - } - }.runBinary(key); - } - - @Override - public List xautoclaimJustId(final byte[] key, final byte[] groupName, final byte[] consumerName, - final long minIdleTime, final byte[] start, XAutoClaimParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params); - } - }.runBinary(key); - } - - @Override - public Object xinfoStreamBinary(byte[] key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.xinfoStreamBinary(key); - } - }.runBinary(key); - } - - @Override - public List xinfoGroupBinary(byte[] key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xinfoGroupBinary(key); - } - }.runBinary(key); - } - - @Override - public List xinfoConsumersBinary(byte[] key, byte[] group) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xinfoConsumersBinary(key, group); - } - }.runBinary(key); - } - - @Override - public long waitReplicas(final byte[] key, final int replicas, final long timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.waitReplicas(replicas, timeout); - } - }.runBinary(key); - } - - public Object sendCommand(final byte[] sampleKey, final ProtocolCommand cmd, final byte[]... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.sendCommand(cmd, args); - } - }.runBinary(sampleKey); - } - - public Object sendBlockingCommand(final byte[] sampleKey, final ProtocolCommand cmd, - final byte[]... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.sendBlockingCommand(cmd, args); - } - }.runBinary(sampleKey); - } - - private static byte[][] getKeys(final Entry... entries) { - byte[][] keys = new byte[entries.length][]; - for (int i = 0; i < entries.length; i++) { - keys[i] = entries[i].getKey(); - } - return keys; - } -} diff --git a/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java b/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java index d0582a0d54..e49fdda860 100644 --- a/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java +++ b/src/main/java/redis/clients/jedis/BinaryJedisPubSub.java @@ -1,21 +1,16 @@ package redis.clients.jedis; -import static redis.clients.jedis.Protocol.Keyword.MESSAGE; -import static redis.clients.jedis.Protocol.Keyword.PMESSAGE; -import static redis.clients.jedis.Protocol.Keyword.PONG; -import static redis.clients.jedis.Protocol.Keyword.PSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.PUNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.SUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.UNSUBSCRIBE; +import static redis.clients.jedis.Protocol.ResponseKeyword.*; import java.util.Arrays; import java.util.List; +import redis.clients.jedis.Protocol.Command; import redis.clients.jedis.exceptions.JedisException; public abstract class BinaryJedisPubSub { private int subscribedChannels = 0; - private Client client; + private Connection client; public void onMessage(byte[] channel, byte[] message) { } @@ -39,42 +34,42 @@ public void onPong(byte[] pattern) { } public void unsubscribe() { - client.unsubscribe(); + client.sendCommand(Command.UNSUBSCRIBE); client.flush(); } public void unsubscribe(byte[]... channels) { - client.unsubscribe(channels); + client.sendCommand(Command.UNSUBSCRIBE, channels); client.flush(); } public void subscribe(byte[]... channels) { - client.subscribe(channels); + client.sendCommand(Command.SUBSCRIBE, channels); client.flush(); } public void psubscribe(byte[]... patterns) { - client.psubscribe(patterns); + client.sendCommand(Command.PSUBSCRIBE, patterns); client.flush(); } public void punsubscribe() { - client.punsubscribe(); + client.sendCommand(Command.PUNSUBSCRIBE); client.flush(); } public void punsubscribe(byte[]... patterns) { - client.punsubscribe(patterns); + client.sendCommand(Command.PUNSUBSCRIBE, patterns); client.flush(); } public void ping() { - client.ping(); + client.sendCommand(Command.PING); client.flush(); } public void ping(byte[] argument) { - client.ping(argument); + client.sendCommand(Command.PING, argument); client.flush(); } @@ -82,21 +77,25 @@ public boolean isSubscribed() { return subscribedChannels > 0; } - public void proceedWithPatterns(Client client, byte[]... patterns) { + public void proceedWithPatterns(Connection client, byte[]... patterns) { this.client = client; - client.psubscribe(patterns); - client.flush(); - process(client); +// client.psubscribe(patterns); +// client.flush(); + psubscribe(patterns); +// process(client); + process(); } - public void proceed(Client client, byte[]... channels) { + public void proceed(Connection client, byte[]... channels) { this.client = client; - client.subscribe(channels); - client.flush(); - process(client); +// client.subscribe(channels); +// client.flush(); + subscribe(channels); +// process(client); + process(); } - private void process(Client client) { + private void process() { do { List reply = client.getUnflushedObjectMultiBulkReply(); final Object firstObj = reply.get(0); diff --git a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java b/src/main/java/redis/clients/jedis/BinaryShardedJedis.java deleted file mode 100644 index 5e2db46633..0000000000 --- a/src/main/java/redis/clients/jedis/BinaryShardedJedis.java +++ /dev/null @@ -1,1334 +0,0 @@ -package redis.clients.jedis; - -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.Pattern; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.commands.BinaryJedisCommands; -import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.params.GeoAddParams; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GetExParams; -import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.params.SetParams; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.params.ZAddParams; -import redis.clients.jedis.params.ZIncrByParams; -import redis.clients.jedis.params.LPosParams; -import redis.clients.jedis.resps.LCSMatchResult; -import redis.clients.jedis.util.Hashing; -import redis.clients.jedis.util.Sharded; - -public class BinaryShardedJedis extends Sharded implements - BinaryJedisCommands { - - private static final Logger logger = LoggerFactory.getLogger(BinaryShardedJedis.class); - - private final byte[][] dummyArray = new byte[0][]; - - public BinaryShardedJedis(List shards) { - super(shards); - } - - public BinaryShardedJedis(List shards, Hashing algo) { - super(shards, algo); - } - - public BinaryShardedJedis(List shards, Pattern keyTagPattern) { - super(shards, keyTagPattern); - } - - public BinaryShardedJedis(List shards, Hashing algo, Pattern keyTagPattern) { - super(shards, algo, keyTagPattern); - } - - public void disconnect() { - for (Jedis jedis : getAllShards()) { - if (jedis.isConnected()) { - try { - // need a proper test, probably with mock - if (!jedis.isBroken()) { - jedis.quit(); - } - } catch (JedisConnectionException e) { - // ignore the exception node, so that all other normal nodes can release all connections. - logger.warn("Error while QUIT", e); - } - try { - jedis.disconnect(); - } catch (JedisConnectionException e) { - // ignore the exception node, so that all other normal nodes can release all connections. - logger.warn("Error while disconnect", e); - } - } - } - } - - protected Jedis create(JedisShardInfo shard) { - return new Jedis(shard); - } - - @Override - public String set(final byte[] key, final byte[] value) { - Jedis j = getShard(key); - return j.set(key, value); - } - - @Override - public String set(final byte[] key, final byte[] value, SetParams params) { - Jedis j = getShard(key); - return j.set(key, value, params); - } - - @Override - public byte[] get(final byte[] key) { - Jedis j = getShard(key); - return j.get(key); - } - - @Override - public byte[] getDel(final byte[] key) { - Jedis j = getShard(key); - return j.getDel(key); - } - - @Override - public byte[] getEx(byte[] key, GetExParams params) { - Jedis j = getShard(key); - return j.getEx(key, params); - } - - @Override - public boolean exists(final byte[] key) { - Jedis j = getShard(key); - return j.exists(key); - } - - @Override - public String type(final byte[] key) { - Jedis j = getShard(key); - return j.type(key); - } - - @Override - public byte[] dump(final byte[] key) { - Jedis j = getShard(key); - return j.dump(key); - } - - @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { - Jedis j = getShard(key); - return j.restore(key, ttl, serializedValue); - } - - @Override - public String restoreReplace(final byte[] key, final long ttl, final byte[] serializedValue) { - Jedis j = getShard(key); - return j.restoreReplace(key, ttl, serializedValue); - } - - @Override - public String restore(final byte[] key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - Jedis j = getShard(key); - return j.restore(key, ttl, serializedValue, params); - } - - @Override - public long expire(final byte[] key, final long seconds) { - Jedis j = getShard(key); - return j.expire(key, seconds); - } - - @Override - public long pexpire(final byte[] key, final long milliseconds) { - Jedis j = getShard(key); - return j.pexpire(key, milliseconds); - } - - @Override - public long expireAt(final byte[] key, final long unixTime) { - Jedis j = getShard(key); - return j.expireAt(key, unixTime); - } - - @Override - public long pexpireAt(final byte[] key, final long millisecondsTimestamp) { - Jedis j = getShard(key); - return j.pexpireAt(key, millisecondsTimestamp); - } - - @Override - public long ttl(final byte[] key) { - Jedis j = getShard(key); - return j.ttl(key); - } - - @Override - public long pttl(final byte[] key) { - Jedis j = getShard(key); - return j.pttl(key); - } - - @Override - public long touch(final byte[] key) { - Jedis j = getShard(key); - return j.touch(key); - } - - @Override - public byte[] getSet(final byte[] key, final byte[] value) { - Jedis j = getShard(key); - return j.getSet(key, value); - } - - @Override - public long setnx(final byte[] key, final byte[] value) { - Jedis j = getShard(key); - return j.setnx(key, value); - } - - @Override - public String setex(final byte[] key, final long seconds, final byte[] value) { - Jedis j = getShard(key); - return j.setex(key, seconds, value); - } - - @Override - public String psetex(final byte[] key, final long milliseconds, final byte[] value) { - Jedis j = getShard(key); - return j.psetex(key, milliseconds, value); - } - - @Override - public long decrBy(final byte[] key, final long decrement) { - Jedis j = getShard(key); - return j.decrBy(key, decrement); - } - - @Override - public long decr(final byte[] key) { - Jedis j = getShard(key); - return j.decr(key); - } - - @Override - public long del(final byte[] key) { - Jedis j = getShard(key); - return j.del(key); - } - - @Override - public long unlink(final byte[] key) { - Jedis j = getShard(key); - return j.unlink(key); - } - - @Override - public long incrBy(final byte[] key, final long increment) { - Jedis j = getShard(key); - return j.incrBy(key, increment); - } - - @Override - public double incrByFloat(final byte[] key, final double increment) { - Jedis j = getShard(key); - return j.incrByFloat(key, increment); - } - - @Override - public long incr(final byte[] key) { - Jedis j = getShard(key); - return j.incr(key); - } - - @Override - public long append(final byte[] key, final byte[] value) { - Jedis j = getShard(key); - return j.append(key, value); - } - - @Override - public byte[] substr(final byte[] key, final int start, final int end) { - Jedis j = getShard(key); - return j.substr(key, start, end); - } - - @Override - public long hset(final byte[] key, final byte[] field, final byte[] value) { - Jedis j = getShard(key); - return j.hset(key, field, value); - } - - @Override - public long hset(final byte[] key, final Map hash) { - Jedis j = getShard(key); - return j.hset(key, hash); - } - - @Override - public byte[] hget(final byte[] key, final byte[] field) { - Jedis j = getShard(key); - return j.hget(key, field); - } - - @Override - public long hsetnx(final byte[] key, final byte[] field, final byte[] value) { - Jedis j = getShard(key); - return j.hsetnx(key, field, value); - } - - @Override - public String hmset(final byte[] key, final Map hash) { - Jedis j = getShard(key); - return j.hmset(key, hash); - } - - @Override - public List hmget(final byte[] key, final byte[]... fields) { - Jedis j = getShard(key); - return j.hmget(key, fields); - } - - @Override - public long hincrBy(final byte[] key, final byte[] field, final long value) { - Jedis j = getShard(key); - return j.hincrBy(key, field, value); - } - - @Override - public double hincrByFloat(final byte[] key, final byte[] field, final double value) { - Jedis j = getShard(key); - return j.hincrByFloat(key, field, value); - } - - @Override - public boolean hexists(final byte[] key, final byte[] field) { - Jedis j = getShard(key); - return j.hexists(key, field); - } - - @Override - public long hdel(final byte[] key, final byte[]... fields) { - Jedis j = getShard(key); - return j.hdel(key, fields); - } - - @Override - public long hlen(final byte[] key) { - Jedis j = getShard(key); - return j.hlen(key); - } - - @Override - public Set hkeys(final byte[] key) { - Jedis j = getShard(key); - return j.hkeys(key); - } - - @Override - public List hvals(final byte[] key) { - Jedis j = getShard(key); - return j.hvals(key); - } - - @Override - public Map hgetAll(final byte[] key) { - Jedis j = getShard(key); - return j.hgetAll(key); - } - - @Override - public byte[] hrandfield(final byte[] key) { - Jedis j = getShard(key); - return j.hrandfield(key); - } - - @Override - public List hrandfield(final byte[] key, final long count) { - Jedis j = getShard(key); - return j.hrandfield(key, count); - } - - @Override - public Map hrandfieldWithValues(final byte[] key, final long count) { - Jedis j = getShard(key); - return j.hrandfieldWithValues(key, count); - } - - @Override - public long rpush(final byte[] key, final byte[]... strings) { - Jedis j = getShard(key); - return j.rpush(key, strings); - } - - @Override - public long lpush(final byte[] key, final byte[]... strings) { - Jedis j = getShard(key); - return j.lpush(key, strings); - } - - @Override - public long strlen(final byte[] key) { - Jedis j = getShard(key); - return j.strlen(key); - } - - @Override - public long lpushx(final byte[] key, final byte[]... string) { - Jedis j = getShard(key); - return j.lpushx(key, string); - } - - @Override - public long persist(final byte[] key) { - Jedis j = getShard(key); - return j.persist(key); - } - - @Override - public long rpushx(final byte[] key, final byte[]... string) { - Jedis j = getShard(key); - return j.rpushx(key, string); - } - - @Override - public long llen(final byte[] key) { - Jedis j = getShard(key); - return j.llen(key); - } - - @Override - public List lrange(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.lrange(key, start, stop); - } - - @Override - public String ltrim(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.ltrim(key, start, stop); - } - - @Override - public byte[] lindex(final byte[] key, final long index) { - Jedis j = getShard(key); - return j.lindex(key, index); - } - - @Override - public String lset(final byte[] key, final long index, final byte[] value) { - Jedis j = getShard(key); - return j.lset(key, index, value); - } - - @Override - public long lrem(final byte[] key, final long count, final byte[] value) { - Jedis j = getShard(key); - return j.lrem(key, count, value); - } - - @Override - public byte[] lpop(final byte[] key) { - Jedis j = getShard(key); - return j.lpop(key); - } - - @Override - public List lpop(final byte[] key, final int count) { - Jedis j = getShard(key); - return j.lpop(key, count); - } - - @Override - public Long lpos(final byte[] key, final byte[] element) { - Jedis j = getShard(key); - return j.lpos(key, element); - } - - @Override - public Long lpos(final byte[] key, final byte[] element, final LPosParams params) { - Jedis j = getShard(key); - return j.lpos(key, element, params); - } - - @Override - public List lpos(final byte[] key, final byte[] element, final LPosParams params, - final long count) { - Jedis j = getShard(key); - return j.lpos(key, element, params, count); - } - - @Override - public byte[] rpop(final byte[] key) { - Jedis j = getShard(key); - return j.rpop(key); - } - - @Override - public List rpop(final byte[] key, final int count) { - Jedis j = getShard(key); - return j.rpop(key, count); - } - - @Override - public long sadd(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.sadd(key, members); - } - - @Override - public Set smembers(final byte[] key) { - Jedis j = getShard(key); - return j.smembers(key); - } - - @Override - public long srem(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.srem(key, members); - } - - @Override - public byte[] spop(final byte[] key) { - Jedis j = getShard(key); - return j.spop(key); - } - - @Override - public Set spop(final byte[] key, final long count) { - Jedis j = getShard(key); - return j.spop(key, count); - } - - @Override - public long scard(final byte[] key) { - Jedis j = getShard(key); - return j.scard(key); - } - - @Override - public boolean sismember(final byte[] key, final byte[] member) { - Jedis j = getShard(key); - return j.sismember(key, member); - } - - @Override - public List smismember(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.smismember(key, members); - } - - @Override - public byte[] srandmember(final byte[] key) { - Jedis j = getShard(key); - return j.srandmember(key); - } - - @Override - public List srandmember(final byte[] key, final int count) { - Jedis j = getShard(key); - return j.srandmember(key, count); - } - - @Override - public long zadd(final byte[] key, final double score, final byte[] member) { - Jedis j = getShard(key); - return j.zadd(key, score, member); - } - - @Override - public long zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { - Jedis j = getShard(key); - return j.zadd(key, score, member, params); - } - - @Override - public long zadd(final byte[] key, final Map scoreMembers) { - Jedis j = getShard(key); - return j.zadd(key, scoreMembers); - } - - @Override - public long zadd(final byte[] key, final Map scoreMembers, final ZAddParams params) { - Jedis j = getShard(key); - return j.zadd(key, scoreMembers, params); - } - - @Override - public Double zaddIncr(final byte[] key, final double score, final byte[] member, final ZAddParams params) { - Jedis j = getShard(key); - return j.zaddIncr(key, score, member, params); - } - - @Override - public Set zrange(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrange(key, start, stop); - } - - @Override - public long zrem(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.zrem(key, members); - } - - @Override - public double zincrby(final byte[] key, final double increment, final byte[] member) { - Jedis j = getShard(key); - return j.zincrby(key, increment, member); - } - - @Override - public Double zincrby(final byte[] key, final double increment, final byte[] member, - ZIncrByParams params) { - Jedis j = getShard(key); - return j.zincrby(key, increment, member, params); - } - - @Override - public Long zrank(final byte[] key, final byte[] member) { - Jedis j = getShard(key); - return j.zrank(key, member); - } - - @Override - public Long zrevrank(final byte[] key, final byte[] member) { - Jedis j = getShard(key); - return j.zrevrank(key, member); - } - - @Override - public Set zrevrange(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrevrange(key, start, stop); - } - - @Override - public Set zrangeWithScores(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrangeWithScores(key, start, stop); - } - - @Override - public Set zrevrangeWithScores(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrevrangeWithScores(key, start, stop); - } - - @Override - public byte[] zrandmember(final byte[] key) { - Jedis j = getShard(key); - return j.zrandmember(key); - } - - @Override - public Set zrandmember(final byte[] key, final long count) { - Jedis j = getShard(key); - return j.zrandmember(key, count); - } - - @Override - public Set zrandmemberWithScores(final byte[] key, final long count) { - Jedis j = getShard(key); - return j.zrandmemberWithScores(key, count); - } - - @Override - public long zcard(final byte[] key) { - Jedis j = getShard(key); - return j.zcard(key); - } - - @Override - public Double zscore(final byte[] key, final byte[] member) { - Jedis j = getShard(key); - return j.zscore(key, member); - } - - @Override - public List zmscore(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.zmscore(key, members); - } - - @Override - public Tuple zpopmax(final byte[] key) { - Jedis j = getShard(key); - return j.zpopmax(key); - } - - @Override - public Set zpopmax(final byte[] key, final int count) { - Jedis j = getShard(key); - return j.zpopmax(key, count); - } - - @Override - public Tuple zpopmin(final byte[] key) { - Jedis j = getShard(key); - return j.zpopmin(key); - } - - @Override - public Set zpopmin(final byte[] key, final int count) { - Jedis j = getShard(key); - return j.zpopmin(key, count); - } - - @Override - public List sort(final byte[] key) { - Jedis j = getShard(key); - return j.sort(key); - } - - @Override - public List sort(final byte[] key, SortingParams sortingParameters) { - Jedis j = getShard(key); - return j.sort(key, sortingParameters); - } - - @Override - public long zcount(final byte[] key, final double min, final double max) { - Jedis j = getShard(key); - return j.zcount(key, min, max); - } - - @Override - public long zcount(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zcount(key, min, max); - } - - @Override - public Set zrangeByScore(final byte[] key, final double min, final double max) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max); - } - - @Override - public Set zrangeByScore(final byte[] key, final double min, final double max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max, offset, count); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final double min, final double max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max, offset, count); - } - - @Override - public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max); - } - - @Override - public Set zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max, offset, count); - } - - @Override - public Set zrangeByScore(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final double max, final double min, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min, offset, count); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min, final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min); - } - - @Override - public Set zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min, offset, count); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min); - } - - @Override - public Set zrevrangeByScoreWithScores(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - - @Override - public long zremrangeByRank(final byte[] key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zremrangeByRank(key, start, stop); - } - - @Override - public long zremrangeByScore(final byte[] key, final double min, final double max) { - Jedis j = getShard(key); - return j.zremrangeByScore(key, min, max); - } - - @Override - public long zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zremrangeByScore(key, min, max); - } - - @Override - public long zlexcount(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zlexcount(key, min, max); - } - - @Override - public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zrangeByLex(key, min, max); - } - - @Override - public Set zrangeByLex(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByLex(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { - Jedis j = getShard(key); - return j.zrevrangeByLex(key, max, min); - } - - @Override - public Set zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByLex(key, max, min, offset, count); - } - - @Override - public long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - Jedis j = getShard(key); - return j.zremrangeByLex(key, min, max); - } - - @Override - public long linsert(final byte[] key, final ListPosition where, final byte[] pivot, - final byte[] value) { - Jedis j = getShard(key); - return j.linsert(key, where, pivot, value); - } - - public long objectRefcount(final byte[] key) { - Jedis j = getShard(key); - return j.objectRefcount(key); - } - - public byte[] objectEncoding(final byte[] key) { - Jedis j = getShard(key); - return j.objectEncoding(key); - } - - public long objectIdletime(final byte[] key) { - Jedis j = getShard(key); - return j.objectIdletime(key); - } - - public List objectHelp() { - Jedis j = getShard("null"); - return j.objectHelp(); - } - - public long objectFreq(final byte[] key) { - Jedis j = getShard(key); - return j.objectIdletime(key); - } - - @Override - public boolean setbit(final byte[] key, final long offset, boolean value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); - } - - @Override - public Boolean setbit(final byte[] key, final long offset, final byte[] value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); - } - - @Override - public boolean getbit(final byte[] key, final long offset) { - Jedis j = getShard(key); - return j.getbit(key, offset); - } - - @Override - public long setrange(final byte[] key, final long offset, final byte[] value) { - Jedis j = getShard(key); - return j.setrange(key, offset, value); - } - - @Override - public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) { - Jedis j = getShard(key); - return j.getrange(key, startOffset, endOffset); - } - - public long move(final byte[] key, final int dbIndex) { - Jedis j = getShard(key); - return j.move(key, dbIndex); - } - - @Override - public byte[] echo(final byte[] arg) { - Jedis j = getShard(arg); - return j.echo(arg); - } - - public List brpop(final byte[] arg) { - Jedis j = getShard(arg); - return j.brpop(arg); - } - - public List blpop(final byte[] arg) { - Jedis j = getShard(arg); - return j.blpop(arg); - } - - @Override - public long bitcount(final byte[] key) { - Jedis j = getShard(key); - return j.bitcount(key); - } - - @Override - public long bitcount(final byte[] key, final long start, final long end) { - Jedis j = getShard(key); - return j.bitcount(key, start, end); - } - - @Override - public long pfadd(final byte[] key, final byte[]... elements) { - Jedis j = getShard(key); - return j.pfadd(key, elements); - } - - @Override - public long pfcount(final byte[] key) { - Jedis j = getShard(key); - return j.pfcount(key); - } - - @Override - public long geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { - Jedis j = getShard(key); - return j.geoadd(key, longitude, latitude, member); - } - - @Override - public long geoadd(final byte[] key, final Map memberCoordinateMap) { - Jedis j = getShard(key); - return j.geoadd(key, memberCoordinateMap); - } - - @Override - public long geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { - Jedis j = getShard(key); - return j.geoadd(key, params, memberCoordinateMap); - } - - @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2) { - Jedis j = getShard(key); - return j.geodist(key, member1, member2); - } - - @Override - public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { - Jedis j = getShard(key); - return j.geodist(key, member1, member2, unit); - } - - @Override - public List geohash(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.geohash(key, members); - } - - @Override - public List geopos(final byte[] key, final byte[]... members) { - Jedis j = getShard(key); - return j.geopos(key, members); - } - - @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadius(key, longitude, latitude, radius, unit); - } - - @Override - public List georadiusReadonly(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadiusReadonly(key, longitude, latitude, radius, unit); - } - - @Override - public List georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadius(key, longitude, latitude, radius, unit, param); - } - - @Override - public List georadiusReadonly(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadiusReadonly(key, longitude, latitude, radius, unit, param); - } - - @Override - public List georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadiusByMember(key, member, radius, unit); - } - - @Override - public List georadiusByMemberReadonly(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadiusByMemberReadonly(key, member, radius, unit); - } - - @Override - public List georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadiusByMember(key, member, radius, unit, param); - } - - @Override - public List georadiusByMemberReadonly(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadiusByMemberReadonly(key, member, radius, unit, param); - } - - @Override - public ScanResult> hscan(final byte[] key, final byte[] cursor, - final ScanParams params) { - Jedis j = getShard(key); - return j.hscan(key, cursor, params); - } - - @Override - public ScanResult sscan(final byte[] key, final byte[] cursor, final ScanParams params) { - Jedis j = getShard(key); - return j.sscan(key, cursor, params); - } - - @Override - public ScanResult zscan(final byte[] key, final byte[] cursor, final ScanParams params) { - Jedis j = getShard(key); - return j.zscan(key, cursor, params); - } - - @Override - public List bitfield(final byte[] key, final byte[]... arguments) { - Jedis j = getShard(key); - return j.bitfield(key, arguments); - } - - @Override - public List bitfieldReadonly(byte[] key, final byte[]... arguments) { - Jedis j = getShard(key); - return j.bitfieldReadonly(key, arguments); - } - - @Override - public long hstrlen(final byte[] key, final byte[] field) { - Jedis j = getShard(key); - return j.hstrlen(key, field); - } - - @Override - public byte[] xadd(byte[] key, byte[] id, Map hash, long maxLen, - boolean approximateLength) { - Jedis j = getShard(key); - return j.xadd(key, id, hash, maxLen, approximateLength); - } - - @Override - public byte[] xadd(final byte[] key, final Map hash, final XAddParams params) { - Jedis j = getShard(key); - return j.xadd(key, hash, params); - } - - @Override - public long xlen(byte[] key) { - Jedis j = getShard(key); - return j.xlen(key); - } - - @Override - public List xrange(byte[] key, byte[] start, byte[] end) { - Jedis j = getShard(key); - return j.xrange(key, start, end); - } - - @Override - public List xrange(byte[] key, byte[] start, byte[] end, int count) { - Jedis j = getShard(key); - return j.xrange(key, start, end, count); - } - - @Override - public List xrevrange(byte[] key, byte[] end, byte[] start) { - Jedis j = getShard(key); - return j.xrevrange(key, end, start); - } - - @Override - public List xrevrange(byte[] key, byte[] end, byte[] start, int count) { - Jedis j = getShard(key); - return j.xrevrange(key, end, start, count); - } - - @Override - public long xack(byte[] key, byte[] group, byte[]... ids) { - Jedis j = getShard(key); - return j.xack(key, group, ids); - } - - @Override - public String xgroupCreate(byte[] key, byte[] consumer, byte[] id, boolean makeStream) { - Jedis j = getShard(key); - return j.xgroupCreate(key, consumer, id, makeStream); - } - - @Override - public String xgroupSetID(byte[] key, byte[] consumer, byte[] id) { - Jedis j = getShard(key); - return j.xgroupSetID(key, consumer, id); - } - - @Override - public long xgroupDestroy(byte[] key, byte[] consumer) { - Jedis j = getShard(key); - return j.xgroupDestroy(key, consumer); - } - - @Override - public long xgroupDelConsumer(byte[] key, byte[] consumer, byte[] consumerName) { - Jedis j = getShard(key); - return j.xgroupDelConsumer(key, consumer, consumerName); - } - - @Override - public long xdel(byte[] key, byte[]... ids) { - Jedis j = getShard(key); - return j.xdel(key, ids); - } - - @Override - public long xtrim(byte[] key, long maxLen, boolean approximateLength) { - Jedis j = getShard(key); - return j.xtrim(key, maxLen, approximateLength); - } - - @Override - public long xtrim(byte[] key, XTrimParams params) { - Jedis j = getShard(key); - return j.xtrim(key, params); - } - - @Override - public List xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, - byte[] consumername) { - Jedis j = getShard(key); - return j.xpending(key, groupname, start, end, count, consumername); - } - - @Override - public Object xpending(final byte[] key, final byte[] groupname) { - Jedis j = getShard(key); - return j.xpending(key, groupname); - } - - @Override - public List xpending(final byte[] key, final byte[] groupname, final XPendingParams params) { - Jedis j = getShard(key); - return j.xpending(key, groupname, params); - } - - @Override - public List xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, byte[]... ids) { - Jedis j = getShard(key); - return j.xclaim(key, groupname, consumername, minIdleTime, newIdleTime, retries, force, ids); - } - - @Override - public List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - Jedis j = getShard(key); - return j.xclaim(key, group, consumername, minIdleTime, params, ids); - } - - @Override - public List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids) { - Jedis j = getShard(key); - return j.xclaimJustId(key, group, consumername, minIdleTime, params, ids); - } - - @Override - public List xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - Jedis j = getShard(key); - return j.xautoclaim(key, groupName, consumerName, minIdleTime, start, params); - } - - @Override - public List xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - Jedis j = getShard(key); - return j.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params); - } - - @Override - public StreamInfo xinfoStream(byte[] key) { - Jedis j = getShard(key); - return j.xinfoStream(key); - } - - @Override - public Object xinfoStreamBinary(byte[] key) { - Jedis j = getShard(key); - return j.xinfoStreamBinary(key); - } - - @Override - public List xinfoGroup(byte[] key) { - Jedis j = getShard(key); - return j.xinfoGroup(key); - } - - @Override - public List xinfoGroupBinary(byte[] key) { - Jedis j = getShard(key); - return j.xinfoGroupBinary(key); - } - - @Override - public List xinfoConsumers(byte[] key, byte[] group) { - Jedis j = getShard(key); - return j.xinfoConsumers(key, group); - } - - @Override - public List xinfoConsumersBinary(byte[] key, byte[] group) { - Jedis j = getShard(key); - return j.xinfoConsumersBinary(key, group); - } - - @Override - public Long memoryUsage(byte[] key) { - Jedis j = getShard(key); - return j.memoryUsage(key); - } - - @Override - public Long memoryUsage(byte[] key, int samples) { - Jedis j = getShard(key); - return j.memoryUsage(key, samples); - } - - public Object sendCommand(ProtocolCommand cmd, byte[]... args) { - // default since no sample key provided in JedisCommands interface - byte[] sampleKey = args.length > 0 ? args[0] : cmd.getRaw(); - Jedis j = getShard(sampleKey); - return j.sendCommand(cmd, args); - } - - public Object sendBlockingCommand(ProtocolCommand cmd, byte[]... args) { - // default since no sample key provided in JedisCommands interface - byte[] sampleKey = args.length > 0 ? args[0] : cmd.getRaw(); - Jedis j = getShard(sampleKey); - return j.sendBlockingCommand(cmd, args); - } - - public Object sendCommand(ProtocolCommand cmd) { - return sendCommand(cmd, dummyArray); - } - - @Override - public LCSMatchResult strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params) { - Jedis j = getShard(""); - return j.strAlgoLCSStrings(strA, strB, params); - } -} diff --git a/src/main/java/redis/clients/jedis/BitOP.java b/src/main/java/redis/clients/jedis/BitOP.java deleted file mode 100644 index 7067e90e9e..0000000000 --- a/src/main/java/redis/clients/jedis/BitOP.java +++ /dev/null @@ -1,11 +0,0 @@ -package redis.clients.jedis; - -public enum BitOP { - AND, OR, XOR, NOT; - - public final byte[] raw; - - private BitOP() { - this.raw = redis.clients.jedis.util.SafeEncoder.encode(name()); - } -} diff --git a/src/main/java/redis/clients/jedis/BitPosParams.java b/src/main/java/redis/clients/jedis/BitPosParams.java deleted file mode 100644 index 92d0b0703e..0000000000 --- a/src/main/java/redis/clients/jedis/BitPosParams.java +++ /dev/null @@ -1,27 +0,0 @@ -package redis.clients.jedis; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -public class BitPosParams { - private List params = new ArrayList<>(); - - protected BitPosParams() { - } - - public BitPosParams(long start) { - params.add(Protocol.toByteArray(start)); - } - - public BitPosParams(long start, long end) { - this(start); - - params.add(Protocol.toByteArray(end)); - } - - public Collection getParams() { - return Collections.unmodifiableCollection(params); - } -} diff --git a/src/main/java/redis/clients/jedis/Builder.java b/src/main/java/redis/clients/jedis/Builder.java index d1cd8742f2..5d3bf0eca1 100644 --- a/src/main/java/redis/clients/jedis/Builder.java +++ b/src/main/java/redis/clients/jedis/Builder.java @@ -1,5 +1,6 @@ package redis.clients.jedis; public abstract class Builder { + public abstract T build(Object data); } diff --git a/src/main/java/redis/clients/jedis/BuilderFactory.java b/src/main/java/redis/clients/jedis/BuilderFactory.java index 7de3630c3a..b429387297 100644 --- a/src/main/java/redis/clients/jedis/BuilderFactory.java +++ b/src/main/java/redis/clients/jedis/BuilderFactory.java @@ -1,39 +1,21 @@ package redis.clients.jedis; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; +import java.io.Serializable; +import java.util.*; +import java.util.stream.Collectors; +import org.json.JSONArray; +import org.json.JSONObject; +import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.resps.LCSMatchResult.MatchedPosition; import redis.clients.jedis.resps.LCSMatchResult.Position; import redis.clients.jedis.resps.*; +import redis.clients.jedis.search.aggr.AggregationResult; import redis.clients.jedis.util.JedisByteHashMap; import redis.clients.jedis.util.SafeEncoder; public final class BuilderFactory { - /** - * @deprecated Use {@link #RAW_OBJECT}. - */ - @Deprecated - public static final Builder OBJECT = new Builder() { - @Override - public Object build(Object data) { - return data; - } - - @Override - public String toString() { - return "Object"; - } - }; - public static final Builder RAW_OBJECT = new Builder() { @Override public Object build(Object data) { @@ -82,6 +64,19 @@ public String toString() { } }; + public static final Builder> ENCODED_OBJECT_MAP = new Builder>() { + @Override + public Map build(Object data) { + final List list = (List) data; + final Map map = new HashMap<>(list.size() / 2, 1); + final Iterator iterator = list.iterator(); + while (iterator.hasNext()) { + map.put(STRING.build(iterator.next()), ENCODED_OBJECT.build(iterator.next())); + } + return map; + } + }; + public static final Builder LONG = new Builder() { @Override public Long build(Object data) { @@ -90,7 +85,7 @@ public Long build(Object data) { @Override public String toString() { - return "long"; // TODO: Long + return "Long"; } }; @@ -128,7 +123,7 @@ public Double build(Object data) { @Override public String toString() { - return "double"; // TODO: Double + return "Double"; } }; @@ -156,12 +151,13 @@ public String toString() { public static final Builder BOOLEAN = new Builder() { @Override public Boolean build(Object data) { + if (data == null) return null; return ((Long) data) == 1L; } @Override public String toString() { - return "boolean"; // Boolean? + return "Boolean"; } }; @@ -175,7 +171,7 @@ public List build(Object data) { List longs = (List) data; List booleans = new ArrayList<>(longs.size()); for (Long value : longs) { - booleans.add(value == 1L); + booleans.add(value == null ? null : value == 1L); } return booleans; } @@ -214,31 +210,49 @@ public String toString() { } }; - public static final Builder> BYTE_ARRAY_ZSET = new Builder>() { + public static final Builder BINARY = new Builder() { + @Override + public byte[] build(Object data) { + return (byte[]) data; + } + + @Override + public String toString() { + return "byte[]"; + } + }; + + public static final Builder> BINARY_LIST = new Builder>() { + @Override + @SuppressWarnings("unchecked") + public List build(Object data) { + return (List) data; + } + + @Override + public String toString() { + return "List"; + } + }; + + public static final Builder> BINARY_SET = new Builder>() { @Override @SuppressWarnings("unchecked") public Set build(Object data) { if (null == data) { return null; } - List l = (List) data; - final Set result = new LinkedHashSet<>(l); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(barray); - } - } - return result; + List l = BINARY_LIST.build(data); + return SetFromList.of(l); } @Override public String toString() { - return "ZSet"; + return "Set"; } }; - public static final Builder> BYTE_ARRAY_MAP = new Builder>() { + + public static final Builder> BINARY_MAP = new Builder>() { @Override @SuppressWarnings("unchecked") public Map build(Object data) { @@ -256,7 +270,6 @@ public Map build(Object data) { public String toString() { return "Map"; } - }; public static final Builder STRING = new Builder() { @@ -267,7 +280,7 @@ public String build(Object data) { @Override public String toString() { - return "string"; // TODO: String + return "String"; } }; @@ -324,32 +337,6 @@ public String toString() { }; - public static final Builder> STRING_ZSET = new Builder>() { - @Override - @SuppressWarnings("unchecked") - public Set build(Object data) { - if (null == data) { - return null; - } - List l = (List) data; - final Set result = new LinkedHashSet<>(l.size(), 1); - for (final byte[] barray : l) { - if (barray == null) { - result.add(null); - } else { - result.add(SafeEncoder.encode(barray)); - } - } - return result; - } - - @Override - public String toString() { - return "ZSet"; - } - - }; - public static final Builder> STRING_MAP = new Builder>() { @Override @SuppressWarnings("unchecked") @@ -421,6 +408,28 @@ public String toString() { } }; + public static final Builder> TUPLE_LIST = new Builder>() { + @Override + @SuppressWarnings("unchecked") + public List build(Object data) { + if (null == data) { + return null; + } + List l = (List) data; + final List result = new ArrayList<>(l.size() / 2); + Iterator iterator = l.iterator(); + while (iterator.hasNext()) { + result.add(new Tuple(iterator.next(), DOUBLE.build(iterator.next()))); + } + return result; + } + + @Override + public String toString() { + return "List"; + } + }; + public static final Builder> TUPLE_ZSET = new Builder>() { @Override @SuppressWarnings("unchecked") @@ -444,52 +453,112 @@ public String toString() { }; - /** - * @deprecated Use {@link #ENCODED_OBJECT}. - */ - @Deprecated - public static final Builder EVAL_RESULT = new Builder() { + public static final Builder> SCAN_RESPONSE = new Builder>() { + @Override + public ScanResult build(Object data) { + List result = (List) data; + String newcursor = new String((byte[]) result.get(0)); + List rawResults = (List) result.get(1); + List results = new ArrayList<>(rawResults.size()); + for (byte[] bs : rawResults) { + results.add(SafeEncoder.encode(bs)); + } + return new ScanResult<>(newcursor, results); + } + }; + public static final Builder>> HSCAN_RESPONSE + = new Builder>>() { @Override - public Object build(Object data) { - return SafeEncoder.encodeObject(data); + public ScanResult> build(Object data) { + List result = (List) data; + String newcursor = new String((byte[]) result.get(0)); + List rawResults = (List) result.get(1); + List> results = new ArrayList<>(rawResults.size() / 2); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new AbstractMap.SimpleEntry<>(SafeEncoder.encode(iterator.next()), + SafeEncoder.encode(iterator.next()))); + } + return new ScanResult<>(newcursor, results); } + }; + public static final Builder> SSCAN_RESPONSE = new Builder>() { @Override - public String toString() { - return "Eval"; + public ScanResult build(Object data) { + List result = (List) data; + String newcursor = new String((byte[]) result.get(0)); + List rawResults = (List) result.get(1); + List results = new ArrayList<>(rawResults.size()); + for (byte[] bs : rawResults) { + results.add(SafeEncoder.encode(bs)); + } + return new ScanResult<>(newcursor, results); } }; - /** - * @deprecated Use {@link #RAW_OBJECT}. - */ - @Deprecated - public static final Builder EVAL_BINARY_RESULT = new Builder() { + public static final Builder> ZSCAN_RESPONSE = new Builder>() { + @Override + public ScanResult build(Object data) { + List result = (List) data; + String newcursor = new String((byte[]) result.get(0)); + List rawResults = (List) result.get(1); + List results = new ArrayList<>(rawResults.size() / 2); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new Tuple(iterator.next(), BuilderFactory.DOUBLE.build(iterator.next()))); + } + return new ScanResult<>(newcursor, results); + } + }; + public static final Builder> SCAN_BINARY_RESPONSE = new Builder>() { @Override - public Object build(Object data) { - return data; + public ScanResult build(Object data) { + List result = (List) data; + byte[] newcursor = (byte[]) result.get(0); + List rawResults = (List) result.get(1); + return new ScanResult<>(newcursor, rawResults); } + }; + public static final Builder>> HSCAN_BINARY_RESPONSE + = new Builder>>() { @Override - public String toString() { - return "Eval"; + public ScanResult> build(Object data) { + List result = (List) data; + byte[] newcursor = (byte[]) result.get(0); + List rawResults = (List) result.get(1); + List> results = new ArrayList<>(rawResults.size() / 2); + Iterator iterator = rawResults.iterator(); + while (iterator.hasNext()) { + results.add(new AbstractMap.SimpleEntry<>(iterator.next(), iterator.next())); + } + return new ScanResult<>(newcursor, results); } }; - public static final Builder> PUBSUB_NUMSUB_MAP = new Builder>() { + public static final Builder> SSCAN_BINARY_RESPONSE = new Builder>() { + @Override + public ScanResult build(Object data) { + List result = (List) data; + byte[] newcursor = (byte[]) result.get(0); + List rawResults = (List) result.get(1); + return new ScanResult<>(newcursor, rawResults); + } + }; + + public static final Builder> PUBSUB_NUMSUB_MAP = new Builder>() { @Override @SuppressWarnings("unchecked") - public Map build(Object data) { + public Map build(Object data) { final List flatHash = (List) data; - final Map hash = new HashMap<>(flatHash.size() / 2, 1); + final Map hash = new HashMap<>(flatHash.size() / 2, 1); final Iterator iterator = flatHash.iterator(); while (iterator.hasNext()) { - hash.put(SafeEncoder.encode((byte[]) iterator.next()), - String.valueOf((Long) iterator.next())); + hash.put(SafeEncoder.encode((byte[]) iterator.next()), (Long) iterator.next()); } - return hash; } @@ -1093,10 +1162,6 @@ private static Map createMapFromDecodingFunctions(Iterator STR_ALGO_LCS_RESULT_BUILDER = new Builder() { @Override public LCSMatchResult build(Object data) { @@ -1143,4 +1208,248 @@ public LCSMatchResult build(Object data) { } }; + public static final Builder> STRING_MAP_FROM_PAIRS = new Builder>() { + @Override + @SuppressWarnings("unchecked") + public Map build(Object data) { + final List list = (List) data; + final Map map = new HashMap<>(list.size()); + for (Object object : list) { + final List flat = (List) object; + map.put(SafeEncoder.encode(flat.get(0)), flat.get(1) != null ? SafeEncoder.encode(flat.get(1)) : null); + } + + return map; + } + + @Override + public String toString() { + return "Map"; + } + + }; + + public static final Builder> JSON_TYPE = new Builder>() { + @Override + public Class build(Object data) { + if (data == null) return null; + String str = STRING.build(data); + switch (str) { + case "null": + return null; + case "boolean": + return boolean.class; + case "integer": + return int.class; + case "number": + return float.class; + case "string": + return String.class; + case "object": + return Object.class; + case "array": + return List.class; + default: + throw new JedisException("Unknown type: " + str); + } + } + + @Override + public String toString() { + return "Class"; + } + }; + + public static final Builder>> JSON_TYPE_LIST = new Builder>>() { + @Override + public List> build(Object data) { + List list = (List) data; + List> classes = new ArrayList<>(list.size()); + for (Object elem : list) { + try { + classes.add(JSON_TYPE.build(elem)); + } catch (JedisException je) { + classes.add(null); + } + } + return classes; + } + }; + + public static final Builder JSON_OBJECT = new Builder() { + @Override + public Object build(Object data) { + if (data == null) return null; + + if (!(data instanceof byte[])) return data; + + String str = STRING.build(data); + if (str.charAt(0) == '{') { + try { + return new JSONObject(str); + } catch (Exception ex) { } + } else if (str.charAt(0) == '[') { + try { + return new JSONArray(str); + } catch (Exception ex) { } + } + return str; + } + }; + + public static final Builder JSON_ARRAY = new Builder() { + @Override + public JSONArray build(Object data) { + if (data == null) return null; + return new JSONArray(STRING.build(data)); + } + }; + + public static final Builder> JSON_ARRAY_LIST = new Builder>() { + @Override + public List build(Object data) { + if (data == null) return null; + List list = (List) data; + return list.stream().map(o -> JSON_ARRAY.build(o)).collect(Collectors.toList()); + } + }; + + public static final Builder SEARCH_AGGREGATION_RESULT = new Builder() { + @Override + public AggregationResult build(Object data) { + return new AggregationResult(data); + } + }; + + public static final Builder SEARCH_AGGREGATION_RESULT_WITH_CURSOR = new Builder() { + @Override + public AggregationResult build(Object data) { + List list = (List) data; + return new AggregationResult(list.get(0), (long) list.get(1)); + } + }; + + public static final Builder>> SEARCH_SYNONYM_GROUPS = new Builder>>() { + @Override + public Map> build(Object data) { + List list = (List) data; + Map> dump = new HashMap<>(list.size() / 2); + for (int i = 0; i < list.size(); i += 2) { + dump.put(STRING.build(list.get(i)), STRING_LIST.build(list.get(i + 1))); + } + return dump; + } + }; + + /** + * A decorator to implement Set from List. Assume that given List do not contains duplicated + * values. The resulting set displays the same ordering, concurrency, and performance + * characteristics as the backing list. This class should be used only for Redis commands which + * return Set result. + * @param + */ + protected static class SetFromList extends AbstractSet implements Serializable { + private static final long serialVersionUID = -2850347066962734052L; + private final List list; + + private SetFromList(List list) { + this.list = list; + } + + @Override + public void clear() { + list.clear(); + } + + @Override + public int size() { + return list.size(); + } + + @Override + public boolean isEmpty() { + return list.isEmpty(); + } + + @Override + public boolean contains(Object o) { + return list.contains(o); + } + + @Override + public boolean remove(Object o) { + return list.remove(o); + } + + @Override + public boolean add(E e) { + return !contains(e) && list.add(e); + } + + @Override + public Iterator iterator() { + return list.iterator(); + } + + @Override + public Object[] toArray() { + return list.toArray(); + } + + @Override + public T[] toArray(T[] a) { + return list.toArray(a); + } + + @Override + public String toString() { + return list.toString(); + } + + @Override + public int hashCode() { + return list.hashCode(); + } + + @Override + public boolean equals(Object o) { + if (o == null) return false; + if (o == this) return true; + if (!(o instanceof Set)) return false; + + Collection c = (Collection) o; + if (c.size() != size()) { + return false; + } + + return containsAll(c); + } + + @Override + public boolean containsAll(Collection c) { + return list.containsAll(c); + } + + @Override + public boolean removeAll(Collection c) { + return list.removeAll(c); + } + + @Override + public boolean retainAll(Collection c) { + return list.retainAll(c); + } + + protected static SetFromList of(List list) { + if (list == null) { + return null; + } + return new SetFromList<>(list); + } + } + + private BuilderFactory() { + throw new InstantiationError("Must not instantiate this class"); + } + } diff --git a/src/main/java/redis/clients/jedis/Client.java b/src/main/java/redis/clients/jedis/Client.java deleted file mode 100644 index 74e8946135..0000000000 --- a/src/main/java/redis/clients/jedis/Client.java +++ /dev/null @@ -1,1722 +0,0 @@ -package redis.clients.jedis; - -import static redis.clients.jedis.Protocol.toByteArray; - -import java.util.HashMap; -import java.util.Map; -import java.util.Map.Entry; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - -import redis.clients.jedis.Protocol.ClusterKeyword; -import redis.clients.jedis.Protocol.SentinelKeyword; -import redis.clients.jedis.args.ClusterFailoverOption; -import redis.clients.jedis.args.ClusterResetType; -import redis.clients.jedis.args.ListDirection; -import redis.clients.jedis.commands.Commands; -import redis.clients.jedis.params.*; -import redis.clients.jedis.util.SafeEncoder; - -public class Client extends BinaryClient implements Commands { - - public Client() { - super(); - } - - /** - * @param host - * @deprecated This constructor will be removed in future. It can be replaced with - * {@link #Client(java.lang.String, int)} with the host and {@link Protocol#DEFAULT_PORT}. - */ - @Deprecated - public Client(final String host) { - super(host); - } - - public Client(final String host, final int port) { - super(host, port); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public Client(final String host, final int port, final boolean ssl) { - super(host, port, ssl); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public Client(final String host, final int port, final boolean ssl, - final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - super(host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - } - - public Client(final HostAndPort hostPort, final JedisClientConfig clientConfig) { - super(hostPort, clientConfig); - } - - public Client(final JedisSocketFactory jedisSocketFactory) { - super(jedisSocketFactory); - } - - @Override - public void copy(String srcKey, String dstKey, int db, boolean replace) { - copy(SafeEncoder.encode(srcKey), SafeEncoder.encode(dstKey), db, replace); - } - - @Override - public void copy(String srcKey, String dstKey, boolean replace) { - copy(SafeEncoder.encode(srcKey), SafeEncoder.encode(dstKey), replace); - } - - @Override - public void ping(final String message) { - ping(SafeEncoder.encode(message)); - } - - @Override - public void set(final String key, final String value) { - set(SafeEncoder.encode(key), SafeEncoder.encode(value)); - } - - @Override - public void set(final String key, final String value, final SetParams params) { - set(SafeEncoder.encode(key), SafeEncoder.encode(value), params); - } - - @Override - public void get(final String key) { - get(SafeEncoder.encode(key)); - } - - @Override - public void getDel(final String key) { - getDel(SafeEncoder.encode(key)); - } - - @Override - public void getEx(String key, GetExParams params) { - getEx(SafeEncoder.encode(key), params); - } - - @Override - public void exists(final String... keys) { - exists(SafeEncoder.encodeMany(keys)); - } - - @Override - public void del(final String... keys) { - del(SafeEncoder.encodeMany(keys)); - } - - @Override - public void unlink(final String... keys) { - unlink(SafeEncoder.encodeMany(keys)); - } - - @Override - public void type(final String key) { - type(SafeEncoder.encode(key)); - } - - @Override - public void keys(final String pattern) { - keys(SafeEncoder.encode(pattern)); - } - - @Override - public void rename(final String oldkey, final String newkey) { - rename(SafeEncoder.encode(oldkey), SafeEncoder.encode(newkey)); - } - - @Override - public void renamenx(final String oldkey, final String newkey) { - renamenx(SafeEncoder.encode(oldkey), SafeEncoder.encode(newkey)); - } - - @Override - public void expire(final String key, final long seconds) { - expire(SafeEncoder.encode(key), seconds); - } - - @Override - public void expireAt(final String key, final long unixTime) { - expireAt(SafeEncoder.encode(key), unixTime); - } - - @Override - public void ttl(final String key) { - ttl(SafeEncoder.encode(key)); - } - - @Override - public void touch(final String... keys) { - touch(SafeEncoder.encodeMany(keys)); - } - - @Override - public void move(final String key, final int dbIndex) { - move(SafeEncoder.encode(key), dbIndex); - } - - @Override - public void getSet(final String key, final String value) { - getSet(SafeEncoder.encode(key), SafeEncoder.encode(value)); - } - - @Override - public void mget(final String... keys) { - mget(SafeEncoder.encodeMany(keys)); - } - - @Override - public void setnx(final String key, final String value) { - setnx(SafeEncoder.encode(key), SafeEncoder.encode(value)); - } - - @Override - public void setex(final String key, final long seconds, final String value) { - setex(SafeEncoder.encode(key), seconds, SafeEncoder.encode(value)); - } - - @Override - public void mset(final String... keysvalues) { - mset(SafeEncoder.encodeMany(keysvalues)); - } - - @Override - public void msetnx(final String... keysvalues) { - msetnx(SafeEncoder.encodeMany(keysvalues)); - } - - @Override - public void decrBy(final String key, final long decrement) { - decrBy(SafeEncoder.encode(key), decrement); - } - - @Override - public void decr(final String key) { - decr(SafeEncoder.encode(key)); - } - - @Override - public void incrBy(final String key, final long increment) { - incrBy(SafeEncoder.encode(key), increment); - } - - @Override - public void incr(final String key) { - incr(SafeEncoder.encode(key)); - } - - @Override - public void append(final String key, final String value) { - append(SafeEncoder.encode(key), SafeEncoder.encode(value)); - } - - @Override - public void substr(final String key, final int start, final int end) { - substr(SafeEncoder.encode(key), start, end); - } - - @Override - public void hset(final String key, final String field, final String value) { - hset(SafeEncoder.encode(key), SafeEncoder.encode(field), SafeEncoder.encode(value)); - } - - @Override - public void hset(final String key, final Map hash) { - final Map bhash = new HashMap<>(hash.size()); - for (final Entry entry : hash.entrySet()) { - bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue())); - } - hset(SafeEncoder.encode(key), bhash); - } - - @Override - public void hget(final String key, final String field) { - hget(SafeEncoder.encode(key), SafeEncoder.encode(field)); - } - - @Override - public void hsetnx(final String key, final String field, final String value) { - hsetnx(SafeEncoder.encode(key), SafeEncoder.encode(field), SafeEncoder.encode(value)); - } - - @Override - public void hmset(final String key, final Map hash) { - final Map bhash = new HashMap<>(hash.size()); - for (final Entry entry : hash.entrySet()) { - bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue())); - } - hmset(SafeEncoder.encode(key), bhash); - } - - @Override - public void hmget(final String key, final String... fields) { - hmget(SafeEncoder.encode(key), SafeEncoder.encodeMany(fields)); - } - - @Override - public void hincrBy(final String key, final String field, final long value) { - hincrBy(SafeEncoder.encode(key), SafeEncoder.encode(field), value); - } - - @Override - public void hexists(final String key, final String field) { - hexists(SafeEncoder.encode(key), SafeEncoder.encode(field)); - } - - @Override - public void hdel(final String key, final String... fields) { - hdel(SafeEncoder.encode(key), SafeEncoder.encodeMany(fields)); - } - - @Override - public void hlen(final String key) { - hlen(SafeEncoder.encode(key)); - } - - @Override - public void hkeys(final String key) { - hkeys(SafeEncoder.encode(key)); - } - - @Override - public void hvals(final String key) { - hvals(SafeEncoder.encode(key)); - } - - @Override - public void hgetAll(final String key) { - hgetAll(SafeEncoder.encode(key)); - } - - @Override - public void hrandfield(final String key) { - hrandfield(SafeEncoder.encode(key)); - } - - @Override - public void hrandfield(final String key, final long count) { - hrandfield(SafeEncoder.encode(key), count); - } - - @Override - public void hrandfieldWithValues(final String key, final long count) { - hrandfieldWithValues(SafeEncoder.encode(key), count); - } - - @Override - public void rpush(final String key, final String... string) { - rpush(SafeEncoder.encode(key), SafeEncoder.encodeMany(string)); - } - - @Override - public void lpush(final String key, final String... string) { - lpush(SafeEncoder.encode(key), SafeEncoder.encodeMany(string)); - } - - @Override - public void llen(final String key) { - llen(SafeEncoder.encode(key)); - } - - @Override - public void lrange(final String key, final long start, final long stop) { - lrange(SafeEncoder.encode(key), start, stop); - } - - @Override - public void ltrim(final String key, final long start, final long stop) { - ltrim(SafeEncoder.encode(key), start, stop); - } - - @Override - public void lindex(final String key, final long index) { - lindex(SafeEncoder.encode(key), index); - } - - @Override - public void lset(final String key, final long index, final String value) { - lset(SafeEncoder.encode(key), index, SafeEncoder.encode(value)); - } - - @Override - public void lrem(final String key, final long count, final String value) { - lrem(SafeEncoder.encode(key), count, SafeEncoder.encode(value)); - } - - @Override - public void lpop(final String key) { - lpop(SafeEncoder.encode(key)); - } - - @Override - public void lpop(final String key, final int count) { - lpop(SafeEncoder.encode(key), count); - } - - @Override - public void lpos(final String key, final String element) { - lpos(SafeEncoder.encode(key), SafeEncoder.encode(element)); - } - - @Override - public void lpos(final String key, final String element, final LPosParams params) { - lpos(SafeEncoder.encode(key), SafeEncoder.encode(element), params); - } - - @Override - public void lpos(final String key, final String element, final LPosParams params, final long count) { - lpos(SafeEncoder.encode(key), SafeEncoder.encode(element), params, count); - } - - @Override - public void rpop(final String key) { - rpop(SafeEncoder.encode(key)); - } - - @Override - public void rpop(final String key, final int count) { - rpop(SafeEncoder.encode(key), count); - } - - @Override - public void rpoplpush(final String srckey, final String dstkey) { - rpoplpush(SafeEncoder.encode(srckey), SafeEncoder.encode(dstkey)); - } - - @Override - public void sadd(final String key, final String... members) { - sadd(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - @Override - public void smembers(final String key) { - smembers(SafeEncoder.encode(key)); - } - - @Override - public void srem(final String key, final String... members) { - srem(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - @Override - public void spop(final String key) { - spop(SafeEncoder.encode(key)); - } - - @Override - public void spop(final String key, final long count) { - spop(SafeEncoder.encode(key), count); - } - - @Override - public void smove(final String srckey, final String dstkey, final String member) { - smove(SafeEncoder.encode(srckey), SafeEncoder.encode(dstkey), SafeEncoder.encode(member)); - } - - @Override - public void scard(final String key) { - scard(SafeEncoder.encode(key)); - } - - @Override - public void sismember(final String key, final String member) { - sismember(SafeEncoder.encode(key), SafeEncoder.encode(member)); - } - - @Override - public void smismember(final String key, final String... members) { - smismember(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - @Override - public void sinter(final String... keys) { - sinter(SafeEncoder.encodeMany(keys)); - } - - @Override - public void sinterstore(final String dstkey, final String... keys) { - sinterstore(SafeEncoder.encode(dstkey), SafeEncoder.encodeMany(keys)); - } - - @Override - public void sunion(final String... keys) { - sunion(SafeEncoder.encodeMany(keys)); - } - - @Override - public void sunionstore(final String dstkey, final String... keys) { - sunionstore(SafeEncoder.encode(dstkey), SafeEncoder.encodeMany(keys)); - } - - @Override - public void sdiff(final String... keys) { - sdiff(SafeEncoder.encodeMany(keys)); - } - - @Override - public void sdiffstore(final String dstkey, final String... keys) { - sdiffstore(SafeEncoder.encode(dstkey), SafeEncoder.encodeMany(keys)); - } - - @Override - public void srandmember(final String key) { - srandmember(SafeEncoder.encode(key)); - } - - @Override - public void zadd(final String key, final double score, final String member) { - zadd(SafeEncoder.encode(key), score, SafeEncoder.encode(member)); - } - - @Override - public void zadd(final String key, final double score, final String member, - final ZAddParams params) { - zadd(SafeEncoder.encode(key), score, SafeEncoder.encode(member), params); - } - - @Override - public void zadd(final String key, final Map scoreMembers) { - HashMap binaryScoreMembers = convertScoreMembersToBinary(scoreMembers); - zadd(SafeEncoder.encode(key), binaryScoreMembers); - } - - @Override - public void zadd(final String key, final Map scoreMembers, final ZAddParams params) { - HashMap binaryScoreMembers = convertScoreMembersToBinary(scoreMembers); - zadd(SafeEncoder.encode(key), binaryScoreMembers, params); - } - - @Override - public void zaddIncr(final String key, final double score, final String member, final ZAddParams params) { - zaddIncr(SafeEncoder.encode(key), score, SafeEncoder.encode(member), params); - } - - @Override - public void zdiff(final String... keys) { - zdiff(SafeEncoder.encodeMany(keys)); - } - - @Override - public void zdiffWithScores(final String... keys) { - zdiffWithScores(SafeEncoder.encodeMany(keys)); - } - - @Override - public void zrange(final String key, final long start, final long stop) { - zrange(SafeEncoder.encode(key), start, stop); - } - - @Override - public void zrem(final String key, final String... members) { - zrem(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - @Override - public void zincrby(final String key, final double increment, final String member) { - zincrby(SafeEncoder.encode(key), increment, SafeEncoder.encode(member)); - } - - @Override - public void zincrby(final String key, final double increment, final String member, - final ZIncrByParams params) { - zincrby(SafeEncoder.encode(key), increment, SafeEncoder.encode(member), params); - } - - @Override - public void zrank(final String key, final String member) { - zrank(SafeEncoder.encode(key), SafeEncoder.encode(member)); - } - - @Override - public void zrevrank(final String key, final String member) { - zrevrank(SafeEncoder.encode(key), SafeEncoder.encode(member)); - } - - @Override - public void zrevrange(final String key, final long start, final long stop) { - zrevrange(SafeEncoder.encode(key), start, stop); - } - - @Override - public void zrangeWithScores(final String key, final long start, final long stop) { - zrangeWithScores(SafeEncoder.encode(key), start, stop); - } - - @Override - public void zrevrangeWithScores(final String key, final long start, final long stop) { - zrevrangeWithScores(SafeEncoder.encode(key), start, stop); - } - - @Override - public void zrandmember(final String key) { - zrandmember(SafeEncoder.encode(key)); - } - - @Override - public void zrandmember(final String key, final long count) { - zrandmember(SafeEncoder.encode(key), count); - } - - @Override - public void zrandmemberWithScores(final String key, final long count) { - zrandmemberWithScores(SafeEncoder.encode(key), count); - } - - @Override - public void zcard(final String key) { - zcard(SafeEncoder.encode(key)); - } - - @Override - public void zscore(final String key, final String member) { - zscore(SafeEncoder.encode(key), SafeEncoder.encode(member)); - } - - @Override - public void zmscore(final String key, final String... members) { - zmscore(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - @Override - public void zpopmax(final String key) { - zpopmax(SafeEncoder.encode(key)); - } - - @Override - public void zpopmax(final String key, final int count) { - zpopmax(SafeEncoder.encode(key), count); - } - - @Override - public void zpopmin(final String key) { - zpopmin(SafeEncoder.encode(key)); - } - - @Override - public void zpopmin(final String key, final long count) { - zpopmin(SafeEncoder.encode(key), count); - } - - @Override - public void watch(final String... keys) { - watch(SafeEncoder.encodeMany(keys)); - } - - @Override - public void sort(final String key) { - sort(SafeEncoder.encode(key)); - } - - @Override - public void sort(final String key, final SortingParams sortingParameters) { - sort(SafeEncoder.encode(key), sortingParameters); - } - - @Override - public void sort(final String key, final SortingParams sortingParameters, final String dstkey) { - sort(SafeEncoder.encode(key), sortingParameters, SafeEncoder.encode(dstkey)); - } - - @Override - public void sort(final String key, final String dstkey) { - sort(SafeEncoder.encode(key), SafeEncoder.encode(dstkey)); - } - - @Override - public void lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { - lmove(SafeEncoder.encode(srcKey), SafeEncoder.encode(dstKey), from, to); - } - - @Override - public void blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, - double timeout) { - blmove(SafeEncoder.encode(srcKey), SafeEncoder.encode(dstKey), from, to, timeout); - } - - @Override - public void blpop(final String[] args) { - blpop(SafeEncoder.encodeMany(args)); - } - - @Override - public void blpop(final int timeout, final String... keys) { - blpop(timeout, SafeEncoder.encodeMany(keys)); - } - - @Override - public void blpop(final double timeout, final String... keys) { - blpop(timeout, SafeEncoder.encodeMany(keys)); - } - - @Override - public void brpop(final String[] args) { - brpop(SafeEncoder.encodeMany(args)); - } - - @Override - public void brpop(final int timeout, final String... keys) { - brpop(timeout, SafeEncoder.encodeMany(keys)); - } - - @Override - public void brpop(final double timeout, final String... keys) { - brpop(timeout, SafeEncoder.encodeMany(keys)); - } - - @Override - public void bzpopmax(final double timeout, final String... keys) { - bzpopmax(timeout, SafeEncoder.encodeMany(keys)); - } - - @Override - public void bzpopmin(final double timeout, final String... keys) { - bzpopmin(timeout, SafeEncoder.encodeMany(keys)); - } - - @Override - public void zcount(final String key, final double min, final double max) { - zcount(SafeEncoder.encode(key), toByteArray(min), toByteArray(max)); - } - - @Override - public void zcount(final String key, final String min, final String max) { - zcount(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); - } - - @Override - public void zdiffStore(final String dstkey, final String... keys) { - zdiffStore(SafeEncoder.encode(dstkey), SafeEncoder.encodeMany(keys)); - } - - @Override - public void zrangeByScore(final String key, final double min, final double max) { - zrangeByScore(SafeEncoder.encode(key), toByteArray(min), toByteArray(max)); - } - - @Override - public void zrangeByScore(final String key, final String min, final String max) { - zrangeByScore(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); - } - - @Override - public void zrangeByScore(final String key, final double min, final double max, final int offset, - final int count) { - zrangeByScore(SafeEncoder.encode(key), toByteArray(min), toByteArray(max), offset, count); - } - - @Override - public void zrangeByScoreWithScores(final String key, final double min, final double max) { - zrangeByScoreWithScores(SafeEncoder.encode(key), toByteArray(min), toByteArray(max)); - } - - @Override - public void zrangeByScoreWithScores(final String key, final double min, final double max, - final int offset, final int count) { - zrangeByScoreWithScores(SafeEncoder.encode(key), toByteArray(min), toByteArray(max), offset, - count); - } - - @Override - public void zrevrangeByScore(final String key, final double max, final double min) { - zrevrangeByScore(SafeEncoder.encode(key), toByteArray(max), toByteArray(min)); - } - - @Override - public void zrangeByScore(final String key, final String min, final String max, final int offset, - final int count) { - zrangeByScore(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max), - offset, count); - } - - @Override - public void zrangeByScoreWithScores(final String key, final String min, final String max) { - zrangeByScoreWithScores(SafeEncoder.encode(key), SafeEncoder.encode(min), - SafeEncoder.encode(max)); - } - - @Override - public void zrangeByScoreWithScores(final String key, final String min, final String max, - final int offset, final int count) { - zrangeByScoreWithScores(SafeEncoder.encode(key), SafeEncoder.encode(min), - SafeEncoder.encode(max), offset, count); - } - - @Override - public void zrevrangeByScore(final String key, final String max, final String min) { - zrevrangeByScore(SafeEncoder.encode(key), SafeEncoder.encode(max), SafeEncoder.encode(min)); - } - - @Override - public void zrevrangeByScore(final String key, final double max, final double min, - final int offset, final int count) { - zrevrangeByScore(SafeEncoder.encode(key), toByteArray(max), toByteArray(min), offset, count); - } - - @Override - public void zrevrangeByScore(final String key, final String max, final String min, - final int offset, final int count) { - zrevrangeByScore(SafeEncoder.encode(key), SafeEncoder.encode(max), SafeEncoder.encode(min), - offset, count); - } - - @Override - public void zrevrangeByScoreWithScores(final String key, final double max, final double min) { - zrevrangeByScoreWithScores(SafeEncoder.encode(key), toByteArray(max), toByteArray(min)); - } - - @Override - public void zrevrangeByScoreWithScores(final String key, final String max, final String min) { - zrevrangeByScoreWithScores(SafeEncoder.encode(key), SafeEncoder.encode(max), - SafeEncoder.encode(min)); - } - - @Override - public void zrevrangeByScoreWithScores(final String key, final double max, final double min, - final int offset, final int count) { - zrevrangeByScoreWithScores(SafeEncoder.encode(key), toByteArray(max), toByteArray(min), offset, - count); - } - - @Override - public void zrevrangeByScoreWithScores(final String key, final String max, final String min, - final int offset, final int count) { - zrevrangeByScoreWithScores(SafeEncoder.encode(key), SafeEncoder.encode(max), - SafeEncoder.encode(min), offset, count); - } - - @Override - public void zremrangeByRank(final String key, final long start, final long stop) { - zremrangeByRank(SafeEncoder.encode(key), start, stop); - } - - @Override - public void zremrangeByScore(final String key, final double min, final double max) { - zremrangeByScore(SafeEncoder.encode(key), toByteArray(min), toByteArray(max)); - } - - @Override - public void zremrangeByScore(final String key, final String min, final String max) { - zremrangeByScore(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); - } - - @Override - public void zunion(final ZParams params, final String... keys) { - zunion(params, SafeEncoder.encodeMany(keys)); - } - - @Override - public void zunionWithScores(final ZParams params, final String... keys) { - zunionWithScores(params, SafeEncoder.encodeMany(keys)); - } - - @Override - public void zunionstore(final String dstkey, final String... sets) { - zunionstore(SafeEncoder.encode(dstkey), SafeEncoder.encodeMany(sets)); - } - - @Override - public void zunionstore(final String dstkey, final ZParams params, final String... sets) { - zunionstore(SafeEncoder.encode(dstkey), params, SafeEncoder.encodeMany(sets)); - } - - @Override - public void zinter(final ZParams params, final String... keys) { - zinter(params, SafeEncoder.encodeMany(keys)); - } - - @Override - public void zinterWithScores(final ZParams params, final String... keys) { - zinterWithScores(params, SafeEncoder.encodeMany(keys)); - } - - @Override - public void zinterstore(final String dstkey, final String... sets) { - zinterstore(SafeEncoder.encode(dstkey), SafeEncoder.encodeMany(sets)); - } - - @Override - public void zinterstore(final String dstkey, final ZParams params, final String... sets) { - zinterstore(SafeEncoder.encode(dstkey), params, SafeEncoder.encodeMany(sets)); - } - - public void zlexcount(final String key, final String min, final String max) { - zlexcount(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); - } - - public void zrangeByLex(final String key, final String min, final String max) { - zrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); - } - - public void zrangeByLex(final String key, final String min, final String max, final int offset, - final int count) { - zrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max), offset, - count); - } - - public void zrevrangeByLex(final String key, final String max, final String min) { - zrevrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(max), SafeEncoder.encode(min)); - } - - public void zrevrangeByLex(final String key, final String max, final String min, - final int offset, final int count) { - zrevrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(max), SafeEncoder.encode(min), - offset, count); - } - - public void zremrangeByLex(final String key, final String min, final String max) { - zremrangeByLex(SafeEncoder.encode(key), SafeEncoder.encode(min), SafeEncoder.encode(max)); - } - - @Override - public void strlen(final String key) { - strlen(SafeEncoder.encode(key)); - } - - @Override - public void strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params) { - strAlgoLCSKeys(SafeEncoder.encode(keyA), SafeEncoder.encode(keyB), params); - } - - @Override - public void strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params) { - strAlgoLCSStrings(SafeEncoder.encode(strA), SafeEncoder.encode(strB), params); - } - - @Override - public void lpushx(final String key, final String... string) { - lpushx(SafeEncoder.encode(key), SafeEncoder.encodeMany(string)); - } - - @Override - public void persist(final String key) { - persist(SafeEncoder.encode(key)); - } - - @Override - public void rpushx(final String key, final String... string) { - rpushx(SafeEncoder.encode(key), SafeEncoder.encodeMany(string)); - } - - @Override - public void echo(final String string) { - echo(SafeEncoder.encode(string)); - } - - @Override - public void linsert(final String key, final ListPosition where, final String pivot, - final String value) { - linsert(SafeEncoder.encode(key), where, SafeEncoder.encode(pivot), SafeEncoder.encode(value)); - } - - @Override - public void brpoplpush(final String source, final String destination, final int timeout) { - brpoplpush(SafeEncoder.encode(source), SafeEncoder.encode(destination), timeout); - } - - @Override - public void setbit(final String key, final long offset, final boolean value) { - setbit(SafeEncoder.encode(key), offset, value); - } - - @Override - public void setbit(final String key, final long offset, final String value) { - setbit(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); - } - - @Override - public void getbit(final String key, final long offset) { - getbit(SafeEncoder.encode(key), offset); - } - - public void bitpos(final String key, final boolean value, final BitPosParams params) { - bitpos(SafeEncoder.encode(key), value, params); - } - - @Override - public void setrange(final String key, final long offset, final String value) { - setrange(SafeEncoder.encode(key), offset, SafeEncoder.encode(value)); - } - - @Override - public void getrange(final String key, final long startOffset, final long endOffset) { - getrange(SafeEncoder.encode(key), startOffset, endOffset); - } - - public void publish(final String channel, final String message) { - publish(SafeEncoder.encode(channel), SafeEncoder.encode(message)); - } - - public void unsubscribe(final String... channels) { - unsubscribe(SafeEncoder.encodeMany(channels)); - } - - public void psubscribe(final String... patterns) { - psubscribe(SafeEncoder.encodeMany(patterns)); - } - - public void punsubscribe(final String... patterns) { - punsubscribe(SafeEncoder.encodeMany(patterns)); - } - - public void subscribe(final String... channels) { - subscribe(SafeEncoder.encodeMany(channels)); - } - - public void pubsubChannels() { - pubsub(Protocol.PUBSUB_CHANNELS); - } - - public void pubsubChannels(final String pattern) { - pubsub(Protocol.PUBSUB_CHANNELS, pattern); - } - - public void pubsubNumPat() { - pubsub(Protocol.PUBSUB_NUM_PAT); - } - - public void pubsubNumSub(final String... channels) { - pubsub(Protocol.PUBSUB_NUMSUB, channels); - } - - @Override - public void configSet(final String parameter, final String value) { - configSet(SafeEncoder.encode(parameter), SafeEncoder.encode(value)); - } - - @Override - public void configGet(final String pattern) { - configGet(SafeEncoder.encode(pattern)); - } - - public void eval(final String script, final int keyCount, final String... params) { - eval(SafeEncoder.encode(script), toByteArray(keyCount), SafeEncoder.encodeMany(params)); - } - - public void evalsha(final String sha1, final int keyCount, final String... params) { - evalsha(SafeEncoder.encode(sha1), toByteArray(keyCount), SafeEncoder.encodeMany(params)); - } - - public void scriptExists(final String... sha1) { - scriptExists(SafeEncoder.encodeMany(sha1)); - } - - public void scriptLoad(final String script) { - scriptLoad(SafeEncoder.encode(script)); - } - - @Override - public void objectRefcount(final String key) { - objectRefcount(SafeEncoder.encode(key)); - } - - @Override - public void objectIdletime(final String key) { - objectIdletime(SafeEncoder.encode(key)); - } - - @Override - public void objectEncoding(final String key) { - objectEncoding(SafeEncoder.encode(key)); - } - - @Override - public void objectFreq(final String key) { - objectFreq(SafeEncoder.encode(key)); - } - - @Override - public void bitcount(final String key) { - bitcount(SafeEncoder.encode(key)); - } - - @Override - public void bitcount(final String key, final long start, final long end) { - bitcount(SafeEncoder.encode(key), start, end); - } - - @Override - public void bitop(final BitOP op, final String destKey, final String... srcKeys) { - bitop(op, SafeEncoder.encode(destKey), SafeEncoder.encodeMany(srcKeys)); - } - - public void sentinel(final String... args) { - sentinel(SafeEncoder.encodeMany(args)); - } - - public void sentinel(SentinelKeyword subcommand, final String... args) { - sentinel(subcommand, SafeEncoder.encodeMany(args)); - } - - @Override - public void dump(final String key) { - dump(SafeEncoder.encode(key)); - } - - @Override - public void restore(final String key, final long ttl, final byte[] serializedValue) { - restore(SafeEncoder.encode(key), ttl, serializedValue); - } - - @Override - public void restoreReplace(final String key, final long ttl, final byte[] serializedValue) { - restoreReplace(SafeEncoder.encode(key), ttl, serializedValue); - } - - @Override - public void restore(final String key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - restore(SafeEncoder.encode(key), ttl, serializedValue, params); - } - - public void pexpire(final String key, final long milliseconds) { - pexpire(SafeEncoder.encode(key), milliseconds); - } - - public void pexpireAt(final String key, final long millisecondsTimestamp) { - pexpireAt(SafeEncoder.encode(key), millisecondsTimestamp); - } - - @Override - public void pttl(final String key) { - pttl(SafeEncoder.encode(key)); - } - - @Override - public void incrByFloat(final String key, final double increment) { - incrByFloat(SafeEncoder.encode(key), increment); - } - - public void psetex(final String key, final long milliseconds, final String value) { - psetex(SafeEncoder.encode(key), milliseconds, SafeEncoder.encode(value)); - } - - public void srandmember(final String key, final int count) { - srandmember(SafeEncoder.encode(key), count); - } - - public void memoryUsage(final String key) { - memoryUsage(SafeEncoder.encode(key)); - } - - public void memoryUsage(final String key, final int samples) { - memoryUsage(SafeEncoder.encode(key), samples); - } - - public void clientKill(final String ipPort) { - clientKill(SafeEncoder.encode(ipPort)); - } - - public void clientSetname(final String name) { - clientSetname(SafeEncoder.encode(name)); - } - - @Override - public void migrate(final String host, final int port, final String key, final int destinationDb, - final int timeout) { - migrate(host, port, SafeEncoder.encode(key), destinationDb, timeout); - } - - @Override - public void migrate(final String host, final int port, final int destinationDB, - final int timeout, final MigrateParams params, String... keys) { - migrate(host, port, destinationDB, timeout, params, SafeEncoder.encodeMany(keys)); - } - - @Override - public void hincrByFloat(final String key, final String field, final double increment) { - hincrByFloat(SafeEncoder.encode(key), SafeEncoder.encode(field), increment); - } - - @Override - public void scan(final String cursor, final ScanParams params) { - scan(SafeEncoder.encode(cursor), params); - } - - @Override - public void scan(final String cursor, final ScanParams params, final String type) { - scan(SafeEncoder.encode(cursor), params, type != null ? SafeEncoder.encode(type) : null); - } - - @Override - public void hscan(final String key, final String cursor, final ScanParams params) { - hscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); - } - - @Override - public void sscan(final String key, final String cursor, final ScanParams params) { - sscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); - } - - @Override - public void zscan(final String key, final String cursor, final ScanParams params) { - zscan(SafeEncoder.encode(key), SafeEncoder.encode(cursor), params); - } - - public void cluster(final String subcommand, final int... args) { - final byte[][] arg = new byte[args.length + 1][]; - for (int i = 1; i < arg.length; i++) { - arg[i] = toByteArray(args[i - 1]); - } - arg[0] = SafeEncoder.encode(subcommand); - cluster(arg); - } - - public void pubsub(final String subcommand, final String... args) { - final byte[][] arg = new byte[args.length + 1][]; - for (int i = 1; i < arg.length; i++) { - arg[i] = SafeEncoder.encode(args[i - 1]); - } - arg[0] = SafeEncoder.encode(subcommand); - pubsub(arg); - } - - public void cluster(final String subcommand, final String... args) { - final byte[][] arg = new byte[args.length + 1][]; - for (int i = 1; i < arg.length; i++) { - arg[i] = SafeEncoder.encode(args[i - 1]); - } - arg[0] = SafeEncoder.encode(subcommand); - cluster(arg); - } - - public void cluster(final String subcommand) { - final byte[][] arg = new byte[1][]; - arg[0] = SafeEncoder.encode(subcommand); - cluster(arg); - } - - public void clusterNodes() { - cluster(ClusterKeyword.NODES); - } - - public void clusterReplicas(final String nodeId) { - cluster(ClusterKeyword.REPLICAS, SafeEncoder.encode(nodeId)); - } - - public void clusterMeet(final String ip, final int port) { - cluster(Protocol.CLUSTER_MEET, ip, String.valueOf(port)); - } - - /** - * @deprecated Use {@link Client#clusterReset(redis.clients.jedis.args.ClusterResetType)}. - */ - @Deprecated - public void clusterReset(final ClusterReset resetType) { - cluster(Protocol.CLUSTER_RESET, resetType.name()); - } - - public void clusterReset(final ClusterResetType resetType) { - if (resetType == null) { - cluster(ClusterKeyword.RESET); - } else { - cluster(ClusterKeyword.RESET, resetType.getRaw()); - } - } - - public void clusterAddSlots(final int... slots) { - cluster(Protocol.CLUSTER_ADDSLOTS, slots); - } - - public void clusterDelSlots(final int... slots) { - cluster(Protocol.CLUSTER_DELSLOTS, slots); - } - - public void clusterInfo() { - cluster(Protocol.CLUSTER_INFO); - } - - public void clusterGetKeysInSlot(final int slot, final int count) { - final int[] args = new int[] { slot, count }; - cluster(Protocol.CLUSTER_GETKEYSINSLOT, args); - } - - public void clusterSetSlotNode(final int slot, final String nodeId) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_NODE, nodeId); - } - - public void clusterSetSlotMigrating(final int slot, final String nodeId) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_MIGRATING, - nodeId); - } - - public void clusterSetSlotImporting(final int slot, final String nodeId) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_IMPORTING, - nodeId); - } - - public void pfadd(final String key, final String... elements) { - pfadd(SafeEncoder.encode(key), SafeEncoder.encodeMany(elements)); - } - - public void pfcount(final String key) { - pfcount(SafeEncoder.encode(key)); - } - - public void pfcount(final String... keys) { - pfcount(SafeEncoder.encodeMany(keys)); - } - - public void pfmerge(final String destkey, final String... sourcekeys) { - pfmerge(SafeEncoder.encode(destkey), SafeEncoder.encodeMany(sourcekeys)); - } - - public void clusterSetSlotStable(final int slot) { - cluster(Protocol.CLUSTER_SETSLOT, String.valueOf(slot), Protocol.CLUSTER_SETSLOT_STABLE); - } - - public void clusterForget(final String nodeId) { - cluster(Protocol.CLUSTER_FORGET, nodeId); - } - - public void clusterFlushSlots() { - cluster(Protocol.CLUSTER_FLUSHSLOT); - } - - public void clusterKeySlot(final String key) { - cluster(Protocol.CLUSTER_KEYSLOT, key); - } - - public void clusterCountKeysInSlot(final int slot) { - cluster(Protocol.CLUSTER_COUNTKEYINSLOT, String.valueOf(slot)); - } - - public void clusterSaveConfig() { - cluster(Protocol.CLUSTER_SAVECONFIG); - } - - public void clusterReplicate(final String nodeId) { - cluster(Protocol.CLUSTER_REPLICATE, nodeId); - } - - public void clusterSlaves(final String nodeId) { - cluster(Protocol.CLUSTER_SLAVES, nodeId); - } - - public void clusterFailover() { - cluster(Protocol.CLUSTER_FAILOVER); - } - - public void clusterFailover(ClusterFailoverOption failoverOption) { - if (failoverOption == null) { - cluster(ClusterKeyword.FAILOVER); - } else { - cluster(ClusterKeyword.FAILOVER, failoverOption.getRaw()); - } - } - - public void clusterSlots() { - cluster(Protocol.CLUSTER_SLOTS); - } - - public void clusterMyId() { - cluster(ClusterKeyword.MYID); - } - - public void geoadd(final String key, final double longitude, final double latitude, - final String member) { - geoadd(SafeEncoder.encode(key), longitude, latitude, SafeEncoder.encode(member)); - } - - public void geoadd(final String key, final Map memberCoordinateMap) { - geoadd(SafeEncoder.encode(key), convertMemberCoordinateMapToBinary(memberCoordinateMap)); - } - - public void geoadd(final String key, final GeoAddParams params, final Map memberCoordinateMap) { - geoadd(SafeEncoder.encode(key), params, convertMemberCoordinateMapToBinary(memberCoordinateMap)); - } - - public void geodist(final String key, final String member1, final String member2) { - geodist(SafeEncoder.encode(key), SafeEncoder.encode(member1), SafeEncoder.encode(member2)); - } - - public void geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { - geodist(SafeEncoder.encode(key), SafeEncoder.encode(member1), SafeEncoder.encode(member2), unit); - } - - public void geohash(final String key, final String... members) { - geohash(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - public void geopos(final String key, final String[] members) { - geopos(SafeEncoder.encode(key), SafeEncoder.encodeMany(members)); - } - - public void georadius(final String key, final double longitude, final double latitude, - final double radius, final GeoUnit unit) { - georadius(SafeEncoder.encode(key), longitude, latitude, radius, unit); - } - - public void georadiusReadonly(final String key, final double longitude, final double latitude, - final double radius, final GeoUnit unit) { - georadiusReadonly(SafeEncoder.encode(key), longitude, latitude, radius, unit); - } - - public void georadius(final String key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - georadius(SafeEncoder.encode(key), longitude, latitude, radius, unit, param); - } - - public void georadiusStore(final String key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - GeoRadiusStoreParam storeParam) { - georadiusStore(SafeEncoder.encode(key), longitude, latitude, radius, unit, param, storeParam); - } - - public void georadiusReadonly(final String key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - georadiusReadonly(SafeEncoder.encode(key), longitude, latitude, radius, unit, param); - } - - public void georadiusByMember(final String key, final String member, final double radius, - final GeoUnit unit) { - georadiusByMember(SafeEncoder.encode(key), SafeEncoder.encode(member), radius, unit); - } - - public void georadiusByMemberReadonly(final String key, final String member, final double radius, - final GeoUnit unit) { - georadiusByMemberReadonly(SafeEncoder.encode(key), SafeEncoder.encode(member), radius, unit); - } - - public void georadiusByMember(final String key, final String member, final double radius, - final GeoUnit unit, final GeoRadiusParam param) { - georadiusByMember(SafeEncoder.encode(key), SafeEncoder.encode(member), radius, unit, param); - } - - public void georadiusByMemberStore(final String key, final String member, final double radius, - final GeoUnit unit, final GeoRadiusParam param, final GeoRadiusStoreParam storeParam) { - georadiusByMemberStore(SafeEncoder.encode(key), SafeEncoder.encode(member), radius, unit, - param, storeParam); - } - - public void georadiusByMemberReadonly(final String key, final String member, final double radius, - final GeoUnit unit, final GeoRadiusParam param) { - georadiusByMemberReadonly(SafeEncoder.encode(key), SafeEncoder.encode(member), radius, unit, - param); - } - - public void moduleLoad(final String path) { - moduleLoad(SafeEncoder.encode(path)); - } - - public void moduleUnload(final String name) { - moduleUnload(SafeEncoder.encode(name)); - } - - public void aclGetUser(final String name) { - aclGetUser(SafeEncoder.encode(name)); - } - - public void aclSetUser(final String name) { - aclSetUser(SafeEncoder.encode(name)); - } - - public void aclSetUser(String name, String... parameters) { - aclSetUser(SafeEncoder.encode(name), SafeEncoder.encodeMany(parameters)); - } - - public void aclCat(final String category) { - aclCat(SafeEncoder.encode(category)); - } - - public void aclLog(final String options) { - aclLog(SafeEncoder.encode(options)); - } - - public void aclDelUser(final String name) { - aclDelUser(SafeEncoder.encode(name)); - } - - private HashMap convertScoreMembersToBinary(final Map scoreMembers) { - HashMap binaryScoreMembers = new HashMap<>(); - for (Entry entry : scoreMembers.entrySet()) { - binaryScoreMembers.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); - } - return binaryScoreMembers; - } - - private HashMap convertMemberCoordinateMapToBinary( - final Map memberCoordinateMap) { - HashMap binaryMemberCoordinateMap = new HashMap<>(); - for (Entry entry : memberCoordinateMap.entrySet()) { - binaryMemberCoordinateMap.put(SafeEncoder.encode(entry.getKey()), entry.getValue()); - } - return binaryMemberCoordinateMap; - } - - @Override - public void bitfield(final String key, final String... arguments) { - bitfield(SafeEncoder.encode(key), SafeEncoder.encodeMany(arguments)); - } - - @Override - public void bitfieldReadonly(String key, final String... arguments) { - bitfieldReadonly(SafeEncoder.encode(key), SafeEncoder.encodeMany(arguments)); - } - - @Override - public void hstrlen(final String key, final String field) { - hstrlen(SafeEncoder.encode(key), SafeEncoder.encode(field)); - } - - @Override - public void xadd(final String key, final StreamEntryID id, final Map hash, - long maxLen, boolean approximateLength) { - xadd(SafeEncoder.encode(key), SafeEncoder.encode(id == null ? "*" : id.toString()), - encodeStringMap(hash), maxLen, approximateLength); - } - - @Override - public void xadd(final String key, final Map hash, final XAddParams params) { - xadd(SafeEncoder.encode(key), encodeStringMap(hash), params); - } - - private static Map encodeStringMap(Map map) { - final Map bhash = new HashMap<>(map.size()); - for (final Map.Entry entry : map.entrySet()) { - bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue())); - } - return bhash; - } - - @Override - public void xlen(final String key) { - xlen(SafeEncoder.encode(key)); - } - - @Override - public void xrange(final String key, final StreamEntryID start, final StreamEntryID end) { - xrange(SafeEncoder.encode(key), SafeEncoder.encode(start == null ? "-" : start.toString()), - SafeEncoder.encode(end == null ? "+" : end.toString())); - } - - @Override - public void xrange(final String key, final StreamEntryID start, final StreamEntryID end, - final int count) { - xrange(SafeEncoder.encode(key), SafeEncoder.encode(start == null ? "-" : start.toString()), - SafeEncoder.encode(end == null ? "+" : end.toString()), count); - } - - @Override - public void xrange(final String key, final StreamEntryID start, final StreamEntryID end, - final long count) { - xrange(SafeEncoder.encode(key), SafeEncoder.encode(start == null ? "-" : start.toString()), - SafeEncoder.encode(end == null ? "+" : end.toString()), count); - } - - @Override - public void xrevrange(String key, StreamEntryID end, StreamEntryID start) { - xrevrange(SafeEncoder.encode(key), SafeEncoder.encode(end == null ? "+" : end.toString()), - SafeEncoder.encode(start == null ? "-" : start.toString())); - } - - @Override - public void xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { - xrevrange(SafeEncoder.encode(key), SafeEncoder.encode(end == null ? "+" : end.toString()), - SafeEncoder.encode(start == null ? "-" : start.toString()), count); - } - - @Override - public void xread(final int count, final long block, - final Entry... streams) { - final Map bhash = new HashMap<>(streams.length); - for (final Entry entry : streams) { - bhash.put(SafeEncoder.encode(entry.getKey()), - SafeEncoder.encode(entry.getValue() == null ? "0-0" : entry.getValue().toString())); - } - xread(count, block, bhash); - } - - @Override - public void xread(final XReadParams params, final Map streams) { - final byte[][] bparams = params.getByteParams(); - final int paramLength = bparams.length; - - final byte[][] args = new byte[paramLength + 1 + streams.size() * 2][]; - System.arraycopy(bparams, 0, args, 0, paramLength); - - args[paramLength] = Protocol.Keyword.STREAMS.getRaw(); - int keyIndex = paramLength + 1; - int idsIndex = keyIndex + streams.size(); - for (Entry entry : streams.entrySet()) { - args[keyIndex++] = SafeEncoder.encode(entry.getKey()); - args[idsIndex++] = SafeEncoder.encode(entry.getValue().toString()); - } - - sendCommand(Protocol.Command.XREAD, args); - } - - @Override - public void xack(final String key, final String group, final StreamEntryID... ids) { - final byte[][] bids = new byte[ids.length][]; - for (int i = 0; i < ids.length; ++i) { - StreamEntryID id = ids[i]; - bids[i] = SafeEncoder.encode(id == null ? "0-0" : id.toString()); - } - xack(SafeEncoder.encode(key), SafeEncoder.encode(group), bids); - } - - @Override - public void xgroupCreate(String key, String groupname, StreamEntryID id, boolean makeStream) { - xgroupCreate(SafeEncoder.encode(key), SafeEncoder.encode(groupname), - SafeEncoder.encode(id == null ? "0-0" : id.toString()), makeStream); - } - - @Override - public void xgroupSetID(String key, String groupname, StreamEntryID id) { - xgroupSetID(SafeEncoder.encode(key), SafeEncoder.encode(groupname), - SafeEncoder.encode(id == null ? "0-0" : id.toString())); - } - - @Override - public void xgroupDestroy(String key, String groupname) { - xgroupDestroy(SafeEncoder.encode(key), SafeEncoder.encode(groupname)); - } - - @Override - public void xgroupDelConsumer(String key, String groupname, String consumerName) { - xgroupDelConsumer(SafeEncoder.encode(key), SafeEncoder.encode(groupname), - SafeEncoder.encode(consumerName)); - } - - @Override - public void xdel(final String key, final StreamEntryID... ids) { - final byte[][] bids = new byte[ids.length][]; - for (int i = 0; i < ids.length; ++i) { - StreamEntryID id = ids[i]; - bids[i] = SafeEncoder.encode(id == null ? "0-0" : id.toString()); - } - xdel(SafeEncoder.encode(key), bids); - } - - @Override - public void xtrim(String key, long maxLen, boolean approximateLength) { - xtrim(SafeEncoder.encode(key), maxLen, approximateLength); - } - - @Override - public void xtrim(String key, XTrimParams params) { - xtrim(SafeEncoder.encode(key), params); - } - - @Override - public void xreadGroup(String groupname, String consumer, int count, long block, boolean noAck, - Entry... streams) { - final Map bhash = new HashMap<>(streams.length); - for (final Entry entry : streams) { - bhash.put(SafeEncoder.encode(entry.getKey()), SafeEncoder.encode(entry.getValue()==null ? ">" : entry.getValue().toString())); - } - xreadGroup(SafeEncoder.encode(groupname), SafeEncoder.encode(consumer), count, block, noAck, bhash); - } - - @Override - public void xreadGroup(String groupname, String consumer, XReadGroupParams params, Map streams) { - final byte[][] bparams = params.getByteParams(); - final int paramLength = bparams.length; - - final byte[][] args = new byte[3 + paramLength + 1 + streams.size() * 2][]; - int index = 0; - args[index++] = Protocol.Keyword.GROUP.getRaw(); - args[index++] = SafeEncoder.encode(groupname); - args[index++] = SafeEncoder.encode(consumer); - System.arraycopy(bparams, 0, args, index, paramLength); - index += paramLength; - - args[index++] = Protocol.Keyword.STREAMS.getRaw(); - int keyIndex = index; - int idsIndex = keyIndex + streams.size(); - for (Entry entry : streams.entrySet()) { - args[keyIndex++] = SafeEncoder.encode(entry.getKey()); - args[idsIndex++] = SafeEncoder.encode(entry.getValue().toString()); - } - - sendCommand(Protocol.Command.XREADGROUP, args); - } - - @Override - public void xpending(String key, String groupname) { - xpending(SafeEncoder.encode(key), SafeEncoder.encode(groupname)); - } - - @Override - public void xpending(String key, String groupname, StreamEntryID start, StreamEntryID end, - int count, String consumername) { - xpending(SafeEncoder.encode(key), SafeEncoder.encode(groupname), SafeEncoder.encode(start==null ? "-" : start.toString()), - SafeEncoder.encode(end==null ? "+" : end.toString()), count, consumername == null? null : SafeEncoder.encode(consumername)); - } - - @Override - public void xpending(String key, String groupname, XPendingParams params) { - xpending(SafeEncoder.encode(key), SafeEncoder.encode(groupname), params); - } - - @Override - public void xclaim(String key, String group, String consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, StreamEntryID... ids) { - final byte[][] bids = convertStreamEntryIDsToBinary(ids); - xclaim(SafeEncoder.encode(key), SafeEncoder.encode(group), SafeEncoder.encode(consumername), minIdleTime, newIdleTime, retries, force, bids); - } - - @Override - public void xclaim(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids) { - final byte[][] bids = convertStreamEntryIDsToBinary(ids); - xclaim(SafeEncoder.encode(key), SafeEncoder.encode(group), SafeEncoder.encode(consumername), - minIdleTime, params, bids); - } - - @Override - public void xclaimJustId(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids) { - final byte[][] bids = convertStreamEntryIDsToBinary(ids); - xclaimJustId(SafeEncoder.encode(key), SafeEncoder.encode(group), SafeEncoder.encode(consumername), - minIdleTime, params, bids); - } - - @Override - public void xautoclaim(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params) { - xautoclaim(SafeEncoder.encode(key), SafeEncoder.encode(group), SafeEncoder.encode(consumerName), - minIdleTime, SafeEncoder.encode(start == null ? "-" : start.toString()), params); - } - - @Override - public void xautoclaimJustId(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params) { - xautoclaimJustId(SafeEncoder.encode(key), SafeEncoder.encode(group), SafeEncoder.encode(consumerName), - minIdleTime, SafeEncoder.encode(start == null ? "-" : start.toString()), params); - } - - @Override - public void xinfoStream(String key) { - xinfoStream(SafeEncoder.encode(key)); - } - - @Override - public void xinfoGroup(String key) { - xinfoGroup(SafeEncoder.encode(key)); - } - - @Override - public void xinfoConsumers(String key, String group) { - xinfoConsumers(SafeEncoder.encode(key), SafeEncoder.encode(group)); - } - - private byte[][] convertStreamEntryIDsToBinary(StreamEntryID... ids) { - final byte[][] bids = new byte[ids.length][]; - for (int i = 0; i < ids.length; i++) { - bids[i] = SafeEncoder.encode(ids[i].toString()); - } - return bids; - } -} diff --git a/src/main/java/redis/clients/jedis/ClusterCommandArguments.java b/src/main/java/redis/clients/jedis/ClusterCommandArguments.java new file mode 100644 index 0000000000..56fc1e8610 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ClusterCommandArguments.java @@ -0,0 +1,40 @@ +package redis.clients.jedis; + +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.exceptions.JedisClusterOperationException; +import redis.clients.jedis.util.JedisClusterCRC16; + +public class ClusterCommandArguments extends CommandArguments { + + private int commandHashSlot = -1; + + public ClusterCommandArguments(ProtocolCommand command) { + super(command); + } + + public int getCommandHashSlot() { + return commandHashSlot; + } + + @Override + protected CommandArguments processKey(byte[] key) { + final int hashSlot = JedisClusterCRC16.getSlot(key); + if (commandHashSlot < 0) { + commandHashSlot = hashSlot; + } else if (commandHashSlot != hashSlot) { + throw new JedisClusterOperationException("Keys must belong to same hashslot."); + } + return this; + } + + @Override + protected CommandArguments processKey(String key) { + final int hashSlot = JedisClusterCRC16.getSlot(key); + if (commandHashSlot < 0) { + commandHashSlot = hashSlot; + } else if (commandHashSlot != hashSlot) { + throw new JedisClusterOperationException("Keys must belong to same hashslot."); + } + return this; + } +} diff --git a/src/main/java/redis/clients/jedis/ClusterCommandObjects.java b/src/main/java/redis/clients/jedis/ClusterCommandObjects.java new file mode 100644 index 0000000000..51d5a1c4c5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ClusterCommandObjects.java @@ -0,0 +1,210 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.Command.KEYS; +import static redis.clients.jedis.Protocol.Command.SCAN; +import static redis.clients.jedis.Protocol.Keyword.TYPE; + +import java.util.Set; + +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.util.JedisClusterHashTag; + +public class ClusterCommandObjects extends CommandObjects { + + @Override + protected ClusterCommandArguments commandArguments(ProtocolCommand command) { + return new ClusterCommandArguments(command); + } + + private static final String CLUSTER_UNSUPPORTED_MESSAGE = "Not supported in cluster mode."; + + @Override + public CommandObject dbSize() { + throw new UnsupportedOperationException(CLUSTER_UNSUPPORTED_MESSAGE); + } + + private static final String KEYS_PATTERN_MESSAGE = "Cluster mode only supports KEYS command" + + " with pattern containing hash-tag ( curly-brackets enclosed string )"; + + private static final String SCAN_PATTERN_MESSAGE = "Cluster mode only supports SCAN command" + + " with MATCH pattern containing hash-tag ( curly-brackets enclosed string )"; + + @Override + public final CommandObject> keys(String pattern) { + if (!JedisClusterHashTag.isClusterCompliantMatchPattern(pattern)) { + throw new IllegalArgumentException(KEYS_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(KEYS).key(pattern).processKey(pattern), BuilderFactory.STRING_SET); + } + + @Override + public final CommandObject> keys(byte[] pattern) { + if (!JedisClusterHashTag.isClusterCompliantMatchPattern(pattern)) { + throw new IllegalArgumentException(KEYS_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(KEYS).key(pattern).processKey(pattern), BuilderFactory.BINARY_SET); + } + + @Override + public final CommandObject> scan(String cursor) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + + @Override + public final CommandObject> scan(String cursor, ScanParams params) { + String match = params.match(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match), BuilderFactory.SCAN_RESPONSE); + } + + @Override + public final CommandObject> scan(String cursor, ScanParams params, String type) { + String match = params.match(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match).add(TYPE).add(type), BuilderFactory.SCAN_RESPONSE); + } + + @Override + public final CommandObject> scan(byte[] cursor) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + + @Override + public final CommandObject> scan(byte[] cursor, ScanParams params) { + byte[] match = params.binaryMatch(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + @Override + public final CommandObject> scan(byte[] cursor, ScanParams params, byte[] type) { + byte[] match = params.binaryMatch(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match).add(TYPE).add(type), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + @Override + public final CommandObject waitReplicas(int replicas, long timeout) { + throw new UnsupportedOperationException(CLUSTER_UNSUPPORTED_MESSAGE); + } +// +// boolean searchLite = false; +// +// private CommandObject processSearchCommand(String indexName, CommandObject command) { +// if (searchLite) command.getArguments().processKey(indexName); +// return command; +// } +// +// @Override +// public final CommandObject ftCreate(String indexName, IndexOptions indexOptions, Schema schema) { +// return processSearchCommand(indexName, super.ftCreate(indexName, indexOptions, schema)); +// } +// +// @Override +// public final CommandObject ftAlter(String indexName, Schema schema) { +// return processSearchCommand(indexName, super.ftAlter(indexName, schema)); +// } +// +// @Override +// public final CommandObject ftSearch(String indexName, Query query) { +// return processSearchCommand(indexName, super.ftSearch(indexName, query)); +// } +// +// @Override +// public final CommandObject ftSearch(byte[] indexName, Query query) { +// CommandObject command = super.ftSearch(indexName, query); +// if (searchLite) command.getArguments().processKey(indexName); +// return command; +// } +// +// @Override +// public CommandObject ftExplain(String indexName, Query query) { +// return processSearchCommand(indexName, super.ftExplain(indexName, query)); +// } +// +// @Override +// public CommandObject> ftExplainCLI(String indexName, Query query) { +// return processSearchCommand(indexName, super.ftExplainCLI(indexName, query)); +// } +// +// @Override +// public CommandObject ftAggregate(String indexName, AggregationBuilder aggr) { +// return processSearchCommand(indexName, super.ftAggregate(indexName, aggr)); +// } +// +// @Override +// public CommandObject ftCursorRead(String indexName, long cursorId, int count) { +// return processSearchCommand(indexName, super.ftCursorRead(indexName, cursorId, count)); +// } +// +// @Override +// public CommandObject ftCursorDel(String indexName, long cursorId) { +// return processSearchCommand(indexName, super.ftCursorDel(indexName, cursorId)); +// } +// +// @Override +// public CommandObject ftDropIndex(String indexName) { +// return processSearchCommand(indexName, super.ftDropIndex(indexName)); +// } +// +// @Override +// public CommandObject ftDropIndexDD(String indexName) { +// return processSearchCommand(indexName, super.ftDropIndexDD(indexName)); +// } +// +// @Override +// public CommandObject ftSynUpdate(String indexName, String synonymGroupId, String... terms) { +// return processSearchCommand(indexName, super.ftSynUpdate(indexName, synonymGroupId, terms)); +// } +// +// @Override +// public CommandObject>> ftSynDump(String indexName) { +// return processSearchCommand(indexName, super.ftSynDump(indexName)); +// } +// +// @Override +// public CommandObject> ftInfo(String indexName) { +// return processSearchCommand(indexName, super.ftInfo(indexName)); +// } +// +// @Override +// public CommandObject ftAliasAdd(String aliasName, String indexName) { +// CommandObject command = super.ftAliasAdd(aliasName, indexName); +// if (searchLite) command.getArguments().processKey(aliasName).processKey(indexName); +// return command; +// } +// +// @Override +// public CommandObject ftAliasUpdate(String aliasName, String indexName) { +// CommandObject command = super.ftAliasUpdate(aliasName, indexName); +// if (searchLite) command.getArguments().processKey(aliasName).processKey(indexName); +// return command; +// } +// +// @Override +// public CommandObject ftAliasDel(String aliasName) { +// CommandObject command = super.ftAliasDel(aliasName); +// if (searchLite) command.getArguments().processKey(aliasName); +// return command; +// } +// +// @Override +// public CommandObject> ftConfigGet(String indexName, String option) { +// return processSearchCommand(indexName, super.ftConfigGet(indexName, option)); +// } +// +// @Override +// public CommandObject ftConfigSet(String indexName, String option, String value) { +// return processSearchCommand(indexName, super.ftConfigSet(indexName, option, value)); +// } +} diff --git a/src/main/java/redis/clients/jedis/ClusterPipeline.java b/src/main/java/redis/clients/jedis/ClusterPipeline.java new file mode 100644 index 0000000000..0e72bcd033 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ClusterPipeline.java @@ -0,0 +1,23 @@ +package redis.clients.jedis; + +import redis.clients.jedis.providers.ClusterConnectionProvider; + +public class ClusterPipeline extends MultiNodePipelineBase { + + private final ClusterConnectionProvider provider; + + public ClusterPipeline(ClusterConnectionProvider provider) { + super(new ClusterCommandObjects()); + this.provider = provider; + } + + @Override + protected HostAndPort getNodeKey(CommandArguments args) { + return provider.getNode(((ClusterCommandArguments) args).getCommandHashSlot()); + } + + @Override + protected Connection getConnection(HostAndPort nodeKey) { + return provider.getConnection(nodeKey); + } +} diff --git a/src/main/java/redis/clients/jedis/ClusterReset.java b/src/main/java/redis/clients/jedis/ClusterReset.java deleted file mode 100644 index bfbc976443..0000000000 --- a/src/main/java/redis/clients/jedis/ClusterReset.java +++ /dev/null @@ -1,11 +0,0 @@ -package redis.clients.jedis; - -import redis.clients.jedis.args.ClusterResetType; - -/** - * @deprecated Use {@link ClusterResetType}. - */ -@Deprecated -public enum ClusterReset { - SOFT, HARD -} diff --git a/src/main/java/redis/clients/jedis/CommandArguments.java b/src/main/java/redis/clients/jedis/CommandArguments.java new file mode 100644 index 0000000000..8b125cd2b5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/CommandArguments.java @@ -0,0 +1,141 @@ +package redis.clients.jedis; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Iterator; +import redis.clients.jedis.args.Rawable; +import redis.clients.jedis.args.RawableFactory; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.params.IParams; + +public class CommandArguments implements Iterable { + + private final ArrayList args; + + private boolean blocking; + + private CommandArguments() { + throw new InstantiationError(); + } + + public CommandArguments(ProtocolCommand command) { + args = new ArrayList<>(); + args.add(command); + } + + public ProtocolCommand getCommand() { + return (ProtocolCommand) args.get(0); + } + + public CommandArguments add(Object arg) { + if (arg instanceof Rawable) { + args.add((Rawable) arg); + } else if (arg instanceof byte[]) { + args.add(RawableFactory.from((byte[]) arg)); + } else if (arg instanceof String) { + args.add(RawableFactory.from((String) arg)); + } else if (arg instanceof Boolean) { + args.add(RawableFactory.from(Integer.toString((Boolean) arg ? 1 : 0))); + } else { + if (arg == null) { + throw new IllegalArgumentException("null is not a valid argument."); + } + args.add(RawableFactory.from(String.valueOf(arg))); + } + return this; + } + + public CommandArguments addObjects(Object... args) { + for (Object arg : args) { + add(arg); + } + return this; + } + + public CommandArguments addObjects(Collection args) { + for (Object arg : args) { + add(arg); + } + return this; + } + + public CommandArguments addObjects(int[] ints) { + for (int i : ints) { + add(i); + } + return this; + } + + public CommandArguments key(Object key) { + if (key instanceof Rawable) { + Rawable raw = (Rawable) key; + processKey(raw.getRaw()); + args.add(raw); + } else if (key instanceof byte[]) { + byte[] raw = (byte[]) key; + processKey(raw); + args.add(RawableFactory.from(raw)); + } else if (key instanceof String) { + String raw = (String) key; + processKey(raw); + args.add(RawableFactory.from(raw)); + } else { + throw new IllegalArgumentException("\"" + key.toString() + "\" is not a valid argument."); + } + return this; + } + + public final CommandArguments keys(Object... keys) { + for (Object key : keys) { + key(key); + } + return this; + } + + public final CommandArguments addParams(IParams params) { + params.addParams(this); + return this; + } + + protected CommandArguments processKey(byte[] key) { + // do nothing + return this; + } + + protected final CommandArguments processKeys(byte[]... keys) { + for (byte[] key : keys) { + processKey(key); + } + return this; + } + + protected CommandArguments processKey(String key) { + // do nothing + return this; + } + + protected final CommandArguments processKeys(String... keys) { + for (String key : keys) { + processKey(key); + } + return this; + } + + public int size() { + return args.size(); + } + + @Override + public Iterator iterator() { + return args.iterator(); + } + + public boolean isBlocking() { + return blocking; + } + + public CommandArguments blocking() { + this.blocking = true; + return this; + } +} diff --git a/src/main/java/redis/clients/jedis/CommandObject.java b/src/main/java/redis/clients/jedis/CommandObject.java new file mode 100644 index 0000000000..b4931f2634 --- /dev/null +++ b/src/main/java/redis/clients/jedis/CommandObject.java @@ -0,0 +1,20 @@ +package redis.clients.jedis; + +public class CommandObject { + + private final CommandArguments arguments; + private final Builder builder; + + public CommandObject(CommandArguments args, Builder builder) { + this.arguments = args; + this.builder = builder; + } + + public CommandArguments getArguments() { + return arguments; + } + + public Builder getBuilder() { + return builder; + } +} diff --git a/src/main/java/redis/clients/jedis/CommandObjects.java b/src/main/java/redis/clients/jedis/CommandObjects.java new file mode 100644 index 0000000000..d55fabe336 --- /dev/null +++ b/src/main/java/redis/clients/jedis/CommandObjects.java @@ -0,0 +1,2852 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.Command.*; +import static redis.clients.jedis.Protocol.Keyword.*; + +import com.google.gson.Gson; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import org.json.JSONArray; +import org.json.JSONObject; + +import redis.clients.jedis.Protocol.Command; +import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.args.*; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.json.JsonProtocol.JsonCommand; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; +import redis.clients.jedis.search.*; +import redis.clients.jedis.search.SearchProtocol.SearchCommand; +import redis.clients.jedis.search.SearchProtocol.SearchKeyword; +import redis.clients.jedis.search.SearchResult.SearchResultBuilder; +import redis.clients.jedis.search.aggr.AggregationBuilder; +import redis.clients.jedis.search.aggr.AggregationResult; + +public class CommandObjects { + + protected CommandArguments commandArguments(ProtocolCommand command) { + return new CommandArguments(command); + } + + // Key commands + public final CommandObject exists(String key) { + return new CommandObject<>(commandArguments(Command.EXISTS).key(key), BuilderFactory.BOOLEAN); + } + + public final CommandObject exists(String... keys) { + return new CommandObject<>(commandArguments(Command.EXISTS).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject exists(byte[] key) { + return new CommandObject<>(commandArguments(Command.EXISTS).key(key), BuilderFactory.BOOLEAN); + } + + public final CommandObject exists(byte[]... keys) { + return new CommandObject<>(commandArguments(Command.EXISTS).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject persist(String key) { + return new CommandObject<>(commandArguments(PERSIST).key(key), BuilderFactory.LONG); + } + + public final CommandObject persist(byte[] key) { + return new CommandObject<>(commandArguments(PERSIST).key(key), BuilderFactory.LONG); + } + + public final CommandObject type(String key) { + return new CommandObject<>(commandArguments(Command.TYPE).key(key), BuilderFactory.STRING); + } + + public final CommandObject type(byte[] key) { + return new CommandObject<>(commandArguments(Command.TYPE).key(key), BuilderFactory.STRING); + } + + public final CommandObject dump(String key) { + return new CommandObject<>(commandArguments(DUMP).key(key), BuilderFactory.BINARY); + } + + public final CommandObject dump(byte[] key) { + return new CommandObject<>(commandArguments(DUMP).key(key), BuilderFactory.BINARY); + } + + public final CommandObject restore(String key, long ttl, byte[] serializedValue) { + return new CommandObject<>(commandArguments(RESTORE).key(key).add(ttl) + .add(serializedValue), BuilderFactory.STRING); + } + + public final CommandObject restore(String key, long ttl, byte[] serializedValue, RestoreParams params) { + return new CommandObject<>(commandArguments(RESTORE).key(key).add(ttl) + .add(serializedValue).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject restore(byte[] key, long ttl, byte[] serializedValue) { + return new CommandObject<>(commandArguments(RESTORE).key(key).add(ttl) + .add(serializedValue), BuilderFactory.STRING); + } + + public final CommandObject restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params) { + return new CommandObject<>(commandArguments(RESTORE).key(key).add(ttl) + .add(serializedValue).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject expire(String key, long seconds) { + return new CommandObject<>(commandArguments(EXPIRE).key(key).add(seconds), BuilderFactory.LONG); + } + + public final CommandObject expire(byte[] key, long seconds) { + return new CommandObject<>(commandArguments(EXPIRE).key(key).add(seconds), BuilderFactory.LONG); + } + + public final CommandObject pexpire(String key, long milliseconds) { + return new CommandObject<>(commandArguments(PEXPIRE).key(key).add(milliseconds), BuilderFactory.LONG); + } + + public final CommandObject pexpire(byte[] key, long milliseconds) { + return new CommandObject<>(commandArguments(PEXPIRE).key(key).add(milliseconds), BuilderFactory.LONG); + } + + public final CommandObject expireAt(String key, long unixTime) { + return new CommandObject<>(commandArguments(EXPIREAT).key(key).add(unixTime), BuilderFactory.LONG); + } + + public final CommandObject expireAt(byte[] key, long unixTime) { + return new CommandObject<>(commandArguments(EXPIREAT).key(key).add(unixTime), BuilderFactory.LONG); + } + + public final CommandObject pexpireAt(String key, long millisecondsTimestamp) { + return new CommandObject<>(commandArguments(PEXPIREAT).key(key).add(millisecondsTimestamp), BuilderFactory.LONG); + } + + public final CommandObject pexpireAt(byte[] key, long millisecondsTimestamp) { + return new CommandObject<>(commandArguments(PEXPIREAT).key(key).add(millisecondsTimestamp), BuilderFactory.LONG); + } + + public final CommandObject ttl(String key) { + return new CommandObject<>(commandArguments(TTL).key(key), BuilderFactory.LONG); + } + + public final CommandObject ttl(byte[] key) { + return new CommandObject<>(commandArguments(TTL).key(key), BuilderFactory.LONG); + } + + public final CommandObject pttl(String key) { + return new CommandObject<>(commandArguments(PTTL).key(key), BuilderFactory.LONG); + } + + public final CommandObject pttl(byte[] key) { + return new CommandObject<>(commandArguments(PTTL).key(key), BuilderFactory.LONG); + } + + public final CommandObject touch(String key) { + return new CommandObject<>(commandArguments(TOUCH).key(key), BuilderFactory.LONG); + } + + public final CommandObject touch(String... keys) { + return new CommandObject<>(commandArguments(TOUCH).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject touch(byte[] key) { + return new CommandObject<>(commandArguments(TOUCH).key(key), BuilderFactory.LONG); + } + + public final CommandObject touch(byte[]... keys) { + return new CommandObject<>(commandArguments(TOUCH).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> sort(String key) { + return new CommandObject<>(commandArguments(SORT).key(key), BuilderFactory.STRING_LIST); + } + + public final CommandObject> sort(String key, SortingParams sortingParameters) { + return new CommandObject<>(commandArguments(SORT).key(key).addParams(sortingParameters), BuilderFactory.STRING_LIST); + } + + public final CommandObject> sort(byte[] key) { + return new CommandObject<>(commandArguments(SORT).key(key), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> sort(byte[] key, SortingParams sortingParameters) { + return new CommandObject<>(commandArguments(SORT).key(key).addParams(sortingParameters), BuilderFactory.BINARY_LIST); + } + + public final CommandObject sort(String key, String dstkey) { + return new CommandObject<>(commandArguments(SORT).key(key) + .add(STORE).key(dstkey), BuilderFactory.LONG); + } + + public final CommandObject sort(String key, SortingParams sortingParameters, String dstkey) { + return new CommandObject<>(commandArguments(SORT).key(key).addParams(sortingParameters) + .add(STORE).key(dstkey), BuilderFactory.LONG); + } + + public final CommandObject sort(byte[] key, byte[] dstkey) { + return new CommandObject<>(commandArguments(SORT).key(key) + .add(STORE).key(dstkey), BuilderFactory.LONG); + } + + public final CommandObject sort(byte[] key, SortingParams sortingParameters, byte[] dstkey) { + return new CommandObject<>(commandArguments(SORT).key(key).addParams(sortingParameters) + .add(STORE).key(dstkey), BuilderFactory.LONG); + } + + public final CommandObject del(String key) { + return new CommandObject<>(commandArguments(DEL).key(key), BuilderFactory.LONG); + } + + public final CommandObject del(String... keys) { + return new CommandObject<>(commandArguments(DEL).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject del(byte[] key) { + return new CommandObject<>(commandArguments(DEL).key(key), BuilderFactory.LONG); + } + + public final CommandObject del(byte[]... keys) { + return new CommandObject<>(commandArguments(DEL).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject unlink(String key) { + return new CommandObject<>(commandArguments(UNLINK).key(key), BuilderFactory.LONG); + } + + public final CommandObject unlink(String... keys) { + return new CommandObject<>(commandArguments(UNLINK).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject unlink(byte[] key) { + return new CommandObject<>(commandArguments(UNLINK).key(key), BuilderFactory.LONG); + } + + public final CommandObject unlink(byte[]... keys) { + return new CommandObject<>(commandArguments(UNLINK).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject copy(String srcKey, String dstKey, boolean replace) { + CommandArguments args = commandArguments(Command.COPY).key(srcKey).key(dstKey); + if (replace) { + args.add(REPLACE); + } + return new CommandObject<>(args, BuilderFactory.BOOLEAN); + } + + public final CommandObject copy(byte[] srcKey, byte[] dstKey, boolean replace) { + CommandArguments args = commandArguments(Command.COPY).key(srcKey).key(dstKey); + if (replace) { + args.add(REPLACE); + } + return new CommandObject<>(args, BuilderFactory.BOOLEAN); + } + + public final CommandObject rename(String oldkey, String newkey) { + return new CommandObject<>(commandArguments(RENAME).key(oldkey).key(newkey), BuilderFactory.STRING); + } + + public final CommandObject renamenx(String oldkey, String newkey) { + return new CommandObject<>(commandArguments(RENAMENX).key(oldkey).key(newkey), BuilderFactory.LONG); + } + + public final CommandObject rename(byte[] oldkey, byte[] newkey) { + return new CommandObject<>(commandArguments(RENAME).key(oldkey).key(newkey), BuilderFactory.STRING); + } + + public final CommandObject renamenx(byte[] oldkey, byte[] newkey) { + return new CommandObject<>(commandArguments(RENAMENX).key(oldkey).key(newkey), BuilderFactory.LONG); + } + + public CommandObject dbSize() { + return new CommandObject<>(commandArguments(DBSIZE), BuilderFactory.LONG); + } + + public CommandObject> keys(String pattern) { + CommandArguments args = commandArguments(Command.KEYS).key(pattern); + return new CommandObject<>(args, BuilderFactory.STRING_SET); + } + + public CommandObject> keys(byte[] pattern) { + CommandArguments args = commandArguments(Command.KEYS).key(pattern); + return new CommandObject<>(args, BuilderFactory.BINARY_SET); + } + + public CommandObject> scan(String cursor) { + return new CommandObject<>(commandArguments(SCAN).add(cursor), BuilderFactory.SCAN_RESPONSE); + } + + public CommandObject> scan(String cursor, ScanParams params) { + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params), BuilderFactory.SCAN_RESPONSE); + } + + public CommandObject> scan(String cursor, ScanParams params, String type) { + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).add(Keyword.TYPE).add(type), BuilderFactory.SCAN_RESPONSE); + } + + public CommandObject> scan(byte[] cursor) { + return new CommandObject<>(commandArguments(SCAN).add(cursor), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + public CommandObject> scan(byte[] cursor, ScanParams params) { + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + public CommandObject> scan(byte[] cursor, ScanParams params, byte[] type) { + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).add(Keyword.TYPE).add(type), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + public final CommandObject randomKey() { + return new CommandObject<>(commandArguments(RANDOMKEY), BuilderFactory.STRING); + } + + public final CommandObject randomBinaryKey() { + return new CommandObject<>(commandArguments(RANDOMKEY), BuilderFactory.BINARY); + } + // Key commands + + // String commands + public final CommandObject set(String key, String value) { + return new CommandObject<>(commandArguments(Command.SET).key(key).add(value), BuilderFactory.STRING); + } + + public final CommandObject set(String key, String value, SetParams params) { + return new CommandObject<>(commandArguments(Command.SET).key(key).add(value).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject set(byte[] key, byte[] value) { + return new CommandObject<>(commandArguments(Command.SET).key(key).add(value), BuilderFactory.STRING); + } + + public final CommandObject set(byte[] key, byte[] value, SetParams params) { + return new CommandObject<>(commandArguments(Command.SET).key(key).add(value).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject get(String key) { + return new CommandObject<>(commandArguments(Command.GET).key(key), BuilderFactory.STRING); + } + + public final CommandObject getDel(String key) { + return new CommandObject<>(commandArguments(Command.GETDEL).key(key), BuilderFactory.STRING); + } + + public final CommandObject getEx(String key, GetExParams params) { + return new CommandObject<>(commandArguments(Command.GETEX).key(key).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject get(byte[] key) { + return new CommandObject<>(commandArguments(Command.GET).key(key), BuilderFactory.BINARY); + } + + public final CommandObject getDel(byte[] key) { + return new CommandObject<>(commandArguments(Command.GETDEL).key(key), BuilderFactory.BINARY); + } + + public final CommandObject getEx(byte[] key, GetExParams params) { + return new CommandObject<>(commandArguments(Command.GETEX).key(key).addParams(params), BuilderFactory.BINARY); + } + + public final CommandObject getSet(String key, String value) { + return new CommandObject<>(commandArguments(Command.GETSET).key(key).add(value), BuilderFactory.STRING); + } + + public final CommandObject getSet(byte[] key, byte[] value) { + return new CommandObject<>(commandArguments(Command.GETSET).key(key).add(value), BuilderFactory.BINARY); + } + + public final CommandObject setnx(String key, String value) { + return new CommandObject<>(commandArguments(SETNX).key(key).add(value), BuilderFactory.LONG); + } + + public final CommandObject setex(String key, long seconds, String value) { + return new CommandObject<>(commandArguments(SETEX).key(key).add(seconds).add(value), BuilderFactory.STRING); + } + + public final CommandObject psetex(String key, long milliseconds, String value) { + return new CommandObject<>(commandArguments(PSETEX).key(key).add(milliseconds).add(value), BuilderFactory.STRING); + } + + public final CommandObject setnx(byte[] key, byte[] value) { + return new CommandObject<>(commandArguments(SETNX).key(key).add(value), BuilderFactory.LONG); + } + + public final CommandObject setex(byte[] key, long seconds, byte[] value) { + return new CommandObject<>(commandArguments(SETEX).key(key).add(seconds).add(value), BuilderFactory.STRING); + } + + public final CommandObject psetex(byte[] key, long milliseconds, byte[] value) { + return new CommandObject<>(commandArguments(PSETEX).key(key).add(milliseconds).add(value), BuilderFactory.STRING); + } + + public final CommandObject setbit(String key, long offset, boolean value) { + return new CommandObject<>(commandArguments(SETBIT).key(key).add(offset).add(value), BuilderFactory.BOOLEAN); + } + + public final CommandObject setbit(byte[] key, long offset, boolean value) { + return new CommandObject<>(commandArguments(SETBIT).key(key).add(offset).add(value), BuilderFactory.BOOLEAN); + } + + public final CommandObject getbit(String key, long offset) { + return new CommandObject<>(commandArguments(GETBIT).key(key).add(offset), BuilderFactory.BOOLEAN); + } + + public final CommandObject getbit(byte[] key, long offset) { + return new CommandObject<>(commandArguments(GETBIT).key(key).add(offset), BuilderFactory.BOOLEAN); + } + + public final CommandObject setrange(String key, long offset, String value) { + return new CommandObject<>(commandArguments(SETRANGE).key(key).add(offset).add(value), BuilderFactory.LONG); + } + + public final CommandObject setrange(byte[] key, long offset, byte[] value) { + return new CommandObject<>(commandArguments(SETRANGE).key(key).add(offset).add(value), BuilderFactory.LONG); + } + + public final CommandObject getrange(String key, long startOffset, long endOffset) { + return new CommandObject<>(commandArguments(GETRANGE).key(key).add(startOffset).add(endOffset), BuilderFactory.STRING); + } + + public final CommandObject getrange(byte[] key, long startOffset, long endOffset) { + return new CommandObject<>(commandArguments(GETRANGE).key(key).add(startOffset).add(endOffset), BuilderFactory.BINARY); + } + + public final CommandObject> mget(String... keys) { + return new CommandObject<>(commandArguments(MGET).keys((Object[]) keys), BuilderFactory.STRING_LIST); + } + + public final CommandObject> mget(byte[]... keys) { + return new CommandObject<>(commandArguments(MGET).keys((Object[]) keys), BuilderFactory.BINARY_LIST); + } + + public final CommandObject mset(String... keysvalues) { + return new CommandObject<>(addFlatKeyValueArgs(commandArguments(MSET), keysvalues), BuilderFactory.STRING); + } + + public final CommandObject msetnx(String... keysvalues) { + return new CommandObject<>(addFlatKeyValueArgs(commandArguments(MSETNX), keysvalues), BuilderFactory.LONG); + } + + public final CommandObject mset(byte[]... keysvalues) { + return new CommandObject<>(addFlatKeyValueArgs(commandArguments(MSET), keysvalues), BuilderFactory.STRING); + } + + public final CommandObject msetnx(byte[]... keysvalues) { + return new CommandObject<>(addFlatKeyValueArgs(commandArguments(MSETNX), keysvalues), BuilderFactory.LONG); + } + + public final CommandObject incr(String key) { + return new CommandObject<>(commandArguments(Command.INCR).key(key), BuilderFactory.LONG); + } + + public final CommandObject incrBy(String key, long increment) { + return new CommandObject<>(commandArguments(INCRBY).key(key).add(increment), BuilderFactory.LONG); + } + + public final CommandObject incrByFloat(String key, double increment) { + return new CommandObject<>(commandArguments(INCRBYFLOAT).key(key).add(increment), BuilderFactory.DOUBLE); + } + + public final CommandObject incr(byte[] key) { + return new CommandObject<>(commandArguments(Command.INCR).key(key), BuilderFactory.LONG); + } + + public final CommandObject incrBy(byte[] key, long increment) { + return new CommandObject<>(commandArguments(INCRBY).key(key).add(increment), BuilderFactory.LONG); + } + + public final CommandObject incrByFloat(byte[] key, double increment) { + return new CommandObject<>(commandArguments(INCRBYFLOAT).key(key).add(increment), BuilderFactory.DOUBLE); + } + + public final CommandObject decr(String key) { + return new CommandObject<>(commandArguments(DECR).key(key), BuilderFactory.LONG); + } + + public final CommandObject decrBy(String key, long decrement) { + return new CommandObject<>(commandArguments(DECRBY).key(key).add(decrement), BuilderFactory.LONG); + } + + public final CommandObject decr(byte[] key) { + return new CommandObject<>(commandArguments(DECR).key(key), BuilderFactory.LONG); + } + + public final CommandObject decrBy(byte[] key, long decrement) { + return new CommandObject<>(commandArguments(DECRBY).key(key).add(decrement), BuilderFactory.LONG); + } + + public final CommandObject append(String key, String value) { + return new CommandObject<>(commandArguments(APPEND).key(key).add(value), BuilderFactory.LONG); + } + + public final CommandObject append(byte[] key, byte[] value) { + return new CommandObject<>(commandArguments(APPEND).key(key).add(value), BuilderFactory.LONG); + } + + public final CommandObject substr(String key, int start, int end) { + return new CommandObject<>(commandArguments(SUBSTR).key(key).add(start).add(end), BuilderFactory.STRING); + } + + public final CommandObject substr(byte[] key, int start, int end) { + return new CommandObject<>(commandArguments(SUBSTR).key(key).add(start).add(end), BuilderFactory.BINARY); + } + + public final CommandObject strlen(String key) { + return new CommandObject<>(commandArguments(STRLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject strlen(byte[] key) { + return new CommandObject<>(commandArguments(STRLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject bitcount(String key) { + return new CommandObject<>(commandArguments(BITCOUNT).key(key), BuilderFactory.LONG); + } + + public final CommandObject bitcount(String key, long start, long end) { + return new CommandObject<>(commandArguments(BITCOUNT).key(key).add(start).add(end), BuilderFactory.LONG); + } + + public final CommandObject bitcount(byte[] key) { + return new CommandObject<>(commandArguments(BITCOUNT).key(key), BuilderFactory.LONG); + } + + public final CommandObject bitcount(byte[] key, long start, long end) { + return new CommandObject<>(commandArguments(BITCOUNT).key(key).add(start).add(end), BuilderFactory.LONG); + } + + public final CommandObject bitpos(String key, boolean value) { + return new CommandObject<>(commandArguments(BITPOS).key(key).add(value ? 1 : 0), BuilderFactory.LONG); + } + + public final CommandObject bitpos(String key, boolean value, BitPosParams params) { + return new CommandObject<>(commandArguments(BITPOS).key(key).add(value ? 1 : 0).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject bitpos(byte[] key, boolean value) { + return new CommandObject<>(commandArguments(BITPOS).key(key).add(value ? 1 : 0), BuilderFactory.LONG); + } + + public final CommandObject bitpos(byte[] key, boolean value, BitPosParams params) { + return new CommandObject<>(commandArguments(BITPOS).key(key).add(value ? 1 : 0).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> bitfield(String key, String... arguments) { + return new CommandObject<>(commandArguments(BITFIELD).key(key).addObjects((Object[]) arguments), BuilderFactory.LONG_LIST); + } + + public final CommandObject> bitfieldReadonly(String key, String... arguments) { + return new CommandObject<>(commandArguments(BITFIELD_RO).key(key).addObjects((Object[]) arguments), BuilderFactory.LONG_LIST); + } + + public final CommandObject> bitfield(byte[] key, byte[]... arguments) { + return new CommandObject<>(commandArguments(BITFIELD).key(key).addObjects((Object[]) arguments), BuilderFactory.LONG_LIST); + } + + public final CommandObject> bitfieldReadonly(byte[] key, byte[]... arguments) { + return new CommandObject<>(commandArguments(BITFIELD_RO).key(key).addObjects((Object[]) arguments), BuilderFactory.LONG_LIST); + } + + public final CommandObject bitop(BitOP op, String destKey, String... srcKeys) { + return new CommandObject<>(commandArguments(BITOP).add(op).key(destKey).keys((Object[]) srcKeys), BuilderFactory.LONG); + } + + public final CommandObject bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { + return new CommandObject<>(commandArguments(BITOP).add(op).key(destKey).keys((Object[]) srcKeys), BuilderFactory.LONG); + } + + public final CommandObject strAlgoLCSKeys(String keyA, String keyB, StrAlgoLCSParams params) { + return new CommandObject<>(commandArguments(STRALGO).add(LCS).add(Keyword.KEYS) + .key(keyA).key(keyB).addParams(params), BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); + } + + public final CommandObject strAlgoLCSKeys(byte[] keyA, byte[] keyB, StrAlgoLCSParams params) { + return new CommandObject<>(commandArguments(STRALGO).add(LCS).add(Keyword.KEYS) + .key(keyA).key(keyB).addParams(params), BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); + } + // String commands + + // List commands + public final CommandObject rpush(String key, String... strings) { + return new CommandObject<>(commandArguments(RPUSH).key(key).addObjects((Object[]) strings), BuilderFactory.LONG); + } + + public final CommandObject rpush(byte[] key, byte[]... strings) { + return new CommandObject<>(commandArguments(RPUSH).key(key).addObjects((Object[]) strings), BuilderFactory.LONG); + } + + public final CommandObject lpush(String key, String... strings) { + return new CommandObject<>(commandArguments(LPUSH).key(key).addObjects((Object[]) strings), BuilderFactory.LONG); + } + + public final CommandObject lpush(byte[] key, byte[]... strings) { + return new CommandObject<>(commandArguments(LPUSH).key(key).addObjects((Object[]) strings), BuilderFactory.LONG); + } + + public final CommandObject llen(String key) { + return new CommandObject<>(commandArguments(LLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject llen(byte[] key) { + return new CommandObject<>(commandArguments(LLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject> lrange(String key, long start, long stop) { + return new CommandObject<>(commandArguments(LRANGE).key(key).add(start).add(stop), BuilderFactory.STRING_LIST); + } + + public final CommandObject> lrange(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(LRANGE).key(key).add(start).add(stop), BuilderFactory.BINARY_LIST); + } + + public final CommandObject ltrim(String key, long start, long stop) { + return new CommandObject<>(commandArguments(LTRIM).key(key).add(start).add(stop), BuilderFactory.STRING); + } + + public final CommandObject ltrim(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(LTRIM).key(key).add(start).add(stop), BuilderFactory.STRING); + } + + public final CommandObject lindex(String key, long index) { + return new CommandObject<>(commandArguments(LINDEX).key(key).add(index), BuilderFactory.STRING); + } + + public final CommandObject lindex(byte[] key, long index) { + return new CommandObject<>(commandArguments(LINDEX).key(key).add(index), BuilderFactory.BINARY); + } + + public final CommandObject lset(String key, long index, String value) { + return new CommandObject<>(commandArguments(LSET).key(key).add(index).add(value), BuilderFactory.STRING); + } + + public final CommandObject lset(byte[] key, long index, byte[] value) { + return new CommandObject<>(commandArguments(LSET).key(key).add(index).add(value), BuilderFactory.STRING); + } + + public final CommandObject lrem(String key, long count, String value) { + return new CommandObject<>(commandArguments(LREM).key(key).add(count).add(value), BuilderFactory.LONG); + } + + public final CommandObject lrem(byte[] key, long count, byte[] value) { + return new CommandObject<>(commandArguments(LREM).key(key).add(count).add(value), BuilderFactory.LONG); + } + + public final CommandObject lpop(String key) { + return new CommandObject<>(commandArguments(LPOP).key(key), BuilderFactory.STRING); + } + + public final CommandObject> lpop(String key, int count) { + return new CommandObject<>(commandArguments(LPOP).key(key).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject lpop(byte[] key) { + return new CommandObject<>(commandArguments(LPOP).key(key), BuilderFactory.BINARY); + } + + public final CommandObject> lpop(byte[] key, int count) { + return new CommandObject<>(commandArguments(LPOP).key(key).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject rpop(String key) { + return new CommandObject<>(commandArguments(RPOP).key(key), BuilderFactory.STRING); + } + + public final CommandObject> rpop(String key, int count) { + return new CommandObject<>(commandArguments(RPOP).key(key).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject rpop(byte[] key) { + return new CommandObject<>(commandArguments(RPOP).key(key), BuilderFactory.BINARY); + } + + public final CommandObject> rpop(byte[] key, int count) { + return new CommandObject<>(commandArguments(RPOP).key(key).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject lpos(String key, String element) { + return new CommandObject<>(commandArguments(LPOS).key(key).add(element), BuilderFactory.LONG); + } + + public final CommandObject lpos(String key, String element, LPosParams params) { + return new CommandObject<>(commandArguments(LPOS).key(key).add(element).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> lpos(String key, String element, LPosParams params, long count) { + return new CommandObject<>(commandArguments(LPOS).key(key).add(element) + .addParams(params).add(COUNT).add(count), BuilderFactory.LONG_LIST); + } + + public final CommandObject lpos(byte[] key, byte[] element) { + return new CommandObject<>(commandArguments(LPOS).key(key).add(element), BuilderFactory.LONG); + } + + public final CommandObject lpos(byte[] key, byte[] element, LPosParams params) { + return new CommandObject<>(commandArguments(LPOS).key(key).add(element).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> lpos(byte[] key, byte[] element, LPosParams params, long count) { + return new CommandObject<>(commandArguments(LPOS).key(key).add(element) + .addParams(params).add(COUNT).add(count), BuilderFactory.LONG_LIST); + } + + public final CommandObject linsert(String key, ListPosition where, String pivot, String value) { + return new CommandObject<>(commandArguments(LINSERT).key(key).add(where) + .add(pivot).add(value), BuilderFactory.LONG); + } + + public final CommandObject linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value) { + return new CommandObject<>(commandArguments(LINSERT).key(key).add(where) + .add(pivot).add(value), BuilderFactory.LONG); + } + + public final CommandObject lpushx(String key, String... string) { + return new CommandObject<>(commandArguments(LPUSHX).key(key).addObjects((Object[]) string), BuilderFactory.LONG); + } + + public final CommandObject rpushx(String key, String... string) { + return new CommandObject<>(commandArguments(RPUSHX).key(key).addObjects((Object[]) string), BuilderFactory.LONG); + } + + public final CommandObject lpushx(byte[] key, byte[]... arg) { + return new CommandObject<>(commandArguments(LPUSHX).key(key).addObjects((Object[]) arg), BuilderFactory.LONG); + } + + public final CommandObject rpushx(byte[] key, byte[]... arg) { + return new CommandObject<>(commandArguments(RPUSHX).key(key).addObjects((Object[]) arg), BuilderFactory.LONG); + } + + public final CommandObject> blpop(int timeout, String key) { + return new CommandObject<>(commandArguments(BLPOP).blocking().key(key).add(timeout), BuilderFactory.STRING_LIST); + } + + public final CommandObject> blpop(int timeout, String... keys) { + return new CommandObject<>(commandArguments(BLPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.STRING_LIST); + } + + public final CommandObject blpop(double timeout, String key) { + return new CommandObject<>(commandArguments(BLPOP).blocking().key(key).add(timeout), BuilderFactory.KEYED_LIST_ELEMENT); + } + + public final CommandObject blpop(double timeout, String... keys) { + return new CommandObject<>(commandArguments(BLPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.KEYED_LIST_ELEMENT); + } + + public final CommandObject> blpop(int timeout, byte[]... keys) { + return new CommandObject<>(commandArguments(BLPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> blpop(double timeout, byte[]... keys) { + return new CommandObject<>(commandArguments(BLPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> brpop(int timeout, String key) { + return new CommandObject<>(commandArguments(BRPOP).blocking().key(key).add(timeout), BuilderFactory.STRING_LIST); + } + + public final CommandObject> brpop(int timeout, String... keys) { + return new CommandObject<>(commandArguments(BRPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.STRING_LIST); + } + + public final CommandObject brpop(double timeout, String key) { + return new CommandObject<>(commandArguments(BRPOP).blocking().key(key).add(timeout), BuilderFactory.KEYED_LIST_ELEMENT); + } + + public final CommandObject brpop(double timeout, String... keys) { + return new CommandObject<>(commandArguments(BRPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.KEYED_LIST_ELEMENT); + } + + public final CommandObject> brpop(int timeout, byte[]... keys) { + return new CommandObject<>(commandArguments(BRPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> brpop(double timeout, byte[]... keys) { + return new CommandObject<>(commandArguments(BRPOP).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.BINARY_LIST); + } + + public final CommandObject rpoplpush(String srckey, String dstkey) { + return new CommandObject<>(commandArguments(RPOPLPUSH).key(srckey).key(dstkey), BuilderFactory.STRING); + } + + public final CommandObject brpoplpush(String source, String destination, int timeout) { + return new CommandObject<>(commandArguments(BRPOPLPUSH).blocking().key(source) + .key(destination).add(timeout), BuilderFactory.STRING); + } + + public final CommandObject rpoplpush(byte[] srckey, byte[] dstkey) { + return new CommandObject<>(commandArguments(RPOPLPUSH).key(srckey).key(dstkey), BuilderFactory.BINARY); + } + + public final CommandObject brpoplpush(byte[] source, byte[] destination, int timeout) { + return new CommandObject<>(commandArguments(BRPOPLPUSH).blocking().key(source) + .key(destination).add(timeout), BuilderFactory.BINARY); + } + + public final CommandObject lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { + return new CommandObject<>(commandArguments(LMOVE).key(srcKey).key(dstKey) + .add(from).add(to), BuilderFactory.STRING); + } + + public final CommandObject blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout) { + return new CommandObject<>(commandArguments(BLMOVE).blocking().key(srcKey) + .key(dstKey).add(from).add(to).add(timeout), BuilderFactory.STRING); + } + + public final CommandObject lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { + return new CommandObject<>(commandArguments(LMOVE).key(srcKey).key(dstKey) + .add(from).add(to), BuilderFactory.BINARY); + } + + public final CommandObject blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { + return new CommandObject<>(commandArguments(BLMOVE).blocking().key(srcKey) + .key(dstKey).add(from).add(to).add(timeout), BuilderFactory.BINARY); + } + // List commands + + // Hash commands + public final CommandObject hset(String key, String field, String value) { + return new CommandObject<>(commandArguments(HSET).key(key).add(field).add(value), BuilderFactory.LONG); + } + + public final CommandObject hset(String key, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(HSET).key(key), hash), BuilderFactory.LONG); + } + + public final CommandObject hget(String key, String field) { + return new CommandObject<>(commandArguments(HGET).key(key).add(field), BuilderFactory.STRING); + } + + public final CommandObject hsetnx(String key, String field, String value) { + return new CommandObject<>(commandArguments(HSETNX).key(key).add(field).add(value), BuilderFactory.LONG); + } + + public final CommandObject hmset(String key, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(HMSET).key(key), hash), BuilderFactory.STRING); + } + + public final CommandObject> hmget(String key, String... fields) { + return new CommandObject<>(commandArguments(HMGET).key(key).addObjects((Object[]) fields), BuilderFactory.STRING_LIST); + } + + public final CommandObject hset(byte[] key, byte[] field, byte[] value) { + return new CommandObject<>(commandArguments(HSET).key(key).add(field).add(value), BuilderFactory.LONG); + } + + public final CommandObject hset(byte[] key, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(HSET).key(key), hash), BuilderFactory.LONG); + } + + public final CommandObject hget(byte[] key, byte[] field) { + return new CommandObject<>(commandArguments(HGET).key(key).add(field), BuilderFactory.BINARY); + } + + public final CommandObject hsetnx(byte[] key, byte[] field, byte[] value) { + return new CommandObject<>(commandArguments(HSETNX).key(key).add(field).add(value), BuilderFactory.LONG); + } + + public final CommandObject hmset(byte[] key, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(HMSET).key(key), hash), BuilderFactory.STRING); + } + + public final CommandObject> hmget(byte[] key, byte[]... fields) { + return new CommandObject<>(commandArguments(HMGET).key(key).addObjects((Object[]) fields), BuilderFactory.BINARY_LIST); + } + + public final CommandObject hincrBy(String key, String field, long value) { + return new CommandObject<>(commandArguments(HINCRBY).key(key).add(field).add(value), BuilderFactory.LONG); + } + + public final CommandObject hincrByFloat(String key, String field, double value) { + return new CommandObject<>(commandArguments(HINCRBYFLOAT).key(key).add(field).add(value), BuilderFactory.DOUBLE); + } + + public final CommandObject hexists(String key, String field) { + return new CommandObject<>(commandArguments(HEXISTS).key(key).add(field), BuilderFactory.BOOLEAN); + } + + public final CommandObject hdel(String key, String... field) { + return new CommandObject<>(commandArguments(HDEL).key(key).addObjects((Object[]) field), BuilderFactory.LONG); + } + + public final CommandObject hlen(String key) { + return new CommandObject<>(commandArguments(HLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject hincrBy(byte[] key, byte[] field, long value) { + return new CommandObject<>(commandArguments(HINCRBY).key(key).add(field).add(value), BuilderFactory.LONG); + } + + public final CommandObject hincrByFloat(byte[] key, byte[] field, double value) { + return new CommandObject<>(commandArguments(HINCRBYFLOAT).key(key).add(field).add(value), BuilderFactory.DOUBLE); + } + + public final CommandObject hexists(byte[] key, byte[] field) { + return new CommandObject<>(commandArguments(HEXISTS).key(key).add(field), BuilderFactory.BOOLEAN); + } + + public final CommandObject hdel(byte[] key, byte[]... field) { + return new CommandObject<>(commandArguments(HDEL).key(key).addObjects((Object[]) field), BuilderFactory.LONG); + } + + public final CommandObject hlen(byte[] key) { + return new CommandObject<>(commandArguments(HLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject> hkeys(String key) { + return new CommandObject<>(commandArguments(HKEYS).key(key), BuilderFactory.STRING_SET); + } + + public final CommandObject> hvals(String key) { + return new CommandObject<>(commandArguments(HVALS).key(key), BuilderFactory.STRING_LIST); + } + + public final CommandObject> hkeys(byte[] key) { + return new CommandObject<>(commandArguments(HKEYS).key(key), BuilderFactory.BINARY_SET); + } + + public final CommandObject> hvals(byte[] key) { + return new CommandObject<>(commandArguments(HVALS).key(key), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> hgetAll(String key) { + return new CommandObject<>(commandArguments(HGETALL).key(key), BuilderFactory.STRING_MAP); + } + + public final CommandObject hrandfield(String key) { + return new CommandObject<>(commandArguments(HRANDFIELD).key(key), BuilderFactory.STRING); + } + + public final CommandObject> hrandfield(String key, long count) { + return new CommandObject<>(commandArguments(HRANDFIELD).key(key).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> hrandfieldWithValues(String key, long count) { + return new CommandObject<>(commandArguments(HRANDFIELD).key(key).add(count).add(WITHVALUES), BuilderFactory.STRING_MAP); + } + + public final CommandObject> hgetAll(byte[] key) { + return new CommandObject<>(commandArguments(HGETALL).key(key), BuilderFactory.BINARY_MAP); + } + + public final CommandObject hrandfield(byte[] key) { + return new CommandObject<>(commandArguments(HRANDFIELD).key(key), BuilderFactory.BINARY); + } + + public final CommandObject> hrandfield(byte[] key, long count) { + return new CommandObject<>(commandArguments(HRANDFIELD).key(key).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> hrandfieldWithValues(byte[] key, long count) { + return new CommandObject<>(commandArguments(HRANDFIELD).key(key).add(count).add(WITHVALUES), BuilderFactory.BINARY_MAP); + } + + public final CommandObject>> hscan(String key, String cursor, ScanParams params) { + return new CommandObject<>(commandArguments(HSCAN).key(key).add(cursor).addParams(params), BuilderFactory.HSCAN_RESPONSE); + } + + public final CommandObject hstrlen(String key, String field) { + return new CommandObject<>(commandArguments(HSTRLEN).key(key).add(field), BuilderFactory.LONG); + } + + public final CommandObject>> hscan(byte[] key, byte[] cursor, ScanParams params) { + return new CommandObject<>(commandArguments(HSCAN).key(key).add(cursor).addParams(params), BuilderFactory.HSCAN_BINARY_RESPONSE); + } + + public final CommandObject hstrlen(byte[] key, byte[] field) { + return new CommandObject<>(commandArguments(HSTRLEN).key(key).add(field), BuilderFactory.LONG); + } + // Hash commands + + // Set commands + public final CommandObject sadd(String key, String... members) { + return new CommandObject<>(commandArguments(SADD).key(key).addObjects((Object[]) members), BuilderFactory.LONG); + } + + public final CommandObject sadd(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(SADD).key(key).addObjects((Object[]) members), BuilderFactory.LONG); + } + + public final CommandObject> smembers(String key) { + return new CommandObject<>(commandArguments(SMEMBERS).key(key), BuilderFactory.STRING_SET); + } + + public final CommandObject> smembers(byte[] key) { + return new CommandObject<>(commandArguments(SMEMBERS).key(key), BuilderFactory.BINARY_SET); + } + + public final CommandObject srem(String key, String... members) { + return new CommandObject<>(commandArguments(SREM).key(key).addObjects((Object[]) members), BuilderFactory.LONG); + } + + public final CommandObject srem(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(SREM).key(key).addObjects((Object[]) members), BuilderFactory.LONG); + } + + public final CommandObject spop(String key) { + return new CommandObject<>(commandArguments(SPOP).key(key), BuilderFactory.STRING); + } + + public final CommandObject spop(byte[] key) { + return new CommandObject<>(commandArguments(SPOP).key(key), BuilderFactory.BINARY); + } + + public final CommandObject> spop(String key, long count) { + return new CommandObject<>(commandArguments(SPOP).key(key).add(count), BuilderFactory.STRING_SET); + } + + public final CommandObject> spop(byte[] key, long count) { + return new CommandObject<>(commandArguments(SPOP).key(key).add(count), BuilderFactory.BINARY_SET); + } + + public final CommandObject scard(String key) { + return new CommandObject<>(commandArguments(SCARD).key(key), BuilderFactory.LONG); + } + + public final CommandObject scard(byte[] key) { + return new CommandObject<>(commandArguments(SCARD).key(key), BuilderFactory.LONG); + } + + public final CommandObject sismember(String key, String member) { + return new CommandObject<>(commandArguments(SISMEMBER).key(key).add(member), BuilderFactory.BOOLEAN); + } + + public final CommandObject sismember(byte[] key, byte[] member) { + return new CommandObject<>(commandArguments(SISMEMBER).key(key).add(member), BuilderFactory.BOOLEAN); + } + + public final CommandObject> smismember(String key, String... members) { + return new CommandObject<>(commandArguments(SMISMEMBER).key(key).addObjects((Object[]) members), BuilderFactory.BOOLEAN_LIST); + } + + public final CommandObject> smismember(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(SMISMEMBER).key(key).addObjects((Object[]) members), BuilderFactory.BOOLEAN_LIST); + } + + public final CommandObject srandmember(String key) { + return new CommandObject<>(commandArguments(SRANDMEMBER).key(key), BuilderFactory.STRING); + } + + public final CommandObject srandmember(byte[] key) { + return new CommandObject<>(commandArguments(SRANDMEMBER).key(key), BuilderFactory.BINARY); + } + + public final CommandObject> srandmember(String key, int count) { + return new CommandObject<>(commandArguments(SRANDMEMBER).key(key).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> srandmember(byte[] key, int count) { + return new CommandObject<>(commandArguments(SRANDMEMBER).key(key).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> sscan(String key, String cursor, ScanParams params) { + return new CommandObject<>(commandArguments(SSCAN).key(key).add(cursor).addParams(params), BuilderFactory.SSCAN_RESPONSE); + } + + public final CommandObject> sscan(byte[] key, byte[] cursor, ScanParams params) { + return new CommandObject<>(commandArguments(SSCAN).key(key).add(cursor).addParams(params), BuilderFactory.SSCAN_BINARY_RESPONSE); + } + + public final CommandObject> sdiff(String... keys) { + return new CommandObject<>(commandArguments(SDIFF).keys((Object[]) keys), BuilderFactory.STRING_SET); + } + + public final CommandObject sdiffstore(String dstkey, String... keys) { + return new CommandObject<>(commandArguments(SDIFFSTORE).key(dstkey).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> sdiff(byte[]... keys) { + return new CommandObject<>(commandArguments(SDIFF).keys((Object[]) keys), BuilderFactory.BINARY_SET); + } + + public final CommandObject sdiffstore(byte[] dstkey, byte[]... keys) { + return new CommandObject<>(commandArguments(SDIFFSTORE).key(dstkey).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> sinter(String... keys) { + return new CommandObject<>(commandArguments(SINTER).keys((Object[]) keys), BuilderFactory.STRING_SET); + } + + public final CommandObject sinterstore(String dstkey, String... keys) { + return new CommandObject<>(commandArguments(SINTERSTORE).key(dstkey).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> sinter(byte[]... keys) { + return new CommandObject<>(commandArguments(SINTER).keys((Object[]) keys), BuilderFactory.BINARY_SET); + } + + public final CommandObject sinterstore(byte[] dstkey, byte[]... keys) { + return new CommandObject<>(commandArguments(SINTERSTORE).key(dstkey).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> sunion(String... keys) { + return new CommandObject<>(commandArguments(SUNION).keys((Object[]) keys), BuilderFactory.STRING_SET); + } + + public final CommandObject sunionstore(String dstkey, String... keys) { + return new CommandObject<>(commandArguments(SUNIONSTORE).key(dstkey).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> sunion(byte[]... keys) { + return new CommandObject<>(commandArguments(SUNION).keys((Object[]) keys), BuilderFactory.BINARY_SET); + } + + public final CommandObject sunionstore(byte[] dstkey, byte[]... keys) { + return new CommandObject<>(commandArguments(SUNIONSTORE).key(dstkey).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject smove(String srckey, String dstkey, String member) { + return new CommandObject<>(commandArguments(SMOVE).key(srckey).key(dstkey).add(member), BuilderFactory.LONG); + } + + public final CommandObject smove(byte[] srckey, byte[] dstkey, byte[] member) { + return new CommandObject<>(commandArguments(SMOVE).key(srckey).key(dstkey).add(member), BuilderFactory.LONG); + } + // Set commands + + // Sorted Set commands + public final CommandObject zadd(String key, double score, String member) { + return new CommandObject<>(commandArguments(ZADD).key(key).add(score).add(member), BuilderFactory.LONG); + } + + public final CommandObject zadd(String key, double score, String member, ZAddParams params) { + return new CommandObject<>(commandArguments(ZADD).key(key).addParams(params) + .add(score).add(member), BuilderFactory.LONG); + } + + public final CommandObject zadd(String key, Map scoreMembers) { + return new CommandObject<>(addSortedSetFlatMapArgs(commandArguments(ZADD).key(key), scoreMembers), BuilderFactory.LONG); + } + + public final CommandObject zadd(String key, Map scoreMembers, ZAddParams params) { + return new CommandObject<>(addSortedSetFlatMapArgs(commandArguments(ZADD).key(key).addParams(params), scoreMembers), BuilderFactory.LONG); + } + + public final CommandObject zaddIncr(String key, double score, String member, ZAddParams params) { + return new CommandObject<>(commandArguments(ZADD).key(key).add(Keyword.INCR) + .addParams(params).add(score).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject zadd(byte[] key, double score, byte[] member) { + return new CommandObject<>(commandArguments(ZADD).key(key).add(score).add(member), BuilderFactory.LONG); + } + + public final CommandObject zadd(byte[] key, double score, byte[] member, ZAddParams params) { + return new CommandObject<>(commandArguments(ZADD).key(key).addParams(params) + .add(score).add(member), BuilderFactory.LONG); + } + + public final CommandObject zadd(byte[] key, Map scoreMembers) { + return new CommandObject<>(addSortedSetFlatMapArgs(commandArguments(ZADD).key(key), scoreMembers), BuilderFactory.LONG); + } + + public final CommandObject zadd(byte[] key, Map scoreMembers, ZAddParams params) { + return new CommandObject<>(addSortedSetFlatMapArgs(commandArguments(ZADD).key(key).addParams(params), scoreMembers), BuilderFactory.LONG); + } + + public final CommandObject zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { + return new CommandObject<>(commandArguments(ZADD).key(key).add(Keyword.INCR) + .addParams(params).add(score).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject zincrby(String key, double increment, String member) { + return new CommandObject<>(commandArguments(ZINCRBY).key(key).add(increment).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject zincrby(String key, double increment, String member, ZIncrByParams params) { + return new CommandObject<>(commandArguments(ZADD).key(key).addParams(params).add(increment).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject zincrby(byte[] key, double increment, byte[] member) { + return new CommandObject<>(commandArguments(ZINCRBY).key(key).add(increment).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params) { + return new CommandObject<>(commandArguments(ZADD).key(key).addParams(params).add(increment).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject zrem(String key, String... members) { + return new CommandObject<>(commandArguments(ZREM).key(key).addObjects((Object[]) members), BuilderFactory.LONG); + } + + public final CommandObject zrem(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(ZREM).key(key).addObjects((Object[]) members), BuilderFactory.LONG); + } + + public final CommandObject zrank(String key, String member) { + return new CommandObject<>(commandArguments(ZRANK).key(key).add(member), BuilderFactory.LONG); + } + + public final CommandObject zrevrank(String key, String member) { + return new CommandObject<>(commandArguments(ZREVRANK).key(key).add(member), BuilderFactory.LONG); + } + + public final CommandObject zrank(byte[] key, byte[] member) { + return new CommandObject<>(commandArguments(ZRANK).key(key).add(member), BuilderFactory.LONG); + } + + public final CommandObject zrevrank(byte[] key, byte[] member) { + return new CommandObject<>(commandArguments(ZREVRANK).key(key).add(member), BuilderFactory.LONG); + } + + public final CommandObject zrandmember(String key) { + return new CommandObject<>(commandArguments(ZRANDMEMBER).key(key), BuilderFactory.STRING); + } + + public final CommandObject> zrandmember(String key, long count) { + return new CommandObject<>(commandArguments(ZRANDMEMBER).key(key).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrandmemberWithScores(String key, long count) { + return new CommandObject<>(commandArguments(ZRANDMEMBER).key(key).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject zrandmember(byte[] key) { + return new CommandObject<>(commandArguments(ZRANDMEMBER).key(key), BuilderFactory.BINARY); + } + + public final CommandObject> zrandmember(byte[] key, long count) { + return new CommandObject<>(commandArguments(ZRANDMEMBER).key(key).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrandmemberWithScores(byte[] key, long count) { + return new CommandObject<>(commandArguments(ZRANDMEMBER).key(key).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject zcard(String key) { + return new CommandObject<>(commandArguments(ZCARD).key(key), BuilderFactory.LONG); + } + + public final CommandObject zscore(String key, String member) { + return new CommandObject<>(commandArguments(ZSCORE).key(key).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject> zmscore(String key, String... members) { + return new CommandObject<>(commandArguments(ZMSCORE).key(key).addObjects((Object[]) members), BuilderFactory.DOUBLE_LIST); + } + + public final CommandObject zcard(byte[] key) { + return new CommandObject<>(commandArguments(ZCARD).key(key), BuilderFactory.LONG); + } + + public final CommandObject zscore(byte[] key, byte[] member) { + return new CommandObject<>(commandArguments(ZSCORE).key(key).add(member), BuilderFactory.DOUBLE); + } + + public final CommandObject> zmscore(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(ZMSCORE).key(key).addObjects((Object[]) members), BuilderFactory.DOUBLE_LIST); + } + + public final CommandObject zpopmax(String key) { + return new CommandObject<>(commandArguments(ZPOPMAX).key(key), BuilderFactory.TUPLE); + } + + public final CommandObject> zpopmax(String key, int count) { + return new CommandObject<>(commandArguments(ZPOPMAX).key(key).add(count), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject zpopmin(String key) { + return new CommandObject<>(commandArguments(ZPOPMIN).key(key), BuilderFactory.TUPLE); + } + + public final CommandObject> zpopmin(String key, int count) { + return new CommandObject<>(commandArguments(ZPOPMIN).key(key).add(count), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject zpopmax(byte[] key) { + return new CommandObject<>(commandArguments(ZPOPMAX).key(key), BuilderFactory.TUPLE); + } + + public final CommandObject> zpopmax(byte[] key, int count) { + return new CommandObject<>(commandArguments(ZPOPMAX).key(key).add(count), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject zpopmin(byte[] key) { + return new CommandObject<>(commandArguments(ZPOPMIN).key(key), BuilderFactory.TUPLE); + } + + public final CommandObject> zpopmin(byte[] key, int count) { + return new CommandObject<>(commandArguments(ZPOPMIN).key(key).add(count), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject bzpopmax(double timeout, String... keys) { + return new CommandObject<>(commandArguments(BZPOPMAX).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.KEYED_ZSET_ELEMENT); + } + + public final CommandObject bzpopmin(double timeout, String... keys) { + return new CommandObject<>(commandArguments(BZPOPMIN).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.KEYED_ZSET_ELEMENT); + } + + public final CommandObject> bzpopmax(double timeout, byte[]... keys) { + return new CommandObject<>(commandArguments(BZPOPMAX).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> bzpopmin(double timeout, byte[]... keys) { + return new CommandObject<>(commandArguments(BZPOPMIN).blocking().keys((Object[]) keys).add(timeout), BuilderFactory.BINARY_LIST); + } + + public final CommandObject zcount(String key, double min, double max) { + return new CommandObject<>(commandArguments(ZCOUNT).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zcount(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZCOUNT).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zcount(byte[] key, double min, double max) { + return new CommandObject<>(commandArguments(ZCOUNT).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zcount(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZCOUNT).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject> zrange(String key, long start, long stop) { + return new CommandObject<>(commandArguments(ZRANGE).key(key).add(start).add(stop), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrange(String key, long start, long stop) { + return new CommandObject<>(commandArguments(ZREVRANGE).key(key).add(start).add(stop), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrangeWithScores(String key, long start, long stop) { + return new CommandObject<>(commandArguments(ZRANGE).key(key) + .add(start).add(stop).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeWithScores(String key, long start, long stop) { + return new CommandObject<>(commandArguments(ZREVRANGE).key(key) + .add(start).add(stop).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScore(String key, double min, double max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrangeByScore(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrangeByScore(String key, double max, double min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrangeByScore(String key, String max, String min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrangeByScore(String key, double min, double max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrangeByScore(String key, String min, String max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrangeByScore(String key, double max, double min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrangeByScore(String key, String max, String min, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(String key, double min, double max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(String key, double max, double min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(String key, String max, String min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(String key, double min, double max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(String key, String min, String max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrange(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(ZRANGE).key(key).add(start).add(stop), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrange(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(ZREVRANGE).key(key).add(start).add(stop), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrangeWithScores(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(ZRANGE).key(key) + .add(start).add(stop).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeWithScores(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(ZREVRANGE).key(key) + .add(start).add(stop).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScore(byte[] key, double min, double max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrangeByScore(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrangeByScore(byte[] key, double max, double min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrangeByScore(byte[] key, byte[] max, byte[] min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrangeByScore(byte[] key, double min, double max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrangeByScore(byte[] key, double max, double min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(byte[] key, double min, double max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(byte[] key, double max, double min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYSCORE).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYSCORE).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count).add(WITHSCORES), BuilderFactory.TUPLE_LIST); + } + + public final CommandObject zremrangeByRank(String key, long start, long stop) { + return new CommandObject<>(commandArguments(ZREMRANGEBYRANK).key(key).add(start).add(stop), BuilderFactory.LONG); + } + + public final CommandObject zremrangeByScore(String key, double min, double max) { + return new CommandObject<>(commandArguments(ZREMRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zremrangeByScore(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZREMRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zremrangeByRank(byte[] key, long start, long stop) { + return new CommandObject<>(commandArguments(ZREMRANGEBYRANK).key(key).add(start).add(stop), BuilderFactory.LONG); + } + + public final CommandObject zremrangeByScore(byte[] key, double min, double max) { + return new CommandObject<>(commandArguments(ZREMRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zremrangeByScore(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZREMRANGEBYSCORE).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zlexcount(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZLEXCOUNT).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject> zrangeByLex(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZRANGEBYLEX).key(key).add(min).add(max), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrangeByLex(String key, String min, String max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYLEX).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrangeByLex(String key, String max, String min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYLEX).key(key).add(max).add(min), BuilderFactory.STRING_LIST); + } + + public final CommandObject> zrevrangeByLex(String key, String max, String min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYLEX).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count), BuilderFactory.STRING_LIST); + } + + public final CommandObject zremrangeByLex(String key, String min, String max) { + return new CommandObject<>(commandArguments(ZREMRANGEBYLEX).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject zlexcount(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZLEXCOUNT).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject> zrangeByLex(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZRANGEBYLEX).key(key).add(min).add(max), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count) { + return new CommandObject<>(commandArguments(ZRANGEBYLEX).key(key).add(min).add(max) + .add(LIMIT).add(offset).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { + return new CommandObject<>(commandArguments(ZREVRANGEBYLEX).key(key).add(max).add(min), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { + return new CommandObject<>(commandArguments(ZREVRANGEBYLEX).key(key).add(max).add(min) + .add(LIMIT).add(offset).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject zremrangeByLex(byte[] key, byte[] min, byte[] max) { + return new CommandObject<>(commandArguments(ZREMRANGEBYLEX).key(key).add(min).add(max), BuilderFactory.LONG); + } + + public final CommandObject> zscan(String key, String cursor, ScanParams params) { + return new CommandObject<>(commandArguments(ZSCAN).key(key).add(cursor).addParams(params), BuilderFactory.ZSCAN_RESPONSE); + } + + public final CommandObject> zscan(byte[] key, byte[] cursor, ScanParams params) { + return new CommandObject<>(commandArguments(ZSCAN).key(key).add(cursor).addParams(params), BuilderFactory.ZSCAN_RESPONSE); + } + + public final CommandObject> zdiff(String... keys) { + return new CommandObject<>(commandArguments(ZDIFF).add(keys.length).keys((Object[]) keys), BuilderFactory.STRING_SET); + } + + public final CommandObject> zdiffWithScores(String... keys) { + return new CommandObject<>(commandArguments(ZDIFF).add(keys.length).keys((Object[]) keys) + .add(WITHSCORES), BuilderFactory.TUPLE_ZSET); + } + + public final CommandObject zdiffStore(String dstkey, String... keys) { + return new CommandObject<>(commandArguments(ZDIFFSTORE).key(dstkey).add(keys.length).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject> zdiff(byte[]... keys) { + return new CommandObject<>(commandArguments(ZDIFF).add(keys.length).keys((Object[]) keys), BuilderFactory.BINARY_SET); + } + + public final CommandObject> zdiffWithScores(byte[]... keys) { + return new CommandObject<>(commandArguments(ZDIFF).add(keys.length).keys((Object[]) keys) + .add(WITHSCORES), BuilderFactory.TUPLE_ZSET); + } + + public final CommandObject zdiffStore(byte[] dstkey, byte[]... keys) { + return new CommandObject<>(commandArguments(ZDIFFSTORE).key(dstkey) + .add(keys.length).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject zinterstore(String dstkey, String... sets) { + return new CommandObject<>(commandArguments(ZINTERSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets), BuilderFactory.LONG); + } + + public final CommandObject zinterstore(String dstkey, ZParams params, String... sets) { + return new CommandObject<>(commandArguments(ZINTERSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> zinter(ZParams params, String... keys) { + return new CommandObject<>(commandArguments(ZINTER).add(keys.length).keys((Object[]) keys) + .addParams(params), BuilderFactory.STRING_SET); + } + + public final CommandObject> zinterWithScores(ZParams params, String... keys) { + return new CommandObject<>(commandArguments(ZINTER).add(keys.length).keys((Object[]) keys) + .addParams(params).add(WITHSCORES), BuilderFactory.TUPLE_ZSET); + } + + public final CommandObject zinterstore(byte[] dstkey, byte[]... sets) { + return new CommandObject<>(commandArguments(ZINTERSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets), BuilderFactory.LONG); + } + + public final CommandObject zinterstore(byte[] dstkey, ZParams params, byte[]... sets) { + return new CommandObject<>(commandArguments(ZINTERSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> zinter(ZParams params, byte[]... keys) { + return new CommandObject<>(commandArguments(ZINTER).add(keys.length).keys((Object[]) keys) + .addParams(params), BuilderFactory.BINARY_SET); + } + + public final CommandObject> zinterWithScores(ZParams params, byte[]... keys) { + return new CommandObject<>(commandArguments(ZINTER).add(keys.length).keys((Object[]) keys) + .addParams(params).add(WITHSCORES), BuilderFactory.TUPLE_ZSET); + } + + public final CommandObject zunionstore(String dstkey, String... sets) { + return new CommandObject<>(commandArguments(ZUNIONSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets), BuilderFactory.LONG); + } + + public final CommandObject zunionstore(String dstkey, ZParams params, String... sets) { + return new CommandObject<>(commandArguments(ZUNIONSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> zunion(ZParams params, String... keys) { + return new CommandObject<>(commandArguments(ZUNION).add(keys.length).keys((Object[]) keys) + .addParams(params), BuilderFactory.STRING_SET); + } + + public final CommandObject> zunionWithScores(ZParams params, String... keys) { + return new CommandObject<>(commandArguments(ZUNION).add(keys.length).keys((Object[]) keys) + .addParams(params).add(WITHSCORES), BuilderFactory.TUPLE_ZSET); + } + + public final CommandObject zunionstore(byte[] dstkey, byte[]... sets) { + return new CommandObject<>(commandArguments(ZUNIONSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets), BuilderFactory.LONG); + } + + public final CommandObject zunionstore(byte[] dstkey, ZParams params, byte[]... sets) { + return new CommandObject<>(commandArguments(ZUNIONSTORE).key(dstkey) + .add(sets.length).keys((Object[]) sets).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject> zunion(ZParams params, byte[]... keys) { + return new CommandObject<>(commandArguments(ZUNION).add(keys.length).keys((Object[]) keys) + .addParams(params), BuilderFactory.BINARY_SET); + } + + public final CommandObject> zunionWithScores(ZParams params, byte[]... keys) { + return new CommandObject<>(commandArguments(ZUNION).add(keys.length).keys((Object[]) keys) + .addParams(params).add(WITHSCORES), BuilderFactory.TUPLE_ZSET); + } + // Sorted Set commands + + // Geo commands + public final CommandObject geoadd(String key, double longitude, double latitude, String member) { + return new CommandObject<>(commandArguments(GEOADD).key(key).add(longitude).add(latitude).add(member), BuilderFactory.LONG); + } + + public final CommandObject geoadd(String key, Map memberCoordinateMap) { + return new CommandObject<>(addGeoCoordinateFlatMapArgs(commandArguments(GEOADD).key(key), memberCoordinateMap), BuilderFactory.LONG); + } + + public final CommandObject geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { + return new CommandObject<>(addGeoCoordinateFlatMapArgs(commandArguments(GEOADD).key(key).addParams(params), memberCoordinateMap), BuilderFactory.LONG); + } + + public final CommandObject geodist(String key, String member1, String member2) { + return new CommandObject<>(commandArguments(GEODIST).key(key).add(member1).add(member2), BuilderFactory.DOUBLE); + } + + public final CommandObject geodist(String key, String member1, String member2, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEODIST).key(key).add(member1).add(member2).add(unit), BuilderFactory.DOUBLE); + } + + public final CommandObject> geohash(String key, String... members) { + return new CommandObject<>(commandArguments(GEOHASH).key(key).addObjects((Object[]) members), BuilderFactory.STRING_LIST); + } + + public final CommandObject> geopos(String key, String... members) { + return new CommandObject<>(commandArguments(GEOPOS).key(key).addObjects((Object[]) members), BuilderFactory.GEO_COORDINATE_LIST); + } + + public final CommandObject geoadd(byte[] key, double longitude, double latitude, byte[] member) { + return new CommandObject<>(commandArguments(GEOADD).key(key).add(longitude).add(latitude).add(member), BuilderFactory.LONG); + } + + public final CommandObject geoadd(byte[] key, Map memberCoordinateMap) { + return new CommandObject<>(addGeoCoordinateFlatMapArgs(commandArguments(GEOADD).key(key), memberCoordinateMap), BuilderFactory.LONG); + } + + public final CommandObject geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { + return new CommandObject<>(addGeoCoordinateFlatMapArgs(commandArguments(GEOADD).key(key).addParams(params), memberCoordinateMap), BuilderFactory.LONG); + } + + public final CommandObject geodist(byte[] key, byte[] member1, byte[] member2) { + return new CommandObject<>(commandArguments(GEODIST).key(key).add(member1).add(member2), BuilderFactory.DOUBLE); + } + + public final CommandObject geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEODIST).key(key).add(member1).add(member2).add(unit), BuilderFactory.DOUBLE); + } + + public final CommandObject> geohash(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(GEOHASH).key(key).addObjects((Object[]) members), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> geopos(byte[] key, byte[]... members) { + return new CommandObject<>(commandArguments(GEOPOS).key(key).addObjects((Object[]) members), BuilderFactory.GEO_COORDINATE_LIST); + } + + public final CommandObject> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUS).key(key).add(longitude).add(latitude) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadius(String key, + double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUS).key(key).add(longitude).add(latitude) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUS_RO).key(key).add(longitude).add(latitude) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusReadonly(String key, + double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUS_RO).key(key).add(longitude).add(latitude) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject georadiusStore(String key, double longitude, double latitude, + double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return new CommandObject<>(commandArguments(GEORADIUS).key(key).add(longitude).add(latitude) + .add(radius).add(unit).addParams(param).addParams(storeParam), BuilderFactory.LONG); + } + + public final CommandObject> georadiusByMember(String key, String member, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER).key(key).add(member) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusByMember(String key, + String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER).key(key).add(member) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER_RO).key(key).add(member) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusByMemberReadonly(String key, + String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER_RO).key(key).add(member) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject georadiusByMemberStore(String key, String member, + double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER).key(key).add(member) + .add(radius).add(unit).addParams(param).addParams(storeParam), BuilderFactory.LONG); + } + + public final CommandObject> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUS).key(key).add(longitude).add(latitude) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadius(byte[] key, + double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUS).key(key).add(longitude).add(latitude) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusReadonly(byte[] key, + double longitude, double latitude, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUS_RO).key(key).add(longitude).add(latitude) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusReadonly(byte[] key, + double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUS_RO).key(key).add(longitude).add(latitude) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject georadiusStore(byte[] key, double longitude, double latitude, + double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return new CommandObject<>(commandArguments(GEORADIUS).key(key).add(longitude).add(latitude) + .add(radius).add(unit).addParams(param).addParams(storeParam), BuilderFactory.LONG); + } + + public final CommandObject> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER).key(key).add(member) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER).key(key).add(member) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER_RO).key(key).add(member) + .add(radius).add(unit), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER_RO).key(key).add(member) + .add(radius).add(unit).addParams(param), BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); + } + + public final CommandObject georadiusByMemberStore(byte[] key, byte[] member, + double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return new CommandObject<>(commandArguments(GEORADIUSBYMEMBER).key(key).add(member) + .add(radius).add(unit).addParams(param).addParams(storeParam), BuilderFactory.LONG); + } + // Geo commands + + // Hyper Log Log commands + public final CommandObject pfadd(String key, String... elements) { + return new CommandObject<>(commandArguments(PFADD).key(key).addObjects((Object[]) elements), BuilderFactory.LONG); + } + + public final CommandObject pfmerge(String destkey, String... sourcekeys) { + return new CommandObject<>(commandArguments(PFMERGE).key(destkey).keys((Object[]) sourcekeys), BuilderFactory.STRING); + } + + public final CommandObject pfadd(byte[] key, byte[]... elements) { + return new CommandObject<>(commandArguments(PFADD).key(key).addObjects((Object[]) elements), BuilderFactory.LONG); + } + + public final CommandObject pfmerge(byte[] destkey, byte[]... sourcekeys) { + return new CommandObject<>(commandArguments(PFMERGE).key(destkey).keys((Object[]) sourcekeys), BuilderFactory.STRING); + } + + public final CommandObject pfcount(String key) { + return new CommandObject<>(commandArguments(PFCOUNT).key(key), BuilderFactory.LONG); + } + + public final CommandObject pfcount(String... keys) { + return new CommandObject<>(commandArguments(PFCOUNT).keys((Object[]) keys), BuilderFactory.LONG); + } + + public final CommandObject pfcount(byte[] key) { + return new CommandObject<>(commandArguments(PFCOUNT).key(key), BuilderFactory.LONG); + } + + public final CommandObject pfcount(byte[]... keys) { + return new CommandObject<>(commandArguments(PFCOUNT).keys((Object[]) keys), BuilderFactory.LONG); + } + // Hyper Log Log commands + + // Stream commands + public final CommandObject xadd(String key, StreamEntryID id, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(XADD).key(key).add(id == null ? StreamEntryID.NEW_ENTRY : id), hash), + BuilderFactory.STREAM_ENTRY_ID); + } + + public final CommandObject xadd(String key, XAddParams params, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(XADD).key(key).addParams(params), hash), + BuilderFactory.STREAM_ENTRY_ID); + } + + public final CommandObject xlen(String key) { + return new CommandObject<>(commandArguments(XLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject xadd(byte[] key, XAddParams params, Map hash) { + return new CommandObject<>(addFlatMapArgs(commandArguments(XADD).key(key).addParams(params), hash), + BuilderFactory.BINARY); + } + + public final CommandObject xlen(byte[] key) { + return new CommandObject<>(commandArguments(XLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject> xrange(String key, StreamEntryID start, StreamEntryID end) { + return new CommandObject<>(commandArguments(XRANGE).key(key).add(start == null ? "-" : start).add(end == null ? "+" : end), + BuilderFactory.STREAM_ENTRY_LIST); + } + + public final CommandObject> xrange(String key, StreamEntryID start, StreamEntryID end, int count) { + return new CommandObject<>(commandArguments(XRANGE).key(key).add(start == null ? "-" : start).add(end == null ? "+" : end) + .add(COUNT).add(count), BuilderFactory.STREAM_ENTRY_LIST); + } + + public final CommandObject> xrevrange(String key, StreamEntryID end, StreamEntryID start) { + return new CommandObject<>(commandArguments(XREVRANGE).key(key).add(end == null ? "+" : end).add(start == null ? "-" : start), + BuilderFactory.STREAM_ENTRY_LIST); + } + + public final CommandObject> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { + return new CommandObject<>(commandArguments(XREVRANGE).key(key).add(end == null ? "+" : end).add(start == null ? "-" : start) + .add(COUNT).add(count), BuilderFactory.STREAM_ENTRY_LIST); + } + + public final CommandObject> xrange(byte[] key, byte[] start, byte[] end) { + return new CommandObject<>(commandArguments(XRANGE).key(key).add(start == null ? "-" : start).add(end == null ? "+" : end), + BuilderFactory.BINARY_LIST); + } + + public final CommandObject> xrange(byte[] key, byte[] start, byte[] end, int count) { + return new CommandObject<>(commandArguments(XRANGE).key(key).add(start == null ? "-" : start).add(end == null ? "+" : end) + .add(COUNT).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> xrevrange(byte[] key, byte[] end, byte[] start) { + return new CommandObject<>(commandArguments(XREVRANGE).key(key).add(end == null ? "+" : end).add(start == null ? "-" : start), + BuilderFactory.BINARY_LIST); + } + + public final CommandObject> xrevrange(byte[] key, byte[] end, byte[] start, int count) { + return new CommandObject<>(commandArguments(XREVRANGE).key(key).add(end == null ? "+" : end).add(start == null ? "-" : start) + .add(COUNT).add(count), BuilderFactory.BINARY_LIST); + } + + public final CommandObject xack(String key, String group, StreamEntryID... ids) { + return new CommandObject<>(commandArguments(XACK).key(key).add(group).addObjects((Object[]) ids), BuilderFactory.LONG); + } + + public final CommandObject xack(byte[] key, byte[] group, byte[]... ids) { + return new CommandObject<>(commandArguments(XACK).key(key).add(group).addObjects((Object[]) ids), BuilderFactory.LONG); + } + + public final CommandObject xgroupCreate(String key, String groupname, StreamEntryID id, boolean makeStream) { + CommandArguments args = commandArguments(XGROUP).add(CREATE).key(key) + .add(groupname).add(id == null ? "0-0" : id); + if (makeStream) args.add(MKSTREAM); + return new CommandObject<>(args, BuilderFactory.STRING); + } + + public final CommandObject xgroupSetID(String key, String groupname, StreamEntryID id) { + return new CommandObject<>(commandArguments(XGROUP).add(SETID) + .key(key).add(groupname).add(id), BuilderFactory.STRING); + } + + public final CommandObject xgroupDestroy(String key, String groupname) { + return new CommandObject<>(commandArguments(XGROUP).add(DESTROY) + .key(key).add(groupname), BuilderFactory.LONG); + } + + public final CommandObject xgroupDelConsumer(String key, String groupname, String consumername) { + return new CommandObject<>(commandArguments(XGROUP).add(DELCONSUMER) + .key(key).add(groupname).add(consumername), BuilderFactory.LONG); + } + + public final CommandObject xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream) { + CommandArguments args = commandArguments(XGROUP).add(CREATE).key(key) + .add(groupname).add(id); + if (makeStream) args.add(MKSTREAM); + return new CommandObject<>(args, BuilderFactory.STRING); + } + + public final CommandObject xgroupSetID(byte[] key, byte[] groupname, byte[] id) { + return new CommandObject<>(commandArguments(XGROUP).add(SETID) + .key(key).add(groupname).add(id), BuilderFactory.STRING); + } + + public final CommandObject xgroupDestroy(byte[] key, byte[] groupname) { + return new CommandObject<>(commandArguments(XGROUP).add(DESTROY) + .key(key).add(groupname), BuilderFactory.LONG); + } + + public final CommandObject xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName) { + return new CommandObject<>(commandArguments(XGROUP).add(DELCONSUMER) + .key(key).add(groupname).add(consumerName), BuilderFactory.LONG); + } + + public final CommandObject xdel(String key, StreamEntryID... ids) { + return new CommandObject<>(commandArguments(XDEL).key(key).addObjects((Object[]) ids), BuilderFactory.LONG); + } + + public final CommandObject xtrim(String key, long maxLen, boolean approximate) { + CommandArguments args = commandArguments(XTRIM).key(key).add(MAXLEN); + if (approximate) args.add(Protocol.BYTES_TILDE); + args.add(maxLen); + return new CommandObject<>(args, BuilderFactory.LONG); + } + + public final CommandObject xtrim(String key, XTrimParams params) { + return new CommandObject<>(commandArguments(XTRIM).key(key).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject xdel(byte[] key, byte[]... ids) { + return new CommandObject<>(commandArguments(XDEL).key(key).addObjects((Object[]) ids), BuilderFactory.LONG); + } + + public final CommandObject xtrim(byte[] key, long maxLen, boolean approximateLength) { + CommandArguments args = commandArguments(XTRIM).key(key).add(MAXLEN); + if (approximateLength) args.add(Protocol.BYTES_TILDE); + args.add(maxLen); + return new CommandObject<>(args, BuilderFactory.LONG); + } + + public final CommandObject xtrim(byte[] key, XTrimParams params) { + return new CommandObject<>(commandArguments(XTRIM).key(key).addParams(params), BuilderFactory.LONG); + } + + public final CommandObject xpending(String key, String groupname) { + return new CommandObject<>(commandArguments(XPENDING).key(key).add(groupname), + BuilderFactory.STREAM_PENDING_SUMMARY); + } + + public final CommandObject> xpending(String key, String groupname, + StreamEntryID start, StreamEntryID end, int count, String consumername) { + CommandArguments args = commandArguments(XPENDING).key(key).add(groupname) + .add(start == null ? "-" : start).add(end == null ? "+" : end).add(count); + if (consumername != null) args.add(consumername); + return new CommandObject<>(args, BuilderFactory.STREAM_PENDING_ENTRY_LIST); + } + + public final CommandObject> xpending(String key, String groupname, XPendingParams params) { + return new CommandObject<>(commandArguments(XPENDING).key(key).add(groupname) + .addParams(params), BuilderFactory.STREAM_PENDING_ENTRY_LIST); + } + + public final CommandObject xpending(byte[] key, byte[] groupname) { + return new CommandObject<>(commandArguments(XPENDING).key(key).add(groupname), + BuilderFactory.RAW_OBJECT); + } + + public final CommandObject> xpending(byte[] key, byte[] groupname, + byte[] start, byte[] end, int count, byte[] consumername) { + CommandArguments args = commandArguments(XPENDING).key(key).add(groupname) + .add(start == null ? "-" : start).add(end == null ? "+" : end).add(count); + if (consumername != null) args.add(consumername); + return new CommandObject<>(args, BuilderFactory.RAW_OBJECT_LIST); + } + + public final CommandObject> xpending(byte[] key, byte[] groupname, XPendingParams params) { + return new CommandObject<>(commandArguments(XPENDING).key(key).add(groupname) + .addParams(params), BuilderFactory.RAW_OBJECT_LIST); + } + + public final CommandObject> xclaim(String key, String group, + String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return new CommandObject<>(commandArguments(XCLAIM).key(key).add(group) + .add(consumername).add(minIdleTime).addObjects((Object[]) ids).addParams(params), + BuilderFactory.STREAM_ENTRY_LIST); + } + + public final CommandObject> xclaimJustId(String key, String group, + String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return new CommandObject<>(commandArguments(XCLAIM).key(key).add(group) + .add(consumername).add(minIdleTime).addObjects((Object[]) ids).addParams(params) + .add(JUSTID), BuilderFactory.STREAM_ENTRY_ID_LIST); + } + + public final CommandObject>> xautoclaim(String key, + String group, String consumerName, long minIdleTime, StreamEntryID start, + XAutoClaimParams params) { + return new CommandObject<>(commandArguments(XAUTOCLAIM).key(key).add(group) + .add(consumerName).add(minIdleTime).add(start).addParams(params), + BuilderFactory.STREAM_AUTO_CLAIM_RESPONSE); + } + + public final CommandObject>> xautoclaimJustId( + String key, String group, String consumerName, long minIdleTime, StreamEntryID start, + XAutoClaimParams params) { + return new CommandObject<>(commandArguments(XAUTOCLAIM).key(key).add(group) + .add(consumerName).add(minIdleTime).add(start).addParams(params) + .add(JUSTID), BuilderFactory.STREAM_AUTO_CLAIM_ID_RESPONSE); + } + + public final CommandObject> xclaim(byte[] key, byte[] group, + byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return new CommandObject<>(commandArguments(XCLAIM).key(key).add(group) + .add(consumername).add(minIdleTime).addObjects((Object[]) ids).addParams(params), + BuilderFactory.BINARY_LIST); + } + + public final CommandObject> xclaimJustId(byte[] key, byte[] group, + byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return new CommandObject<>(commandArguments(XCLAIM).key(key).add(group) + .add(consumername).add(minIdleTime).addObjects((Object[]) ids).addParams(params) + .add(JUSTID), BuilderFactory.BINARY_LIST); + } + + public final CommandObject> xautoclaim(byte[] key, byte[] groupName, + byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return new CommandObject<>(commandArguments(XAUTOCLAIM).key(key).add(groupName) + .add(consumerName).add(minIdleTime).add(start).addParams(params), + BuilderFactory.RAW_OBJECT_LIST); + } + + public final CommandObject> xautoclaimJustId(byte[] key, byte[] groupName, + byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return new CommandObject<>(commandArguments(XAUTOCLAIM).key(key).add(groupName) + .add(consumerName).add(minIdleTime).add(start).addParams(params) + .add(JUSTID), BuilderFactory.RAW_OBJECT_LIST); + } + + public final CommandObject xinfoStream(String key) { + return new CommandObject<>(commandArguments(XINFO).add(STREAM).key(key), BuilderFactory.STREAM_INFO); + } + + public final CommandObject> xinfoGroup(String key) { + return new CommandObject<>(commandArguments(XINFO).add(GROUPS).key(key), BuilderFactory.STREAM_GROUP_INFO_LIST); + } + + public final CommandObject> xinfoConsumers(String key, String group) { + return new CommandObject<>(commandArguments(XINFO).add(CONSUMERS).key(key).add(group), BuilderFactory.STREAM_CONSUMERS_INFO_LIST); + } + + public final CommandObject xinfoStream(byte[] key) { + return new CommandObject<>(commandArguments(XINFO).add(STREAM).key(key), BuilderFactory.RAW_OBJECT); + } + + public final CommandObject> xinfoGroup(byte[] key) { + return new CommandObject<>(commandArguments(XINFO).add(GROUPS).key(key), BuilderFactory.RAW_OBJECT_LIST); + } + + public final CommandObject> xinfoConsumers(byte[] key, byte[] group) { + return new CommandObject<>(commandArguments(XINFO).add(CONSUMERS).key(key).add(group), BuilderFactory.RAW_OBJECT_LIST); + } + + public final CommandObject>>> xread( + XReadParams xReadParams, Map streams) { + CommandArguments args = commandArguments(XREAD).addParams(xReadParams).add(STREAMS); + Set> entrySet = streams.entrySet(); + entrySet.forEach(entry -> args.key(entry.getKey())); + entrySet.forEach(entry -> args.add(entry.getValue())); + return new CommandObject<>(args, BuilderFactory.STREAM_READ_RESPONSE); + } + + public final CommandObject>>> xreadGroup( + String groupname, String consumer, XReadGroupParams xReadGroupParams, + Map streams) { + CommandArguments args = commandArguments(XREADGROUP) + .add(GROUP).add(groupname).add(consumer) + .addParams(xReadGroupParams).add(STREAMS); + Set> entrySet = streams.entrySet(); + entrySet.forEach(entry -> args.key(entry.getKey())); + entrySet.forEach(entry -> args.add(entry.getValue())); + return new CommandObject<>(args, BuilderFactory.STREAM_READ_RESPONSE); + } + + public final CommandObject> xread(XReadParams xReadParams, Map.Entry... streams) { + CommandArguments args = commandArguments(XREAD).addParams(xReadParams).add(STREAMS); + for (Map.Entry entry : streams) { + args.key(entry.getKey()); + } + for (Map.Entry entry : streams) { + args.add(entry.getValue()); + } + return new CommandObject<>(args, BuilderFactory.BINARY_LIST); + } + + public final CommandObject> xreadGroup(byte[] groupname, byte[] consumer, + XReadGroupParams xReadGroupParams, Map.Entry... streams) { + CommandArguments args = commandArguments(XREADGROUP) + .add(GROUP).add(groupname).add(consumer) + .addParams(xReadGroupParams).add(STREAMS); + for (Map.Entry entry : streams) { + args.key(entry.getKey()); + } + for (Map.Entry entry : streams) { + args.add(entry.getValue()); + } + return new CommandObject<>(args, BuilderFactory.BINARY_LIST); + } + // Stream commands + + // Scripting commands + public final CommandObject eval(String script) { + return new CommandObject<>(commandArguments(EVAL).add(script).add(0), BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject eval(String script, String sampleKey) { + return new CommandObject<>(commandArguments(EVAL).add(script).add(0).processKey(sampleKey), BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject eval(String script, int keyCount, String... params) { + return new CommandObject<>(commandArguments(EVAL).add(script).add(keyCount) + .addObjects((Object[]) params).processKeys(Arrays.copyOf(params, keyCount)), + BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject eval(String script, List keys, List args) { + String[] keysArray = keys.toArray(new String[keys.size()]); + String[] argsArray = args.toArray(new String[args.size()]); + return new CommandObject<>(commandArguments(EVAL).add(script).add(keysArray.length) + .keys((Object[]) keysArray).addObjects((Object[]) argsArray), + BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject eval(byte[] script) { + return new CommandObject<>(commandArguments(EVAL).add(script).add(0), BuilderFactory.RAW_OBJECT); + } + + public final CommandObject eval(byte[] script, byte[] sampleKey) { + return new CommandObject<>(commandArguments(EVAL).add(script).add(0).processKey(sampleKey), BuilderFactory.RAW_OBJECT); + } + + public final CommandObject eval(byte[] script, int keyCount, byte[]... params) { + return new CommandObject<>(commandArguments(EVAL).add(script).add(keyCount) + .addObjects((Object[]) params).processKeys(Arrays.copyOf(params, keyCount)), + BuilderFactory.RAW_OBJECT); + } + + public final CommandObject eval(byte[] script, List keys, List args) { + byte[][] keysArray = keys.toArray(new byte[keys.size()][]); + byte[][] argsArray = args.toArray(new byte[args.size()][]); + return new CommandObject<>(commandArguments(EVAL).add(script).add(keysArray.length) + .keys((Object[]) keysArray).addObjects((Object[]) argsArray), + BuilderFactory.RAW_OBJECT); + } + + public final CommandObject evalsha(String sha1) { + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(0), BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject evalsha(String sha1, String sampleKey) { + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(0).processKey(sampleKey), BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject evalsha(String sha1, int keyCount, String... params) { + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(keyCount) + .addObjects((Object[]) params).processKeys(Arrays.copyOf(params, keyCount)), + BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject evalsha(String sha1, List keys, List args) { + String[] keysArray = keys.toArray(new String[keys.size()]); + String[] argsArray = args.toArray(new String[args.size()]); + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(keysArray.length) + .keys((Object[]) keysArray).addObjects((Object[]) argsArray), + BuilderFactory.ENCODED_OBJECT); + } + + public final CommandObject evalsha(byte[] sha1) { + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(0), BuilderFactory.RAW_OBJECT); + } + + public final CommandObject evalsha(byte[] sha1, byte[] sampleKey) { + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(0).processKey(sampleKey), BuilderFactory.RAW_OBJECT); + } + + public final CommandObject evalsha(byte[] sha1, int keyCount, byte[]... params) { + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(keyCount) + .addObjects((Object[]) params).processKeys(Arrays.copyOf(params, keyCount)), + BuilderFactory.RAW_OBJECT); + } + + public final CommandObject evalsha(byte[] sha1, List keys, List args) { + byte[][] keysArray = keys.toArray(new byte[keys.size()][]); + byte[][] argsArray = args.toArray(new byte[args.size()][]); + return new CommandObject<>(commandArguments(EVALSHA).add(sha1).add(keysArray.length) + .keys((Object[]) keysArray).addObjects((Object[]) argsArray), + BuilderFactory.RAW_OBJECT); + } + + public final CommandObject> scriptExists(String sampleKey, String... sha1s) { + return new CommandObject<>(commandArguments(SCRIPT).add(Keyword.EXISTS).addObjects((Object[]) sha1s) + .processKey(sampleKey), BuilderFactory.BOOLEAN_LIST); + } + + public final CommandObject scriptLoad(String script, String sampleKey) { + return new CommandObject<>(commandArguments(SCRIPT).add(LOAD).add(script).processKey(sampleKey), BuilderFactory.STRING); + } + + public final CommandObject scriptFlush(String sampleKey) { + return new CommandObject<>(commandArguments(SCRIPT).add(FLUSH).processKey(sampleKey), BuilderFactory.STRING); + } + + public final CommandObject scriptFlush(String sampleKey, FlushMode flushMode) { + return new CommandObject<>(commandArguments(SCRIPT).add(FLUSH).add(flushMode).processKey(sampleKey), BuilderFactory.STRING); + } + + public final CommandObject scriptKill(String sampleKey) { + return new CommandObject<>(commandArguments(SCRIPT).add(KILL).processKey(sampleKey), BuilderFactory.STRING); + } + + public final CommandObject> scriptExists(byte[] sampleKey, byte[]... sha1s) { + return new CommandObject<>(commandArguments(SCRIPT).add(Keyword.EXISTS).addObjects((Object[]) sha1s) + .processKey(sampleKey), BuilderFactory.BOOLEAN_LIST); + } + + public final CommandObject scriptLoad(byte[] script, byte[] sampleKey) { + return new CommandObject<>(commandArguments(SCRIPT).add(LOAD).add(script).processKey(sampleKey), BuilderFactory.BINARY); + } + + public final CommandObject scriptFlush(byte[] sampleKey) { + return new CommandObject<>(commandArguments(SCRIPT).add(FLUSH).processKey(sampleKey), BuilderFactory.STRING); + } + + public final CommandObject scriptFlush(byte[] sampleKey, FlushMode flushMode) { + return new CommandObject<>(commandArguments(SCRIPT).add(FLUSH).add(flushMode).processKey(sampleKey), BuilderFactory.STRING); + } + + public final CommandObject scriptKill(byte[] sampleKey) { + return new CommandObject<>(commandArguments(SCRIPT).add(KILL).processKey(sampleKey), BuilderFactory.STRING); + } + // Scripting commands + + // Miscellaneous commands + public final CommandObject strAlgoLCSStrings(String strA, String strB, StrAlgoLCSParams params) { + return new CommandObject<>(commandArguments(STRALGO).add(LCS).add(STRINGS) + .add(strA).add(strB).addParams(params), + BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); + } + + public final CommandObject strAlgoLCSStrings(byte[] strA, byte[] strB, StrAlgoLCSParams params) { + return new CommandObject<>(commandArguments(STRALGO).add(LCS).add(STRINGS) + .add(strA).add(strB).addParams(params), + BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); + } + + public final CommandObject copy(String srcKey, String dstKey, int dstDB, boolean replace) { + CommandArguments args = commandArguments(Command.COPY).key(srcKey).key(dstKey).add(DB).add(dstDB); + if (replace) { + args.add(REPLACE); + } + return new CommandObject<>(args, BuilderFactory.BOOLEAN); + } + + public final CommandObject copy(byte[] srcKey, byte[] dstKey, int dstDB, boolean replace) { + CommandArguments args = commandArguments(Command.COPY).key(srcKey).key(dstKey).add(DB).add(dstDB); + if (replace) { + args.add(REPLACE); + } + return new CommandObject<>(args, BuilderFactory.BOOLEAN); + } + + public final CommandObject memoryUsage(String key) { + return new CommandObject<>(commandArguments(MEMORY).add(USAGE).key(key), BuilderFactory.LONG); + } + + public final CommandObject memoryUsage(String key, int samples) { + return new CommandObject<>(commandArguments(MEMORY).add(USAGE).key(key).add(SAMPLES).add(samples), BuilderFactory.LONG); + } + + public final CommandObject memoryUsage(byte[] key) { + return new CommandObject<>(commandArguments(MEMORY).add(USAGE).key(key), BuilderFactory.LONG); + } + + public final CommandObject memoryUsage(byte[] key, int samples) { + return new CommandObject<>(commandArguments(MEMORY).add(USAGE).key(key).add(SAMPLES).add(samples), BuilderFactory.LONG); + } + + public final CommandObject objectRefcount(String key) { + return new CommandObject<>(commandArguments(OBJECT).add(REFCOUNT).key(key), BuilderFactory.LONG); + } + + public final CommandObject objectEncoding(String key) { + return new CommandObject<>(commandArguments(OBJECT).add(ENCODING).key(key), BuilderFactory.STRING); + } + + public final CommandObject objectIdletime(String key) { + return new CommandObject<>(commandArguments(OBJECT).add(IDLETIME).key(key), BuilderFactory.LONG); + } + + public final CommandObject objectFreq(String key) { + return new CommandObject<>(commandArguments(OBJECT).add(FREQ).key(key), BuilderFactory.LONG); + } + + public final CommandObject objectRefcount(byte[] key) { + return new CommandObject<>(commandArguments(OBJECT).add(REFCOUNT).key(key), BuilderFactory.LONG); + } + + public final CommandObject objectEncoding(byte[] key) { + return new CommandObject<>(commandArguments(OBJECT).add(ENCODING).key(key), BuilderFactory.BINARY); + } + + public final CommandObject objectIdletime(byte[] key) { + return new CommandObject<>(commandArguments(OBJECT).add(IDLETIME).key(key), BuilderFactory.LONG); + } + + public final CommandObject objectFreq(byte[] key) { + return new CommandObject<>(commandArguments(OBJECT).add(FREQ).key(key), BuilderFactory.LONG); + } + + public CommandObject waitReplicas(int replicas, long timeout) { + return new CommandObject<>(commandArguments(WAIT).add(replicas).add(timeout), BuilderFactory.LONG); + } + + public final CommandObject waitReplicas(String sampleKey, int replicas, long timeout) { + return new CommandObject<>(commandArguments(WAIT).add(replicas).add(timeout).processKey(sampleKey), BuilderFactory.LONG); + } + + public final CommandObject waitReplicas(byte[] sampleKey, int replicas, long timeout) { + return new CommandObject<>(commandArguments(WAIT).add(replicas).add(timeout).processKey(sampleKey), BuilderFactory.LONG); + } + + public final CommandObject migrate(String host, int port, String key, int timeout) { + return new CommandObject<>(commandArguments(MIGRATE).add(host).add(port).key(key).add(0).add(timeout), BuilderFactory.STRING); + } + + public final CommandObject migrate(String host, int port, int timeout, MigrateParams params, String... keys) { + return new CommandObject<>(commandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(0) + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys), BuilderFactory.STRING); + } + + public final CommandObject migrate(String host, int port, byte[] key, int timeout) { + return new CommandObject<>(commandArguments(MIGRATE).add(host).add(port).key(key).add(0).add(timeout), BuilderFactory.STRING); + } + + public final CommandObject migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { + return new CommandObject<>(commandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(0) + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys), BuilderFactory.STRING); + } + + public final CommandObject publish(String channel, String message) { + return new CommandObject<>(commandArguments(PUBLISH).add(channel).add(message), BuilderFactory.LONG); + } + + public final CommandObject publish(byte[] channel, byte[] message) { + return new CommandObject<>(commandArguments(PUBLISH).add(channel).add(message), BuilderFactory.LONG); + } + // Miscellaneous commands + + // RediSearch commands + public CommandObject ftCreate(String indexName, IndexOptions indexOptions, Schema schema) { + CommandArguments args = commandArguments(SearchCommand.CREATE).add(indexName) + .addParams(indexOptions).add(SearchKeyword.SCHEMA); + schema.fields.forEach(field -> field.addParams(args)); + return new CommandObject<>(args, BuilderFactory.STRING); + } + + public CommandObject ftAlter(String indexName, Schema schema) { + CommandArguments args = commandArguments(SearchCommand.ALTER).add(indexName) + .add(SearchKeyword.SCHEMA).add(SearchKeyword.ADD); + schema.fields.forEach(field -> field.addParams(args)); + return new CommandObject<>(args, BuilderFactory.STRING); + } + + public CommandObject ftSearch(String indexName, Query query) { + return new CommandObject<>(commandArguments(SearchCommand.SEARCH).add(indexName).addParams(query), + new SearchResultBuilder(!query.getNoContent(), query.getWithScores(), query.getWithPayloads(), true)); + } + + public CommandObject ftSearch(byte[] indexName, Query query) { + return new CommandObject<>(commandArguments(SearchCommand.SEARCH).add(indexName).addParams(query), + new SearchResultBuilder(!query.getNoContent(), query.getWithScores(), query.getWithPayloads(), false)); + } + + public CommandObject ftExplain(String indexName, Query query) { + return new CommandObject<>(commandArguments(SearchCommand.EXPLAIN).add(indexName).addParams(query), BuilderFactory.STRING); + } + + public CommandObject> ftExplainCLI(String indexName, Query query) { + return new CommandObject<>(commandArguments(SearchCommand.EXPLAINCLI).add(indexName).addParams(query), BuilderFactory.STRING_LIST); + } + + public CommandObject ftAggregate(String indexName, AggregationBuilder aggr) { + return new CommandObject<>(commandArguments(SearchCommand.AGGREGATE).add(indexName).addObjects(aggr.getArgs()), + !aggr.isWithCursor() ? BuilderFactory.SEARCH_AGGREGATION_RESULT : BuilderFactory.SEARCH_AGGREGATION_RESULT_WITH_CURSOR); + } + + public CommandObject ftCursorRead(String indexName, long cursorId, int count) { + return new CommandObject<>(commandArguments(SearchCommand.CURSOR).add(SearchKeyword.READ) + .add(indexName).add(cursorId).add(count), BuilderFactory.SEARCH_AGGREGATION_RESULT_WITH_CURSOR); + } + + public CommandObject ftCursorDel(String indexName, long cursorId) { + return new CommandObject<>(commandArguments(SearchCommand.CURSOR).add(SearchKeyword.DEL) + .add(indexName).add(cursorId), BuilderFactory.STRING); + } + + public CommandObject ftDropIndex(String indexName) { + return new CommandObject<>(commandArguments(SearchCommand.DROPINDEX).add(indexName), BuilderFactory.STRING); + } + + public CommandObject ftDropIndexDD(String indexName) { + return new CommandObject<>(commandArguments(SearchCommand.DROPINDEX).add(indexName).add(SearchKeyword.DD), BuilderFactory.STRING); + } + + public CommandObject ftSynUpdate(String indexName, String synonymGroupId, String... terms) { + return new CommandObject<>(commandArguments(SearchCommand.SYNUPDATE).add(indexName) + .add(synonymGroupId).addObjects((Object[]) terms), BuilderFactory.STRING); + } + + public CommandObject>> ftSynDump(String indexName) { + return new CommandObject<>(commandArguments(SearchCommand.SYNDUMP).add(indexName), BuilderFactory.SEARCH_SYNONYM_GROUPS); + } + + public CommandObject> ftInfo(String indexName) { + return new CommandObject<>(commandArguments(SearchCommand.INFO).add(indexName), BuilderFactory.ENCODED_OBJECT_MAP); + } + + public CommandObject ftAliasAdd(String aliasName, String indexName) { + return new CommandObject<>(commandArguments(SearchCommand.ALIASADD).add(aliasName).add(indexName), BuilderFactory.STRING); + } + + public CommandObject ftAliasUpdate(String aliasName, String indexName) { + return new CommandObject<>(commandArguments(SearchCommand.ALIASUPDATE).add(aliasName).add(indexName), BuilderFactory.STRING); + } + + public CommandObject ftAliasDel(String aliasName) { + return new CommandObject<>(commandArguments(SearchCommand.ALIASDEL).add(aliasName), BuilderFactory.STRING); + } + + public final CommandObject> ftConfigGet(String option) { + return new CommandObject<>(commandArguments(SearchCommand.CONFIG).add(SearchKeyword.GET).add(option), BuilderFactory.STRING_MAP_FROM_PAIRS); + } + + public CommandObject> ftConfigGet(String indexName, String option) { + return ftConfigGet(option); + } + + public final CommandObject ftConfigSet(String option, String value) { + return new CommandObject<>(commandArguments(SearchCommand.CONFIG).add(SearchKeyword.SET).add(option).add(value), BuilderFactory.STRING); + } + + public CommandObject ftConfigSet(String indexName, String option, String value) { + return ftConfigSet(option, value); + } + // RediSearch commands + + // RedisJSON commands + public final CommandObject jsonSet(String key, Path2 path, Object object) { + return new CommandObject<>(commandArguments(JsonCommand.SET).key(key).add(path).add(object), BuilderFactory.STRING); + } + + public final CommandObject jsonSetWithEscape(String key, Path2 path, Object object) { + return new CommandObject<>(commandArguments(JsonCommand.SET).key(key).add(path).add(GSON.toJson(object)), BuilderFactory.STRING); + } + + public final CommandObject jsonSet(String key, Path path, Object pojo) { + return new CommandObject<>(commandArguments(JsonCommand.SET).key(key).add(path).add(GSON.toJson(pojo)), BuilderFactory.STRING); + } + + public final CommandObject jsonSet(String key, Path2 path, Object object, JsonSetParams params) { + return new CommandObject<>(commandArguments(JsonCommand.SET).key(key).add(path).add(object).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject jsonSetWithEscape(String key, Path2 path, Object object, JsonSetParams params) { + return new CommandObject<>(commandArguments(JsonCommand.SET).key(key).add(path).add(GSON.toJson(object)).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject jsonSet(String key, Path path, Object pojo, JsonSetParams params) { + return new CommandObject<>(commandArguments(JsonCommand.SET).key(key).add(path).add(GSON.toJson(pojo)).addParams(params), BuilderFactory.STRING); + } + + public final CommandObject jsonGet(String key) { + return new CommandObject<>(commandArguments(JsonCommand.GET).key(key), new GsonObjectBuilder<>(Object.class)); + } + + public final CommandObject jsonGet(String key, Class clazz) { + return new CommandObject<>(commandArguments(JsonCommand.GET).key(key), new GsonObjectBuilder<>(clazz)); + } + + public final CommandObject jsonGet(String key, Path2... paths) { + return new CommandObject<>(commandArguments(JsonCommand.GET).key(key).addObjects((Object[]) paths), BuilderFactory.JSON_OBJECT); + } + + public final CommandObject jsonGet(String key, Path... paths) { + return new CommandObject<>(commandArguments(JsonCommand.GET).key(key).addObjects((Object[]) paths), new GsonObjectBuilder<>(Object.class)); + } + + public final CommandObject jsonGet(String key, Class clazz, Path... paths) { + return new CommandObject<>(commandArguments(JsonCommand.GET).key(key).addObjects((Object[]) paths), new GsonObjectBuilder<>(clazz)); + } + + public final CommandObject> jsonMGet(Path2 path, String... keys) { + return new CommandObject<>(commandArguments(JsonCommand.MGET).keys((Object[]) keys).add(path), BuilderFactory.JSON_ARRAY_LIST); + } + + public final CommandObject> jsonMGet(Path path, Class clazz, String... keys) { + return new CommandObject<>(commandArguments(JsonCommand.MGET).keys((Object[]) keys).add(path), new GsonObjectListBuilder<>(clazz)); + } + + public final CommandObject jsonDel(String key) { + return new CommandObject<>(commandArguments(JsonCommand.DEL).key(key), BuilderFactory.LONG); + } + + public final CommandObject jsonDel(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.DEL).key(key).add(path), BuilderFactory.LONG); + } + + public final CommandObject jsonDel(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.DEL).key(key).add(path), BuilderFactory.LONG); + } + + public final CommandObject jsonClear(String key) { + return new CommandObject<>(commandArguments(JsonCommand.CLEAR).key(key), BuilderFactory.LONG); + } + + public final CommandObject jsonClear(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.CLEAR).key(key).add(path), BuilderFactory.LONG); + } + + public final CommandObject jsonClear(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.CLEAR).key(key).add(path), BuilderFactory.LONG); + } + + public final CommandObject> jsonToggle(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.TOGGLE).key(key).add(path), BuilderFactory.BOOLEAN_LIST); + } + + public final CommandObject jsonToggle(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.TOGGLE).key(key).add(path), BuilderFactory.STRING); + } + + public final CommandObject> jsonType(String key) { + return new CommandObject<>(commandArguments(JsonCommand.TYPE).key(key), BuilderFactory.JSON_TYPE); + } + + public final CommandObject>> jsonType(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.TYPE).key(key).add(path), BuilderFactory.JSON_TYPE_LIST); + } + + public final CommandObject> jsonType(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.TYPE).key(key).add(path), BuilderFactory.JSON_TYPE); + } + + public final CommandObject jsonStrAppend(String key, Object string) { + return new CommandObject<>(commandArguments(JsonCommand.STRAPPEND).key(key).add(GSON.toJson(string)), BuilderFactory.LONG); + } + + public final CommandObject> jsonStrAppend(String key, Path2 path, Object string) { + return new CommandObject<>(commandArguments(JsonCommand.STRAPPEND).key(key).add(path).add(GSON.toJson(string)), BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonStrAppend(String key, Path path, Object string) { + return new CommandObject<>(commandArguments(JsonCommand.STRAPPEND).key(key).add(path).add(GSON.toJson(string)), BuilderFactory.LONG); + } + + public final CommandObject jsonStrLen(String key) { + return new CommandObject<>(commandArguments(JsonCommand.STRLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject> jsonStrLen(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.STRLEN).key(key).add(path), BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonStrLen(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.STRLEN).key(key).add(path), BuilderFactory.LONG); + } + + public final CommandObject jsonArrAppend(String key, String path, JSONObject... objects) { + CommandArguments args = commandArguments(JsonCommand.ARRAPPEND).key(key).add(path); + for (Object object : objects) { + args.add(object); + } + return new CommandObject<>(args, BuilderFactory.LONG); + } + + public final CommandObject> jsonArrAppend(String key, Path2 path, Object... objects) { + CommandArguments args = commandArguments(JsonCommand.ARRAPPEND).key(key).add(path).addObjects(objects); + return new CommandObject<>(args, BuilderFactory.LONG_LIST); + } + + public final CommandObject> jsonArrAppendWithEscape(String key, Path2 path, Object... objects) { + CommandArguments args = commandArguments(JsonCommand.ARRAPPEND).key(key).add(path); + for (Object object : objects) { + args.add(GSON.toJson(object)); + } + return new CommandObject<>(args, BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonArrAppend(String key, Path path, Object... pojos) { + CommandArguments args = commandArguments(JsonCommand.ARRAPPEND).key(key).add(path); + for (Object pojo : pojos) { + args.add(GSON.toJson(pojo)); + } + return new CommandObject<>(args, BuilderFactory.LONG); + } + + public final CommandObject> jsonArrIndex(String key, Path2 path, Object scalar) { + return new CommandObject<>(commandArguments(JsonCommand.ARRINDEX).key(key).add(path).add(scalar), BuilderFactory.LONG_LIST); + } + + public final CommandObject> jsonArrIndexWithEscape(String key, Path2 path, Object scalar) { + return new CommandObject<>(commandArguments(JsonCommand.ARRINDEX).key(key).add(path).add(GSON.toJson(scalar)), BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonArrIndex(String key, Path path, Object scalar) { + return new CommandObject<>(commandArguments(JsonCommand.ARRINDEX).key(key).add(path).add(GSON.toJson(scalar)), BuilderFactory.LONG); + } + + public final CommandObject> jsonArrInsert(String key, Path2 path, int index, Object... objects) { + CommandArguments args = commandArguments(JsonCommand.ARRINSERT).key(key).add(path).add(index).addObjects(objects); + return new CommandObject<>(args, BuilderFactory.LONG_LIST); + } + + public final CommandObject> jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects) { + CommandArguments args = commandArguments(JsonCommand.ARRINSERT).key(key).add(path).add(index); + for (Object object : objects) { + args.add(GSON.toJson(object)); + } + return new CommandObject<>(args, BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonArrInsert(String key, Path path, int index, Object... pojos) { + CommandArguments args = commandArguments(JsonCommand.ARRINSERT).key(key).add(path).add(index); + for (Object pojo : pojos) { + args.add(GSON.toJson(pojo)); + } + return new CommandObject<>(args, BuilderFactory.LONG); + } + + public final CommandObject jsonArrPop(String key) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key), new GsonObjectBuilder<>(Object.class)); + } + + public final CommandObject jsonArrPop(String key, Class clazz) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key), new GsonObjectBuilder<>(clazz)); + } + + public final CommandObject> jsonArrPop(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key).add(path), new GsonObjectListBuilder<>(Object.class)); + } + + public final CommandObject jsonArrPop(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key).add(path), new GsonObjectBuilder<>(Object.class)); + } + + public final CommandObject jsonArrPop(String key, Class clazz, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key).add(path), new GsonObjectBuilder<>(clazz)); + } + + public final CommandObject> jsonArrPop(String key, Path2 path, int index) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key).add(path).add(index), new GsonObjectListBuilder<>(Object.class)); + } + + public final CommandObject jsonArrPop(String key, Path path, int index) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key).add(path).add(index), new GsonObjectBuilder<>(Object.class)); + } + + public final CommandObject jsonArrPop(String key, Class clazz, Path path, int index) { + return new CommandObject<>(commandArguments(JsonCommand.ARRPOP).key(key).add(path).add(index), new GsonObjectBuilder<>(clazz)); + } + + public final CommandObject jsonArrLen(String key) { + return new CommandObject<>(commandArguments(JsonCommand.ARRLEN).key(key), BuilderFactory.LONG); + } + + public final CommandObject> jsonArrLen(String key, Path2 path) { + return new CommandObject<>(commandArguments(JsonCommand.ARRLEN).key(key).add(path), BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonArrLen(String key, Path path) { + return new CommandObject<>(commandArguments(JsonCommand.ARRLEN).key(key).add(path), BuilderFactory.LONG); + } + + public final CommandObject> jsonArrTrim(String key, Path2 path, int start, int stop) { + return new CommandObject<>(commandArguments(JsonCommand.ARRTRIM).key(key).add(path).add(start).add(stop), BuilderFactory.LONG_LIST); + } + + public final CommandObject jsonArrTrim(String key, Path path, int start, int stop) { + return new CommandObject<>(commandArguments(JsonCommand.ARRTRIM).key(key).add(path).add(start).add(stop), BuilderFactory.LONG); + } + // RedisJSON commands + + private static final Gson GSON = new Gson(); + + private class GsonObjectBuilder extends Builder { + + private final Class clazz; + + public GsonObjectBuilder(Class clazz) { + this.clazz = clazz; + } + + @Override + public T build(Object data) { + return GSON.fromJson(BuilderFactory.STRING.build(data), clazz); + } + } + + private class GsonObjectListBuilder extends Builder> { + + private final Class clazz; + + public GsonObjectListBuilder(Class clazz) { + this.clazz = clazz; + } + + @Override + public List build(Object data) { + if (data == null) { + return null; + } + List list = BuilderFactory.STRING_LIST.build(data); + return list.stream().map(s -> GSON.fromJson(s, clazz)).collect(Collectors.toList()); + } + } + + private CommandArguments addFlatKeyValueArgs(CommandArguments args, String... keyvalues) { + for (int i = 0; i < keyvalues.length; i += 2) { + args.key(keyvalues[i]).add(keyvalues[i + 1]); + } + return args; + } + + private CommandArguments addFlatKeyValueArgs(CommandArguments args, byte[]... keyvalues) { + for (int i = 0; i < keyvalues.length; i += 2) { + args.key(keyvalues[i]).add(keyvalues[i + 1]); + } + return args; + } + + private CommandArguments addFlatMapArgs(CommandArguments args, Map map) { + for (Map.Entry entry : map.entrySet()) { + args.add(entry.getKey()); + args.add(entry.getValue()); + } + return args; + } + + private CommandArguments addSortedSetFlatMapArgs(CommandArguments args, Map map) { + for (Map.Entry entry : map.entrySet()) { + args.add(entry.getValue()); + args.add(entry.getKey()); + } + return args; + } + + private CommandArguments addGeoCoordinateFlatMapArgs(CommandArguments args, Map map) { + for (Map.Entry entry : map.entrySet()) { + GeoCoordinate ord = entry.getValue(); + args.add(ord.getLongitude()); + args.add(ord.getLatitude()); + args.add(entry.getKey()); + } + return args; + } +} diff --git a/src/main/java/redis/clients/jedis/Connection.java b/src/main/java/redis/clients/jedis/Connection.java index 605e04f88a..0e0b28c1f9 100644 --- a/src/main/java/redis/clients/jedis/Connection.java +++ b/src/main/java/redis/clients/jedis/Connection.java @@ -7,13 +7,11 @@ import java.util.ArrayList; import java.util.List; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - +import redis.clients.jedis.args.Rawable; import redis.clients.jedis.commands.ProtocolCommand; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.util.IOUtils; import redis.clients.jedis.util.RedisInputStream; import redis.clients.jedis.util.RedisOutputStream; @@ -21,14 +19,12 @@ public class Connection implements Closeable { - private static final byte[][] EMPTY_ARGS = new byte[0][]; - - private boolean socketParamModified = false; // for backward compatibility - private JedisSocketFactory socketFactory; // TODO: should be final + private ConnectionPool memberOf; + private final JedisSocketFactory socketFactory; private Socket socket; private RedisOutputStream outputStream; private RedisInputStream inputStream; - private int soTimeout = Protocol.DEFAULT_TIMEOUT; + private int soTimeout = 0; private int infiniteSoTimeout = 0; private boolean broken = false; @@ -36,49 +32,29 @@ public Connection() { this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); } - /** - * @param host - * @deprecated This constructor will be removed in future. It can be replaced with - * {@link #Connection(java.lang.String, int)} with the host and {@link Protocol#DEFAULT_PORT}. - */ - @Deprecated - public Connection(final String host) { - this(host, Protocol.DEFAULT_PORT); - } - public Connection(final String host, final int port) { - this(new HostAndPort(host, port), DefaultJedisClientConfig.builder().build()); - } - - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public Connection(final String host, final int port, final boolean ssl) { - this(new HostAndPort(host, port), DefaultJedisClientConfig.builder().ssl(ssl).build()); + this(new HostAndPort(host, port)); } - /** - * @deprecated This constructor will be removed in future. - */ - @Deprecated - public Connection(final String host, final int port, final boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(new HostAndPort(host, port), DefaultJedisClientConfig.builder().ssl(ssl) - .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) - .hostnameVerifier(hostnameVerifier).build()); + public Connection(final HostAndPort hostAndPort) { + this(new DefaultJedisSocketFactory(hostAndPort)); } public Connection(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { this(new DefaultJedisSocketFactory(hostAndPort, clientConfig)); + this.infiniteSoTimeout = clientConfig.getBlockingSocketTimeoutMillis(); + initializeFromClientConfig(clientConfig); + } + + public Connection(final JedisSocketFactory socketFactory, JedisClientConfig clientConfig) { + this.socketFactory = socketFactory; this.soTimeout = clientConfig.getSocketTimeoutMillis(); this.infiniteSoTimeout = clientConfig.getBlockingSocketTimeoutMillis(); + initializeFromClientConfig(clientConfig); } - public Connection(final JedisSocketFactory jedisSocketFactory) { - this.socketFactory = jedisSocketFactory; - this.soTimeout = jedisSocketFactory.getSoTimeout(); + public Connection(final JedisSocketFactory socketFactory) { + this.socketFactory = socketFactory; } @Override @@ -86,30 +62,19 @@ public String toString() { return "Connection{" + socketFactory + "}"; } - public Socket getSocket() { - return socket; + public final void setHandlingPool(final ConnectionPool pool) { + this.memberOf = pool; } - public int getConnectionTimeout() { - return socketFactory.getConnectionTimeout(); + final HostAndPort getHostAndPort() { + return ((DefaultJedisSocketFactory) socketFactory).getHostAndPort(); } public int getSoTimeout() { return soTimeout; } - /** - * @param connectionTimeout - * @deprecated This method is not supported anymore and is kept for backward compatibility. It - * will be removed in future. - */ - @Deprecated - public void setConnectionTimeout(int connectionTimeout) { - socketFactory.setConnectionTimeout(connectionTimeout); - } - public void setSoTimeout(int soTimeout) { - socketFactory.setSoTimeout(soTimeout); this.soTimeout = soTimeout; if (this.socket != null) { try { @@ -121,10 +86,6 @@ public void setSoTimeout(int soTimeout) { } } - public void setInfiniteSoTimeout(int infiniteSoTimeout) { - this.infiniteSoTimeout = infiniteSoTimeout; - } - public void setTimeoutInfinite() { try { if (!isConnected()) { @@ -139,29 +100,57 @@ public void setTimeoutInfinite() { public void rollbackTimeout() { try { - socket.setSoTimeout(socketFactory.getSoTimeout()); + socket.setSoTimeout(this.soTimeout); } catch (SocketException ex) { broken = true; throw new JedisConnectionException(ex); } } - public void sendCommand(final ProtocolCommand cmd, final String... args) { - final byte[][] bargs = new byte[args.length][]; - for (int i = 0; i < args.length; i++) { - bargs[i] = SafeEncoder.encode(args[i]); + public Object executeCommand(final ProtocolCommand cmd) { + return executeCommand(new CommandArguments(cmd)); + } + + public Object executeCommand(final CommandArguments args) { + sendCommand(args); + return getOne(); + } + + public T executeCommand(final CommandObject commandObject) { + final CommandArguments args = commandObject.getArguments(); + sendCommand(args); + if (!args.isBlocking()) { + return commandObject.getBuilder().build(getOne()); + } else { + try { + setTimeoutInfinite(); + return commandObject.getBuilder().build(getOne()); + } finally { + rollbackTimeout(); + } } - sendCommand(cmd, bargs); } public void sendCommand(final ProtocolCommand cmd) { - sendCommand(cmd, EMPTY_ARGS); + sendCommand(new CommandArguments(cmd)); + } + + public void sendCommand(final ProtocolCommand cmd, Rawable keyword) { + sendCommand(new CommandArguments(cmd).add(keyword)); + } + + public void sendCommand(final ProtocolCommand cmd, final String... args) { + sendCommand(new CommandArguments(cmd).addObjects((Object[]) args)); } public void sendCommand(final ProtocolCommand cmd, final byte[]... args) { + sendCommand(new CommandArguments(cmd).addObjects((Object[]) args)); + } + + public void sendCommand(final CommandArguments args) { try { connect(); - Protocol.sendCommand(outputStream, cmd, args); + Protocol.sendCommand(outputStream, args); } catch (JedisConnectionException ex) { /* * When client send request which formed by invalid protocol, Redis send back error message @@ -172,9 +161,9 @@ public void sendCommand(final ProtocolCommand cmd, final byte[]... args) { if (errorMessage != null && errorMessage.length() > 0) { ex = new JedisConnectionException(errorMessage, ex.getCause()); } - } catch (RuntimeException e) { + } catch (Exception e) { /* - * Catch any JedisConnectionException occurred from InputStream#read and just + * Catch any IOException or JedisConnectionException occurred from InputStream#read and just * ignore. This approach is safe because reading error message is optional and connection * will eventually be closed. */ @@ -185,54 +174,20 @@ public void sendCommand(final ProtocolCommand cmd, final byte[]... args) { } } - public String getHost() { - return socketFactory.getHost(); - } - - /** - * @param host - * @deprecated This method will be removed in future. - */ - @Deprecated - public void setHost(final String host) { - socketFactory.setHost(host); - socketParamModified = true; - } - - public int getPort() { - return socketFactory.getPort(); - } - - /** - * @param port - * @deprecated This method will be removed in future. - */ - @Deprecated - public void setPort(final int port) { - socketFactory.setPort(port); - socketParamModified = true; - } - public void connect() throws JedisConnectionException { - if (socketParamModified) { // this is only for backward compatibility - try { - disconnect(); - } catch (RuntimeException e) { - // swallow - } - } if (!isConnected()) { try { socket = socketFactory.createSocket(); + soTimeout = socket.getSoTimeout(); //? outputStream = new RedisOutputStream(socket.getOutputStream()); inputStream = new RedisInputStream(socket.getInputStream()); - } catch (IOException ioe) { - broken = true; - throw new JedisConnectionException("Failed to create input/output stream", ioe); } catch (JedisConnectionException jce) { broken = true; throw jce; + } catch (IOException ioe) { + broken = true; + throw new JedisConnectionException("Failed to create input/output stream", ioe); } finally { if (broken) { IOUtils.closeQuietly(socket); @@ -243,7 +198,17 @@ public void connect() throws JedisConnectionException { @Override public void close() { - disconnect(); + if (this.memberOf != null) { + ConnectionPool pool = this.memberOf; + this.memberOf = null; + if (isBroken()) { + pool.returnBrokenResource(this); + } else { + pool.returnResource(this); + } + } else { + disconnect(); + } } public void disconnect() { @@ -265,6 +230,14 @@ public boolean isConnected() { && !socket.isInputShutdown() && !socket.isOutputShutdown(); } + public boolean isBroken() { + return broken; + } + + public void setBroken() { + broken = true; + } + public String getStatusCodeReply() { flush(); final byte[] resp = (byte[]) readProtocolWithCheckingBroken(); @@ -330,10 +303,6 @@ public Object getOne() { return readProtocolWithCheckingBroken(); } - public boolean isBroken() { - return broken; - } - protected void flush() { try { outputStream.flush(); @@ -368,4 +337,75 @@ public List getMany(final int count) { } return responses; } + + private void initializeFromClientConfig(JedisClientConfig config) { + try { + connect(); + String password = config.getPassword(); + if (password != null) { + String user = config.getUser(); + if (user != null) { + auth(user, password); + } else { + auth(password); + } + } + int dbIndex = config.getDatabase(); + if (dbIndex > 0) { + select(dbIndex); + } + String clientName = config.getClientName(); + if (clientName != null) { + // TODO: need to figure out something without encoding + clientSetname(clientName); + } + } catch (JedisException je) { + try { + if (isConnected()) { + quit(); + } + disconnect(); + } catch (Exception e) { + // + } + throw je; + } + } + + private String auth(final String password) { + sendCommand(Protocol.Command.AUTH, password); + return getStatusCodeReply(); + } + + private String auth(final String user, final String password) { + sendCommand(Protocol.Command.AUTH, user, password); + return getStatusCodeReply(); + } + + public String select(final int index) { + sendCommand(Protocol.Command.SELECT, Protocol.toByteArray(index)); + return getStatusCodeReply(); + } + + private String clientSetname(final String name) { + sendCommand(Protocol.Command.CLIENT, Protocol.Keyword.SETNAME.name(), name); + return getStatusCodeReply(); + } + + public String quit() { + sendCommand(Protocol.Command.QUIT); + String quitReturn = getStatusCodeReply(); + disconnect(); + setBroken(); + return quitReturn; + } + + public boolean ping() { + sendCommand(Protocol.Command.PING); + String status = getStatusCodeReply(); + if (!"PONG".equals(status)) { + throw new JedisException(status); + } + return true; + } } diff --git a/src/main/java/redis/clients/jedis/ConnectionFactory.java b/src/main/java/redis/clients/jedis/ConnectionFactory.java new file mode 100644 index 0000000000..b7af747093 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ConnectionFactory.java @@ -0,0 +1,107 @@ +package redis.clients.jedis; + + +import org.apache.commons.pool2.PooledObject; +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.DefaultPooledObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import redis.clients.jedis.exceptions.JedisException; + +/** + * PoolableObjectFactory custom impl. + */ +public class ConnectionFactory implements PooledObjectFactory { + + private static final Logger logger = LoggerFactory.getLogger(ConnectionFactory.class); + + private final JedisSocketFactory jedisSocketFactory; + + private final JedisClientConfig clientConfig; + + public ConnectionFactory(final HostAndPort hostAndPort) { + this.clientConfig = DefaultJedisClientConfig.builder().build(); + this.jedisSocketFactory = new DefaultJedisSocketFactory(hostAndPort); + } + + public ConnectionFactory(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { + this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig); + this.jedisSocketFactory = new DefaultJedisSocketFactory(hostAndPort, this.clientConfig); + } + + public ConnectionFactory(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) { + this.clientConfig = DefaultJedisClientConfig.copyConfig(clientConfig); + this.jedisSocketFactory = jedisSocketFactory; + } + + public void setPassword(final String password) { + this.clientConfig.updatePassword(password); + } + + @Override + public void activateObject(PooledObject pooledConnection) throws Exception { + // what to do ?? + } + + @Override + public void destroyObject(PooledObject pooledConnection) throws Exception { + final Connection jedis = pooledConnection.getObject(); + if (jedis.isConnected()) { + try { + // need a proper test, probably with mock + if (!jedis.isBroken()) { + jedis.quit(); + } + } catch (RuntimeException e) { + logger.warn("Error while QUIT", e); + } + try { + jedis.close(); + } catch (RuntimeException e) { + logger.warn("Error while close", e); + } + } + } + + @Override + public PooledObject makeObject() throws Exception { + Connection jedis = null; + try { + jedis = new Connection(jedisSocketFactory, clientConfig); + jedis.connect(); + return new DefaultPooledObject<>(jedis); + } catch (JedisException je) { + if (jedis != null) { + try { + jedis.quit(); + } catch (RuntimeException e) { + logger.warn("Error while QUIT", e); + } + try { + jedis.close(); + } catch (RuntimeException e) { + logger.warn("Error while close", e); + } + } + throw je; + } + } + + @Override + public void passivateObject(PooledObject pooledConnection) throws Exception { + // TODO maybe should select db 0? Not sure right now. + } + + @Override + public boolean validateObject(PooledObject pooledConnection) { + final Connection jedis = pooledConnection.getObject(); + try { + // check HostAndPort ?? + return jedis.isConnected() && jedis.ping(); + } catch (final Exception e) { + logger.error("Error while validating pooled Connection object.", e); + return false; + } + } +} diff --git a/src/main/java/redis/clients/jedis/ConnectionPool.java b/src/main/java/redis/clients/jedis/ConnectionPool.java new file mode 100644 index 0000000000..26a3fe2a85 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ConnectionPool.java @@ -0,0 +1,32 @@ +package redis.clients.jedis; + +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import redis.clients.jedis.util.Pool; + +public class ConnectionPool extends Pool { + + public ConnectionPool(HostAndPort hostAndPort, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig) { + this(new ConnectionFactory(hostAndPort, clientConfig), poolConfig); + } + + public ConnectionPool(HostAndPort hostAndPort, JedisClientConfig clientConfig) { + this(new ConnectionFactory(hostAndPort, clientConfig)); + } + + public ConnectionPool(PooledObjectFactory factory) { + this(factory, new GenericObjectPoolConfig()); + } + + public ConnectionPool(PooledObjectFactory factory, GenericObjectPoolConfig poolConfig) { + super(factory, poolConfig); + } + + @Override + public Connection getResource() { + Connection conn = super.getResource(); + conn.setHandlingPool(this); + return conn; + } +} diff --git a/src/main/java/redis/clients/jedis/ConnectionPoolConfig.java b/src/main/java/redis/clients/jedis/ConnectionPoolConfig.java new file mode 100644 index 0000000000..48ea4942e0 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ConnectionPoolConfig.java @@ -0,0 +1,14 @@ +package redis.clients.jedis; + +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +public class ConnectionPoolConfig extends GenericObjectPoolConfig { + + public ConnectionPoolConfig() { + // defaults to make your life with connection pool easier :) + setTestWhileIdle(true); + setMinEvictableIdleTimeMillis(60000); + setTimeBetweenEvictionRunsMillis(30000); + setNumTestsPerEvictionRun(-1); + } +} diff --git a/src/main/java/redis/clients/jedis/DebugParams.java b/src/main/java/redis/clients/jedis/DebugParams.java deleted file mode 100644 index 2ac111c381..0000000000 --- a/src/main/java/redis/clients/jedis/DebugParams.java +++ /dev/null @@ -1,31 +0,0 @@ -package redis.clients.jedis; - -public class DebugParams { - - private String[] command; - - private DebugParams() { - } - - public String[] getCommand() { - return command; - } - - public static DebugParams SEGFAULT() { - DebugParams debugParams = new DebugParams(); - debugParams.command = new String[] { "SEGFAULT" }; - return debugParams; - } - - public static DebugParams OBJECT(String key) { - DebugParams debugParams = new DebugParams(); - debugParams.command = new String[] { "OBJECT", key }; - return debugParams; - } - - public static DebugParams RELOAD() { - DebugParams debugParams = new DebugParams(); - debugParams.command = new String[] { "RELOAD" }; - return debugParams; - } -} diff --git a/src/main/java/redis/clients/jedis/DefaultJedisClientConfig.java b/src/main/java/redis/clients/jedis/DefaultJedisClientConfig.java index 4c6d02ec5c..630f36f262 100644 --- a/src/main/java/redis/clients/jedis/DefaultJedisClientConfig.java +++ b/src/main/java/redis/clients/jedis/DefaultJedisClientConfig.java @@ -139,6 +139,12 @@ public DefaultJedisClientConfig build() { sslParameters, hostnameVerifier, hostAndPortMapper); } + public Builder timeoutMillis(int timeoutMillis) { + this.connectionTimeoutMillis = timeoutMillis; + this.socketTimeoutMillis = timeoutMillis; + return this; + } + public Builder connectionTimeoutMillis(int connectionTimeoutMillis) { this.connectionTimeoutMillis = connectionTimeoutMillis; return this; @@ -200,6 +206,15 @@ public Builder hostAndPortMapper(HostAndPortMapper hostAndPortMapper) { } } + public static DefaultJedisClientConfig create(int connectionTimeoutMillis, int soTimeoutMillis, + int blockingSocketTimeoutMillis, String user, String password, int database, String clientName, + boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, + HostnameVerifier hostnameVerifier, HostAndPortMapper hostAndPortMapper) { + return new DefaultJedisClientConfig(connectionTimeoutMillis, soTimeoutMillis, + blockingSocketTimeoutMillis, user, password, database, clientName, ssl, + sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMapper); + } + public static DefaultJedisClientConfig copyConfig(JedisClientConfig copy) { return new DefaultJedisClientConfig(copy.getConnectionTimeoutMillis(), copy.getSocketTimeoutMillis(), copy.getBlockingSocketTimeoutMillis(), copy.getUser(), diff --git a/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java b/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java index 4c11874abd..c7bebc2d0e 100644 --- a/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java +++ b/src/main/java/redis/clients/jedis/DefaultJedisSocketFactory.java @@ -69,34 +69,30 @@ public Socket createSocket() throws JedisConnectionException { Socket socket = null; try { socket = new Socket(); - // ->@wjw_add socket.setReuseAddress(true); socket.setKeepAlive(true); // Will monitor the TCP connection is valid socket.setTcpNoDelay(true); // Socket buffer Whetherclosed, to ensure timely delivery of data socket.setSoLinger(true, 0); // Control calls close () method, the underlying socket is closed immediately - // <-@wjw_add - HostAndPort hostAndPort = getSocketHostAndPort(); - socket.connect(new InetSocketAddress(hostAndPort.getHost(), hostAndPort.getPort()), getConnectionTimeout()); - socket.setSoTimeout(getSoTimeout()); + HostAndPort _hostAndPort = getSocketHostAndPort(); + socket.connect(new InetSocketAddress(_hostAndPort.getHost(), _hostAndPort.getPort()), connectionTimeout); + socket.setSoTimeout(socketTimeout); if (ssl) { - SSLSocketFactory sslSocketFactory = getSslSocketFactory(); - if (null == sslSocketFactory) { - sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); + SSLSocketFactory _sslSocketFactory = this.sslSocketFactory; + if (null == _sslSocketFactory) { + _sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); } - socket = sslSocketFactory.createSocket(socket, hostAndPort.getHost(), hostAndPort.getPort(), true); + socket = _sslSocketFactory.createSocket(socket, _hostAndPort.getHost(), _hostAndPort.getPort(), true); - SSLParameters sslParameters = getSslParameters(); if (null != sslParameters) { ((SSLSocket) socket).setSSLParameters(sslParameters); } - HostnameVerifier hostnameVerifier = getHostnameVerifier(); if (null != hostnameVerifier - && !hostnameVerifier.verify(hostAndPort.getHost(), ((SSLSocket) socket).getSession())) { + && !hostnameVerifier.verify(_hostAndPort.getHost(), ((SSLSocket) socket).getSession())) { String message = String.format( - "The connection to '%s' failed ssl/tls hostname verification.", hostAndPort.getHost()); + "The connection to '%s' failed ssl/tls hostname verification.", _hostAndPort.getHost()); throw new JedisConnectionException(message); } } @@ -111,167 +107,24 @@ public Socket createSocket() throws JedisConnectionException { } } - @Override public void updateHostAndPort(HostAndPort hostAndPort) { this.hostAndPort = hostAndPort; } - public HostAndPort getSocketHostAndPort() { - HostAndPortMapper mapper = getHostAndPortMapper(); - HostAndPort hostAndPort = getHostAndPort(); + public HostAndPort getHostAndPort() { + return this.hostAndPort; + } + + protected HostAndPort getSocketHostAndPort() { + HostAndPortMapper mapper = hostAndPortMapper; + HostAndPort hap = this.hostAndPort; if (mapper != null) { - HostAndPort mapped = mapper.getHostAndPort(hostAndPort); + HostAndPort mapped = mapper.getHostAndPort(hap); if (mapped != null) { return mapped; } } - return hostAndPort; - } - - public HostAndPort getHostAndPort() { - return this.hostAndPort; - } - - /** - * @param hostAndPort - * @deprecated This will be removed in next major release. Use - * {@link #updateHostAndPort(redis.clients.jedis.HostAndPort)}. - */ - @Deprecated - public void setHostAndPort(HostAndPort hostAndPort) { - this.hostAndPort = hostAndPort; - } - - @Override - public String getDescription() { - return this.hostAndPort.toString(); - } - - @Override - public String getHost() { - return this.hostAndPort.getHost(); - } - - /** - * @param host - * @deprecated This will be removed in next major release. Use - * {@link #updateHostAndPort(redis.clients.jedis.HostAndPort)}. - */ - @Override - @Deprecated - public void setHost(String host) { - this.hostAndPort = new HostAndPort(host, this.hostAndPort.getPort()); - } - - @Override - public int getPort() { - return this.hostAndPort.getPort(); - } - - /** - * @param port - * @deprecated This will be removed in next major release. Use - * {@link #updateHostAndPort(redis.clients.jedis.HostAndPort)}. - */ - @Override - @Deprecated - public void setPort(int port) { - this.hostAndPort = new HostAndPort(this.hostAndPort.getHost(), port); - } - - @Override - public int getConnectionTimeout() { - return this.connectionTimeout; - } - - /** - * @param connectionTimeout - * @deprecated This will be removed in next major release. - */ - @Override - @Deprecated - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - @Override - public int getSoTimeout() { - return this.socketTimeout; - } - - /** - * @param soTimeout - * @deprecated This will be removed in next major release. - */ - @Override - @Deprecated - public void setSoTimeout(int soTimeout) { - this.socketTimeout = soTimeout; - } - - public boolean isSsl() { - return ssl; - } - - /** - * @param ssl - * @deprecated This will be removed in next major release. - */ - @Deprecated - public void setSsl(boolean ssl) { - this.ssl = ssl; - } - - public SSLSocketFactory getSslSocketFactory() { - return sslSocketFactory; - } - - /** - * @param sslSocketFactory - * @deprecated This will be removed in next major release. - */ - @Deprecated - public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) { - this.sslSocketFactory = sslSocketFactory; - } - - public SSLParameters getSslParameters() { - return sslParameters; - } - - /** - * @param sslParameters - * @deprecated This will be removed in next major release. - */ - @Deprecated - public void setSslParameters(SSLParameters sslParameters) { - this.sslParameters = sslParameters; - } - - public HostnameVerifier getHostnameVerifier() { - return hostnameVerifier; - } - - /** - * @param hostnameVerifier - * @deprecated This will be removed in next major release. - */ - @Deprecated - public void setHostnameVerifier(HostnameVerifier hostnameVerifier) { - this.hostnameVerifier = hostnameVerifier; - } - - public HostAndPortMapper getHostAndPortMapper() { - return hostAndPortMapper; - } - - /** - * @param hostAndPortMapper - * @deprecated This will be removed in next major release. - */ - @Deprecated - public void setHostAndPortMapper(HostAndPortMapper hostAndPortMapper) { - this.hostAndPortMapper = hostAndPortMapper; + return hap; } @Override diff --git a/src/main/java/redis/clients/jedis/GeoCoordinate.java b/src/main/java/redis/clients/jedis/GeoCoordinate.java index 35883337a4..05e8d3ccff 100644 --- a/src/main/java/redis/clients/jedis/GeoCoordinate.java +++ b/src/main/java/redis/clients/jedis/GeoCoordinate.java @@ -1,6 +1,7 @@ package redis.clients.jedis; public class GeoCoordinate { + private double longitude; private double latitude; diff --git a/src/main/java/redis/clients/jedis/GeoUnit.java b/src/main/java/redis/clients/jedis/GeoUnit.java deleted file mode 100644 index 0fe9a42ea7..0000000000 --- a/src/main/java/redis/clients/jedis/GeoUnit.java +++ /dev/null @@ -1,13 +0,0 @@ -package redis.clients.jedis; - -import redis.clients.jedis.util.SafeEncoder; - -public enum GeoUnit { - M, KM, MI, FT; - - public final byte[] raw; - - GeoUnit() { - raw = SafeEncoder.encode(this.name().toLowerCase()); - } -} diff --git a/src/main/java/redis/clients/jedis/HostAndPort.java b/src/main/java/redis/clients/jedis/HostAndPort.java index d661336cec..612595e777 100644 --- a/src/main/java/redis/clients/jedis/HostAndPort.java +++ b/src/main/java/redis/clients/jedis/HostAndPort.java @@ -1,20 +1,18 @@ package redis.clients.jedis; import java.io.Serializable; -import java.net.InetAddress; -import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class HostAndPort implements Serializable { + private static final long serialVersionUID = -519876229978427751L; - protected static Logger log = LoggerFactory.getLogger(HostAndPort.class.getName()); - public static volatile String localhost; + protected static Logger log = LoggerFactory.getLogger(HostAndPort.class); - private String host; - private int port; + private final String host; + private final int port; public HostAndPort(String host, int port) { this.host = host; @@ -35,16 +33,14 @@ public boolean equals(Object obj) { if (obj == this) return true; if (!(obj instanceof HostAndPort)) return false; - HostAndPort hp = (HostAndPort) obj; + HostAndPort other = (HostAndPort) obj; - String thisHost = convertHost(host); - String hpHost = convertHost(hp.host); - return port == hp.port && thisHost.equals(hpHost); + return this.port == other.port && this.host.equals(other.host); } @Override public int hashCode() { - return 31 * convertHost(host).hashCode() + port; + return 31 * host.hashCode() + port; } @Override @@ -63,101 +59,4 @@ public static HostAndPort from(String string) { int port = Integer.parseInt(string.substring(lastColon + 1)); return new HostAndPort(host, port); } - - /** - * Splits String into host and port parts. - * String must be in ( host + ":" + port ) format. - * Port is optional - * @param from String to parse - * @return array of host and port strings - */ - public static String[] extractParts(String from) { - int idx = from.lastIndexOf(':'); - String host = idx != -1 ? from.substring(0, idx) : from; - String port = idx != -1 ? from.substring(idx + 1) : ""; - return new String[] { host, port }; - } - - /** - * Creates HostAndPort instance from string. - * String must be in ( host + ":" + port ) format. - * Port is mandatory. Can convert host part. - * @see #convertHost(String) - * @param from String to parse - * @return HostAndPort instance - */ - public static HostAndPort parseString(String from) { - // NOTE: redis answers with - // '99aa9999aa9a99aa099aaa990aa99a09aa9a9999 9a09:9a9:a090:9a::99a slave 8c88888888cc08088cc8c8c888c88c8888c88cc8 0 1468251272993 37 connected' - // for CLUSTER NODES, ASK and MOVED scenarios. That's why there is no possibility to parse address in 'correct' way. - // Redis should switch to 'bracketized' (RFC 3986) IPv6 address. - try { - String[] parts = extractParts(from); - String host = parts[0]; - int port = Integer.parseInt(parts[1]); - return new HostAndPort(convertHost(host), port); - } catch (NumberFormatException ex) { - throw new IllegalArgumentException(ex); - } - } - - public static String convertHost(String host) { - try { - /* - * Validate the host name as an IPV4/IPV6 address. - * If this is an AWS ENDPOINT it will not parse. - * In that case accept host as is. - * - * Costs: If this is an IPV4/6 encoding, e.g. 127.0.0.1 then no DNS lookup - * is done. If it is a name then a DNS lookup is done but it is normally cached. - * Secondarily, this class is typically used to create a connection once - * at the beginning of processing and then not used again. So even if the DNS - * lookup needs to be done then the cost is miniscule. - */ - InetAddress inetAddress = InetAddress.getByName(host); - - // isLoopbackAddress() handles both IPV4 and IPV6 - if (inetAddress.isLoopbackAddress() || host.equals("0.0.0.0") || host.startsWith("169.254")) { - return getLocalhost(); - } - } catch (UnknownHostException | RuntimeException e) { - // Not a valid IP address - log.warn("{}.convertHost '{}' is not a valid IP address. ", HostAndPort.class.getName(), - host, e); - } - return host; - } - - public static void setLocalhost(String localhost) { - synchronized (HostAndPort.class) { - HostAndPort.localhost = localhost; - } - } - - /** - * This method resolves the localhost in a 'lazy manner'. - * @return localhost - */ - public static String getLocalhost() { - if (localhost == null) { - synchronized (HostAndPort.class) { - if (localhost == null) { - return localhost = getLocalHostQuietly(); - } - } - } - return localhost; - } - - public static String getLocalHostQuietly() { - String localAddress; - try { - localAddress = InetAddress.getLocalHost().getHostAddress(); - } catch (UnknownHostException | RuntimeException ex) { - log.error("{}.getLocalHostQuietly : cant resolve localhost address", - HostAndPort.class.getName(), ex); - localAddress = "localhost"; - } - return localAddress; - } } diff --git a/src/main/java/redis/clients/jedis/Jedis.java b/src/main/java/redis/clients/jedis/Jedis.java index eb36cedd97..45de16981f 100644 --- a/src/main/java/redis/clients/jedis/Jedis.java +++ b/src/main/java/redis/clients/jedis/Jedis.java @@ -1,169 +1,318 @@ package redis.clients.jedis; +import static redis.clients.jedis.Protocol.Command.*; +import static redis.clients.jedis.Protocol.Keyword.*; +import static redis.clients.jedis.Protocol.toByteArray; +import static redis.clients.jedis.util.SafeEncoder.encode; + +import java.io.Closeable; import java.net.URI; -import java.util.AbstractMap; -import java.util.ArrayList; -import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import java.util.stream.Collectors; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLParameters; import javax.net.ssl.SSLSocketFactory; -import redis.clients.jedis.Protocol.SentinelKeyword; +import redis.clients.jedis.Protocol.*; import redis.clients.jedis.args.*; import redis.clients.jedis.commands.*; +import redis.clients.jedis.exceptions.InvalidURIException; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.params.*; import redis.clients.jedis.resps.*; +import redis.clients.jedis.util.JedisURIHelper; import redis.clients.jedis.util.Pool; -import redis.clients.jedis.util.SafeEncoder; -import redis.clients.jedis.util.Slowlog; -public class Jedis extends BinaryJedis implements JedisCommands, MultiKeyCommands, - AdvancedJedisCommands, ScriptingCommands, BasicCommands, ClusterCommands, SentinelCommands, - ModuleCommands { +public class Jedis implements ServerCommands, DatabaseCommands, JedisCommands, JedisBinaryCommands, + ControlCommands, ControlBinaryCommands, ClusterCommands, ModuleCommands, + GenericControlCommands, Closeable { + + protected final Connection connection; + private final CommandObjects commandObjects = new CommandObjects(); + private int db = 0; + private Transaction transaction = null; + private boolean isInMulti = false; + private boolean isInWatch = false; + private Pipeline pipeline = null; + protected static final byte[][] DUMMY_ARRAY = new byte[0][]; private Pool dataSource = null; public Jedis() { - super(); + connection = new Connection(); } /** - * @deprecated This constructor will not support a host string in future. It will accept only a - * uri string. {@link JedisURIHelper#isValid(java.net.URI)} can used before this. If this - * constructor was being used with a host, it can be replaced with - * {@link #Jedis(java.lang.String, int)} with the host and {@link Protocol#DEFAULT_PORT}. - * @param uri + * This constructor only accepts a URI string. {@link JedisURIHelper#isValid(java.net.URI)} can be + * used before this. + * @param url */ - @Deprecated - public Jedis(final String uri) { - super(uri); + public Jedis(final String url) { + this(URI.create(url)); } public Jedis(final HostAndPort hp) { - super(hp); + connection = new Connection(hp); } - public Jedis(final HostAndPort hp, final JedisClientConfig config) { - super(hp, config); + public Jedis(final String host, final int port) { + connection = new Connection(host, port); } - public Jedis(final String host, final int port) { - super(host, port); + public Jedis(final String host, final int port, final JedisClientConfig config) { + this(new HostAndPort(host, port), config); + } + + public Jedis(final HostAndPort hostPort, final JedisClientConfig config) { + connection = new Connection(hostPort, config); } public Jedis(final String host, final int port, final boolean ssl) { - super(host, port, ssl); + this(host, port, DefaultJedisClientConfig.builder().ssl(ssl).build()); } public Jedis(final String host, final int port, final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(host, port, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + this(host, port, DefaultJedisClientConfig.builder().ssl(ssl) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); } public Jedis(final String host, final int port, final int timeout) { - super(host, port, timeout); + this(host, port, timeout, timeout); } public Jedis(final String host, final int port, final int timeout, final boolean ssl) { - super(host, port, timeout, ssl); + this(host, port, timeout, timeout, ssl); } public Jedis(final String host, final int port, final int timeout, final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(host, port, timeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - } - - public Jedis(final String host, final int port, final int connectionTimeout, final int soTimeout) { - super(host, port, connectionTimeout, soTimeout); + this(host, port, timeout, timeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier); } - public Jedis(final String host, final int port, final int connectionTimeout, final int soTimeout, - final int infiniteSoTimeout) { - super(host, port, connectionTimeout, soTimeout, infiniteSoTimeout); + public Jedis(final String host, final int port, final int connectionTimeout, + final int soTimeout) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).build()); } - public Jedis(final String host, final int port, final int connectionTimeout, final int soTimeout, - final boolean ssl) { - super(host, port, connectionTimeout, soTimeout, ssl); + public Jedis(final String host, final int port, final int connectionTimeout, + final int soTimeout, final int infiniteSoTimeout) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) + .blockingSocketTimeoutMillis(infiniteSoTimeout).build()); } - public Jedis(final String host, final int port, final int connectionTimeout, final int soTimeout, - final boolean ssl, final SSLSocketFactory sslSocketFactory, - final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(host, port, connectionTimeout, soTimeout, ssl, sslSocketFactory, sslParameters, - hostnameVerifier); + public Jedis(final String host, final int port, final int connectionTimeout, + final int soTimeout, final boolean ssl) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl) + .build()); } - public Jedis(final String host, final int port, final int connectionTimeout, final int soTimeout, - final int infiniteSoTimeout, final boolean ssl, final SSLSocketFactory sslSocketFactory, + public Jedis(final String host, final int port, final int connectionTimeout, + final int soTimeout, final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(host, port, connectionTimeout, soTimeout, infiniteSoTimeout, ssl, sslSocketFactory, - sslParameters, hostnameVerifier); + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); } - public Jedis(JedisShardInfo shardInfo) { - super(shardInfo); + public Jedis(final String host, final int port, final int connectionTimeout, + final int soTimeout, final int infiniteSoTimeout, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) + .blockingSocketTimeoutMillis(infiniteSoTimeout).ssl(ssl) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); } public Jedis(URI uri) { - super(uri); + if (!JedisURIHelper.isValid(uri)) { + throw new InvalidURIException(String.format( + "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); + } + connection = new Connection(new HostAndPort(uri.getHost(), uri.getPort()), + DefaultJedisClientConfig.builder().user(JedisURIHelper.getUser(uri)) + .password(JedisURIHelper.getPassword(uri)).database(JedisURIHelper.getDBIndex(uri)) + .ssl(JedisURIHelper.isRedisSSLScheme(uri)).build()); } - public Jedis(URI uri, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, - final HostnameVerifier hostnameVerifier) { - super(uri, sslSocketFactory, sslParameters, hostnameVerifier); + public Jedis(URI uri, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(uri, DefaultJedisClientConfig.builder().sslSocketFactory(sslSocketFactory) + .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); } public Jedis(final URI uri, final int timeout) { - super(uri, timeout); + this(uri, timeout, timeout); } public Jedis(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(uri, timeout, sslSocketFactory, sslParameters, hostnameVerifier); + this(uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); } public Jedis(final URI uri, final int connectionTimeout, final int soTimeout) { - super(uri, connectionTimeout, soTimeout); + this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).build()); } public Jedis(final URI uri, final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(uri, connectionTimeout, soTimeout, sslSocketFactory, sslParameters, hostnameVerifier); + this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).sslSocketFactory(sslSocketFactory) + .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); } public Jedis(final URI uri, final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { - super(uri, connectionTimeout, soTimeout, infiniteSoTimeout, sslSocketFactory, sslParameters, - hostnameVerifier); + this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); } public Jedis(final URI uri, JedisClientConfig config) { - super(uri, config); + if (!JedisURIHelper.isValid(uri)) { + throw new InvalidURIException(String.format( + "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); + } + connection = new Connection(new HostAndPort(uri.getHost(), uri.getPort()), + DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(config.getConnectionTimeoutMillis()) + .socketTimeoutMillis(config.getSocketTimeoutMillis()) + .blockingSocketTimeoutMillis(config.getBlockingSocketTimeoutMillis()) + .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) + .database(JedisURIHelper.getDBIndex(uri)).clientName(config.getClientName()) + .ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(config.getSslSocketFactory()) + .sslParameters(config.getSslParameters()).hostnameVerifier(config.getHostnameVerifier()) + .build()); } - /** - * @deprecated This constructor will be removed in future major release. - * - * Use {@link Jedis#Jedis(redis.clients.jedis.JedisSocketFactory, redis.clients.jedis.JedisClientConfig)}. - */ - @Deprecated public Jedis(final JedisSocketFactory jedisSocketFactory) { - super(jedisSocketFactory); + connection = new Connection(jedisSocketFactory); } public Jedis(final JedisSocketFactory jedisSocketFactory, final JedisClientConfig clientConfig) { - super(jedisSocketFactory, clientConfig); + connection = new Connection(jedisSocketFactory, clientConfig); + } + + public Jedis(final Connection connection) { + this.connection = connection; + } + + @Override + public String toString() { + return "Jedis{" + connection + '}'; + } + + // Legacy + public Connection getClient() { + return getConnection(); + } + + public Connection getConnection() { + return connection; + } + + // Legacy + public void connect() { + connection.connect(); + } + + // Legacy + public void disconnect() { + connection.disconnect(); + } + + public boolean isConnected() { + return connection.isConnected(); + } + + public boolean isBroken() { + return connection.isBroken(); + } + + public void resetState() { + if (isConnected()) { + if (transaction != null) { + transaction.close(); + } + + if (pipeline != null) { + pipeline.close(); + } + +// connection.resetState(); + if (isInWatch) { + connection.sendCommand(UNWATCH); + connection.getStatusCodeReply(); + isInWatch = false; + } + } + + transaction = null; + pipeline = null; + } + + protected void setDataSource(Pool jedisPool) { + this.dataSource = jedisPool; + } + + @Override + public void close() { + if (dataSource != null) { + Pool pool = this.dataSource; + this.dataSource = null; + if (isBroken()) { + pool.returnBrokenResource(this); + } else { + pool.returnResource(this); + } + } else { + connection.close(); + } + } + + // Legacy + public Transaction multi() { + transaction = new Transaction(this); + return transaction; + } + + // Legacy + public Pipeline pipelined() { + pipeline = new Pipeline(this); + return pipeline; + } + + // Legacy + protected void checkIsInMultiOrPipeline() { +// if (connection.isInMulti()) { + if (transaction != null) { + throw new IllegalStateException( + "Cannot use Jedis when in Multi. Please use Transaction or reset jedis state."); + } else if (pipeline != null && pipeline.hasPipelinedResponse()) { + throw new IllegalStateException( + "Cannot use Jedis when in Pipeline. Please use Pipeline or reset jedis state."); + } + } + + public int getDB() { + return this.db; } /** @@ -173,13 +322,11 @@ public Jedis(final JedisSocketFactory jedisSocketFactory, final JedisClientConfi * @param dstKey the destination key. * @param db * @param replace - * @return */ @Override - public boolean copy(String srcKey, String dstKey, int db, boolean replace) { + public boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) { checkIsInMultiOrPipeline(); - client.copy(srcKey, dstKey, db, replace); - return BuilderFactory.BOOLEAN.build(client.getOne()); + return connection.executeCommand(commandObjects.copy(srcKey, dstKey, db, replace)); } /** @@ -188,24 +335,32 @@ public boolean copy(String srcKey, String dstKey, int db, boolean replace) { * @param srcKey the source key. * @param dstKey the destination key. * @param replace - * @return */ @Override - public boolean copy(String srcKey, String dstKey, boolean replace) { + public boolean copy(byte[] srcKey, byte[] dstKey, boolean replace) { checkIsInMultiOrPipeline(); - client.copy(srcKey, dstKey, replace); - return BuilderFactory.BOOLEAN.build(client.getOne()); + return connection.executeCommand(commandObjects.copy(srcKey, dstKey, replace)); } /** - * Works same as ping() but returns argument message instead of PONG. + * @return PONG + */ + @Override + public String ping() { + checkIsInMultiOrPipeline(); + connection.sendCommand(Command.PING); + return connection.getStatusCodeReply(); + } + + /** + * Works same as {@link #ping()} but returns argument message instead of PONG. * @param message * @return message */ - public String ping(final String message) { + public byte[] ping(final byte[] message) { checkIsInMultiOrPipeline(); - client.ping(message); - return client.getBulkReply(); + connection.sendCommand(Command.PING, message); + return connection.getBinaryBulkReply(); } /** @@ -218,10 +373,9 @@ public String ping(final String message) { * @return Status code reply */ @Override - public String set(final String key, final String value) { + public String set(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); - client.set(key, value); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.set(key, value)); } /** @@ -229,15 +383,13 @@ public String set(final String key, final String value) { * GB). * @param key * @param value - * @param params NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the - * key if it already exist. EX|PX, expire time units: EX = seconds; PX = milliseconds + * @param params * @return Status code reply */ @Override - public String set(final String key, final String value, final SetParams params) { + public String set(final byte[] key, final byte[] value, final SetParams params) { checkIsInMultiOrPipeline(); - client.set(key, value, params); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.set(key, value, params)); } /** @@ -250,10 +402,9 @@ public String set(final String key, final String value, final SetParams params) * @return Bulk reply */ @Override - public String get(final String key) { + public byte[] get(final byte[] key) { checkIsInMultiOrPipeline(); - client.get(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.get(key)); } /** @@ -266,17 +417,24 @@ public String get(final String key) { * @since Redis 6.2 */ @Override - public String getDel(final String key) { + public byte[] getDel(final byte[] key) { checkIsInMultiOrPipeline(); - client.getDel(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.getDel(key)); } @Override - public String getEx(String key, GetExParams params) { + public byte[] getEx(final byte[] key, final GetExParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.getEx(key, params)); + } + + /** + * Ask the server to silently close the connection. + */ + @Override + public String quit() { checkIsInMultiOrPipeline(); - client.getEx(key, params); - return client.getBulkReply(); + return connection.quit(); } /** @@ -287,10 +445,9 @@ public String getEx(String key, GetExParams params) { * 0 if none of the specified keys exist. */ @Override - public long exists(final String... keys) { + public long exists(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.exists(keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.exists(keys)); } /** @@ -301,10 +458,9 @@ public long exists(final String... keys) { * @return Boolean reply, true if the key exists, otherwise false */ @Override - public boolean exists(final String key) { + public boolean exists(final byte[] key) { checkIsInMultiOrPipeline(); - client.exists(key); - return client.getIntegerReply() == 1; + return connection.executeCommand(commandObjects.exists(key)); } /** @@ -315,17 +471,15 @@ public boolean exists(final String key) { * 0 if none of the specified key existed */ @Override - public long del(final String... keys) { + public long del(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.del(keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.del(keys)); } @Override - public long del(final String key) { + public long del(final byte[] key) { checkIsInMultiOrPipeline(); - client.del(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.del(key)); } /** @@ -342,17 +496,15 @@ public long del(final String key) { * @return Integer reply: The number of keys that were unlinked */ @Override - public long unlink(final String... keys) { + public long unlink(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.unlink(keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.unlink(keys)); } @Override - public long unlink(final String key) { + public long unlink(final byte[] key) { checkIsInMultiOrPipeline(); - client.unlink(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.unlink(key)); } /** @@ -365,31 +517,79 @@ public long unlink(final String key) { * contains a Hash value */ @Override - public String type(final String key) { + public String type(final byte[] key) { checkIsInMultiOrPipeline(); - client.type(key); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.type(key)); } + /** + * Delete all the keys of the currently selected DB. This command never fails. + * @return Status code reply + */ @Override - public Set keys(final String pattern) { + public String flushDB() { + checkIsInMultiOrPipeline(); + connection.sendCommand(FLUSHDB); + return connection.getStatusCodeReply(); + } + + /** + * Delete all the keys of the currently selected DB. This command never fails. + * @param flushMode + * @return Status code reply + */ + @Override + public String flushDB(FlushMode flushMode) { + checkIsInMultiOrPipeline(); + connection.sendCommand(FLUSHDB, flushMode.getRaw()); + return connection.getStatusCodeReply(); + } + + /** + * Returns all the keys matching the glob-style pattern as space separated strings. For example if + * you have in the database the keys "foo" and "foobar" the command "KEYS foo*" will return + * "foo foobar". + *

+ * Note that while the time complexity for this operation is O(n) the constant times are pretty + * low. For example Redis running on an entry level laptop can scan a 1 million keys database in + * 40 milliseconds. Still it's better to consider this one of the slow commands that may ruin + * the DB performance if not used with care. + *

+ * In other words this command is intended only for debugging and special operations like creating + * a script to change the DB schema. Don't use it in your normal code. Use Redis Sets in order to + * group together a subset of objects. + *

+ * Glob style patterns examples: + *

    + *
  • h?llo will match hello hallo hhllo + *
  • h*llo will match hllo heeeello + *
  • h[ae]llo will match hello and hallo, but not hillo + *
+ *

+ * Use \ to escape special chars if you want to match them verbatim. + *

+ * Time complexity: O(n) (with n being the number of keys in the DB, and assuming keys and pattern + * of limited length) + * @param pattern + * @return Multi bulk reply + */ + @Override + public Set keys(final byte[] pattern) { checkIsInMultiOrPipeline(); - client.keys(pattern); - return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.keys(pattern)); } /** * Return a randomly selected key from the currently selected DB. *

* Time complexity: O(1) - * @return Singe line reply, specifically the randomly selected key or an empty string is the + * @return Single line reply, specifically the randomly selected key or an empty string is the * database is empty */ @Override - public String randomKey() { + public byte[] randomBinaryKey() { checkIsInMultiOrPipeline(); - client.randomKey(); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.randomBinaryKey()); } /** @@ -399,13 +599,12 @@ public String randomKey() { * Time complexity: O(1) * @param oldkey * @param newkey - * @return Status code repy + * @return Status code reply */ @Override - public String rename(final String oldkey, final String newkey) { + public String rename(final byte[] oldkey, final byte[] newkey) { checkIsInMultiOrPipeline(); - client.rename(oldkey, newkey); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.rename(oldkey, newkey)); } /** @@ -417,24 +616,34 @@ public String rename(final String oldkey, final String newkey) { * @return Integer reply, specifically: 1 if the key was renamed 0 if the target key already exist */ @Override - public long renamenx(final String oldkey, final String newkey) { + public long renamenx(final byte[] oldkey, final byte[] newkey) { checkIsInMultiOrPipeline(); - client.renamenx(oldkey, newkey); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.renamenx(oldkey, newkey)); + } + + /** + * Return the number of keys in the currently selected database. + * @return Integer reply + */ + @Override + public long dbSize() { + checkIsInMultiOrPipeline(); + connection.sendCommand(DBSIZE); + return connection.getIntegerReply(); } /** * Set a timeout on the specified key. After the timeout the key will be automatically deleted by * the server. A key with an associated timeout is said to be volatile in Redis terminology. *

- * Volatile keys are stored on disk like the other keys, the timeout is persistent too like all - * the other aspects of the dataset. Saving a dataset containing expires and stopping the server - * does not stop the flow of time as Redis stores on disk the time when the key will no longer be + * Volatile keys are stored on disk like the other keys, the timeout is persistent too like all the + * other aspects of the dataset. Saving a dataset containing expires and stopping the server does + * not stop the flow of time as Redis stores on disk the time when the key will no longer be * available as Unix time, and not the remaining seconds. *

* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire * set. It is also possible to undo the expire at all turning the key into a normal key using the - * {@link #persist(String) PERSIST} command. + * {@link #persist(byte[]) PERSIST} command. *

* Time complexity: O(1) * @see Expire Command @@ -445,16 +654,15 @@ public long renamenx(final String oldkey, final String newkey) { * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. */ @Override - public long expire(final String key, final long seconds) { + public long expire(final byte[] key, final long seconds) { checkIsInMultiOrPipeline(); - client.expire(key, seconds); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.expire(key, seconds)); } /** - * EXPIREAT works exactly like {@link #expire(String, int) EXPIRE} but instead to get the number - * of seconds representing the Time To Live of the key as a second argument (that is a relative - * way of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of + * EXPIREAT works exactly like {@link #expire(byte[], int) EXPIRE} but instead to get the number of + * seconds representing the Time To Live of the key as a second argument (that is a relative way + * of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of * seconds elapsed since 1 Gen 1970). *

* EXPIREAT was introduced in order to implement the Append Only File persistence mode so that @@ -464,7 +672,7 @@ public long expire(final String key, final long seconds) { *

* Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire * set. It is also possible to undo the expire at all turning the key into a normal key using the - * {@link #persist(String) PERSIST} command. + * {@link #persist(byte[]) PERSIST} command. *

* Time complexity: O(1) * @see Expire Command @@ -475,27 +683,24 @@ public long expire(final String key, final long seconds) { * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. */ @Override - public long expireAt(final String key, final long unixTime) { + public long expireAt(final byte[] key, final long unixTime) { checkIsInMultiOrPipeline(); - client.expireAt(key, unixTime); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.expireAt(key, unixTime)); } /** * The TTL command returns the remaining time to live in seconds of a key that has an - * {@link #expire(String, int) EXPIRE} set. This introspection capability allows a Redis client to - * check how many seconds a given key will continue to be part of the dataset. + * {@link #expire(byte[], int) EXPIRE} set. This introspection capability allows a Redis connection to + check how many seconds a given key will continue to be part of the dataset. * @param key * @return Integer reply, returns the remaining time to live in seconds of a key that has an - * EXPIRE. In Redis 2.6 or older, if the Key does not exists or does not have an - * associated expire, -1 is returned. In Redis 2.8 or newer, if the Key does not have an - * associated expire, -1 is returned or if the Key does not exists, -2 is returned. + * EXPIRE. If the Key does not exists or does not have an associated expire, -1 is + * returned. */ @Override - public long ttl(final String key) { + public long ttl(final byte[] key) { checkIsInMultiOrPipeline(); - client.ttl(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.ttl(key)); } /** @@ -505,17 +710,37 @@ public long ttl(final String key) { * @return Integer reply: The number of keys that were touched. */ @Override - public long touch(final String... keys) { + public long touch(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.touch(keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.touch(keys)); } @Override - public long touch(final String key) { + public long touch(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.touch(key)); + } + + /** + * Select the DB with having the specified zero-based numeric index. For default every new connection + connection is automatically selected to DB 0. + * @param index + * @return Status code reply + */ + @Override + public String select(final int index) { + checkIsInMultiOrPipeline(); + connection.sendCommand(SELECT, toByteArray(index)); + String statusCodeReply = connection.getStatusCodeReply(); + this.db = index; + return statusCodeReply; + } + + @Override + public String swapDB(final int index1, final int index2) { checkIsInMultiOrPipeline(); - client.touch(key); - return client.getIntegerReply(); + connection.sendCommand(SWAPDB, toByteArray(index1), toByteArray(index2)); + return connection.getStatusCodeReply(); } /** @@ -529,10 +754,35 @@ public long touch(final String key) { * already present on the target DB or was not found in the current DB. */ @Override - public long move(final String key, final int dbIndex) { + public long move(final byte[] key, final int dbIndex) { + checkIsInMultiOrPipeline(); + connection.sendCommand(MOVE, key, toByteArray(dbIndex)); + return connection.getIntegerReply(); + } + + /** + * Delete all the keys of all the existing databases, not just the currently selected one. This + * command never fails. + * @return Status code reply + */ + @Override + public String flushAll() { + checkIsInMultiOrPipeline(); + connection.sendCommand(FLUSHALL); + return connection.getStatusCodeReply(); + } + + /** + * Delete all the keys of all the existing databases, not just the currently selected one. This + * command never fails. + * @param flushMode + * @return Status code reply + */ + @Override + public String flushAll(FlushMode flushMode) { checkIsInMultiOrPipeline(); - client.move(key, dbIndex); - return client.getIntegerReply(); + connection.sendCommand(FLUSHALL, flushMode.getRaw()); + return connection.getStatusCodeReply(); } /** @@ -546,10 +796,9 @@ public long move(final String key, final int dbIndex) { * @return Bulk reply */ @Override - public String getSet(final String key, final String value) { + public byte[] getSet(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); - client.getSet(key, value); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.getSet(key, value)); } /** @@ -562,14 +811,13 @@ public String getSet(final String key, final String value) { * @return Multi bulk reply */ @Override - public List mget(final String... keys) { + public List mget(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.mget(keys); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.mget(keys)); } /** - * SETNX works exactly like {@link #set(String, String) SET} with the only difference that if the + * SETNX works exactly like {@link #set(byte[], byte[]) SET} with the only difference that if the * key already exists no operation is performed. SETNX actually means "SET if Not eXists". *

* Time complexity: O(1) @@ -578,15 +826,14 @@ public List mget(final String... keys) { * @return Integer reply, specifically: 1 if the key was set 0 if the key was not set */ @Override - public long setnx(final String key, final String value) { + public long setnx(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); - client.setnx(key, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.setnx(key, value)); } /** * The command is exactly equivalent to the following group of commands: - * {@link #set(String, String) SET} + {@link #expire(String, int) EXPIRE}. The operation is + * {@link #set(byte[], byte[]) SET} + {@link #expire(byte[], int) EXPIRE}. The operation is * atomic. *

* Time complexity: O(1) @@ -596,37 +843,35 @@ public long setnx(final String key, final String value) { * @return Status code reply */ @Override - public String setex(final String key, final long seconds, final String value) { + public String setex(final byte[] key, final long seconds, final byte[] value) { checkIsInMultiOrPipeline(); - client.setex(key, seconds, value); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.setex(key, seconds, value)); } /** * Set the the respective keys to the respective values. MSET will replace old values with new - * values, while {@link #msetnx(String...) MSETNX} will not perform any operation at all even if + * values, while {@link Jedis#msetnx(byte[][]) MSETNX} will not perform any operation at all even if * just a single key already exists. *

* Because of this semantic MSETNX can be used in order to set different keys representing * different fields of an unique logic object in a way that ensures that either all the fields or * none at all are set. *

- * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B - * are modified, another client talking to Redis can either see the changes to both A and B at - * once, or no modification at all. - * @see #msetnx(String...) + Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B + are modified, another connection talking to Redis can either see the changes to both A and B at + once, or no modification at all. + * @see Jedis#msetnx(byte[][]) * @param keysvalues * @return Status code reply Basically +OK as MSET can't fail */ @Override - public String mset(final String... keysvalues) { + public String mset(final byte[]... keysvalues) { checkIsInMultiOrPipeline(); - client.mset(keysvalues); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.mset(keysvalues)); } /** - * Set the the respective keys to the respective values. {@link #mset(String...) MSET} will + * Set the the respective keys to the respective values. {@link Jedis#mset(byte[][]) MSET} will * replace old values with new values, while MSETNX will not perform any operation at all even if * just a single key already exists. *

@@ -634,24 +879,23 @@ public String mset(final String... keysvalues) { * different fields of an unique logic object in a way that ensures that either all the fields or * none at all are set. *

- * Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B - * are modified, another client talking to Redis can either see the changes to both A and B at - * once, or no modification at all. - * @see #mset(String...) + Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B + are modified, another connection talking to Redis can either see the changes to both A and B at + once, or no modification at all. + * @see Jedis#mset(byte[][]) * @param keysvalues * @return Integer reply, specifically: 1 if the all the keys were set 0 if no key was set (at * least one key already existed) */ @Override - public long msetnx(final String... keysvalues) { + public long msetnx(final byte[]... keysvalues) { checkIsInMultiOrPipeline(); - client.msetnx(keysvalues); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.msetnx(keysvalues)); } /** - * IDECRBY work just like {@link #decr(String) INCR} but instead to decrement by 1 the decrement - * is integer. + * DECRBY work just like {@link #decr(byte[]) INCR} but instead to decrement by 1 the decrement is + * integer. *

* INCR commands are limited to 64 bit signed integers. *

@@ -660,18 +904,17 @@ public long msetnx(final String... keysvalues) { * and then converted back as a string. *

* Time complexity: O(1) - * @see #incr(String) - * @see #decr(String) - * @see #incrBy(String, long) + * @see #incr(byte[]) + * @see #decr(byte[]) + * @see #incrBy(byte[], long) * @param key * @param decrement * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override - public long decrBy(final String key, final long decrement) { + public long decrBy(final byte[] key, final long decrement) { checkIsInMultiOrPipeline(); - client.decrBy(key, decrement); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.decrBy(key, decrement)); } /** @@ -685,21 +928,20 @@ public long decrBy(final String key, final long decrement) { * and then converted back as a string. *

* Time complexity: O(1) - * @see #incr(String) - * @see #incrBy(String, long) - * @see #decrBy(String, long) + * @see #incr(byte[]) + * @see #incrBy(byte[], long) + * @see #decrBy(byte[], long) * @param key * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override - public long decr(final String key) { + public long decr(final byte[] key) { checkIsInMultiOrPipeline(); - client.decr(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.decr(key)); } /** - * INCRBY work just like {@link #incr(String) INCR} but instead to increment by 1 the increment is + * INCRBY work just like {@link #incr(byte[]) INCR} but instead to increment by 1 the increment is * integer. *

* INCR commands are limited to 64 bit signed integers. @@ -709,22 +951,22 @@ public long decr(final String key) { * and then converted back as a string. *

* Time complexity: O(1) - * @see #incr(String) - * @see #decr(String) - * @see #decrBy(String, long) + * @see #incr(byte[]) + * @see #decr(byte[]) + * @see #decrBy(byte[], long) * @param key * @param increment * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override - public long incrBy(final String key, final long increment) { + public long incrBy(final byte[] key, final long increment) { checkIsInMultiOrPipeline(); - client.incrBy(key, increment); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.incrBy(key, increment)); } /** - * INCRBYFLOAT + * INCRBYFLOAT work just like {@link #incrBy(byte[], long)} INCRBY} but increments by floats + * instead of integers. *

* INCRBYFLOAT commands are limited to double precision floating point values. *

@@ -734,15 +976,17 @@ public long incrBy(final String key, final long increment) { * negative value will work as expected. *

* Time complexity: O(1) - * @param key - * @param increment - * @return Double reply, this commands will reply with the new value of key after the increment. + * @see #incr(byte[]) + * @see #decr(byte[]) + * @see #decrBy(byte[], long) + * @param key the key to increment + * @param increment the value to increment by + * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override - public double incrByFloat(final String key, final double increment) { + public double incrByFloat(final byte[] key, final double increment) { checkIsInMultiOrPipeline(); - client.incrByFloat(key, increment); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.incrByFloat(key, increment)); } /** @@ -756,17 +1000,16 @@ public double incrByFloat(final String key, final double increment) { * and then converted back as a string. *

* Time complexity: O(1) - * @see #incrBy(String, long) - * @see #decr(String) - * @see #decrBy(String, long) + * @see #incrBy(byte[], long) + * @see #decr(byte[]) + * @see #decrBy(byte[], long) * @param key * @return Integer reply, this commands will reply with the new value of key after the increment. */ @Override - public long incr(final String key) { + public long incr(final byte[] key) { checkIsInMultiOrPipeline(); - client.incr(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.incr(key)); } /** @@ -782,10 +1025,9 @@ public long incr(final String key) { * @return Integer reply, specifically the total length of the string after the append operation. */ @Override - public long append(final String key, final String value) { + public long append(final byte[] key, final byte[] value) { checkIsInMultiOrPipeline(); - client.append(key, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.append(key, value)); } /** @@ -805,10 +1047,9 @@ public long append(final String key, final String value) { * @return Bulk reply */ @Override - public String substr(final String key, final int start, final int end) { + public byte[] substr(final byte[] key, final int start, final int end) { checkIsInMultiOrPipeline(); - client.substr(key, start, end); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.substr(key, start, end)); } /** @@ -824,17 +1065,15 @@ public String substr(final String key, final int start, final int end) { * returned, otherwise if a new field is created 1 is returned. */ @Override - public long hset(final String key, final String field, final String value) { + public long hset(final byte[] key, final byte[] field, final byte[] value) { checkIsInMultiOrPipeline(); - client.hset(key, field, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hset(key, field, value)); } @Override - public long hset(final String key, final Map hash) { + public long hset(final byte[] key, final Map hash) { checkIsInMultiOrPipeline(); - client.hset(key, hash); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hset(key, hash)); } /** @@ -848,10 +1087,9 @@ public long hset(final String key, final Map hash) { * @return Bulk reply */ @Override - public String hget(final String key, final String field) { + public byte[] hget(final byte[] key, final byte[] field) { checkIsInMultiOrPipeline(); - client.hget(key, field); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.hget(key, field)); } /** @@ -864,10 +1102,9 @@ public String hget(final String key, final String field) { * returned. */ @Override - public long hsetnx(final String key, final String field, final String value) { + public long hsetnx(final byte[] key, final byte[] field, final byte[] value) { checkIsInMultiOrPipeline(); - client.hsetnx(key, field, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hsetnx(key, field, value)); } /** @@ -878,13 +1115,12 @@ public long hsetnx(final String key, final String field, final String value) { * Time complexity: O(N) (with N being the number of fields) * @param key * @param hash - * @return Return OK or Exception if hash is empty + * @return Always OK because HMSET can't fail */ @Override - public String hmset(final String key, final Map hash) { + public String hmset(final byte[] key, final Map hash) { checkIsInMultiOrPipeline(); - client.hmset(key, hash); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.hmset(key, hash)); } /** @@ -900,10 +1136,9 @@ public String hmset(final String key, final Map hash) { * fields, in the same order of the request. */ @Override - public List hmget(final String key, final String... fields) { + public List hmget(final byte[] key, final byte[]... fields) { checkIsInMultiOrPipeline(); - client.hmget(key, fields); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.hmget(key, fields)); } /** @@ -921,10 +1156,9 @@ public List hmget(final String key, final String... fields) { * @return Integer reply The new value at field after the increment operation. */ @Override - public long hincrBy(final String key, final String field, final long value) { + public long hincrBy(final byte[] key, final byte[] field, final long value) { checkIsInMultiOrPipeline(); - client.hincrBy(key, field, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hincrBy(key, field, value)); } /** @@ -944,10 +1178,9 @@ public long hincrBy(final String key, final String field, final long value) { * operation. */ @Override - public double hincrByFloat(final String key, final String field, final double value) { + public double hincrByFloat(final byte[] key, final byte[] field, final double value) { checkIsInMultiOrPipeline(); - client.hincrByFloat(key, field, value); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.hincrByFloat(key, field, value)); } /** @@ -958,10 +1191,9 @@ public double hincrByFloat(final String key, final String field, final double va * not found or the field is not present. */ @Override - public boolean hexists(final String key, final String field) { + public boolean hexists(final byte[] key, final byte[] field) { checkIsInMultiOrPipeline(); - client.hexists(key, field); - return client.getIntegerReply() == 1; + return connection.executeCommand(commandObjects.hexists(key, field)); } /** @@ -974,10 +1206,9 @@ public boolean hexists(final String key, final String field) { * returned and no operation is performed. */ @Override - public long hdel(final String key, final String... fields) { + public long hdel(final byte[] key, final byte[]... fields) { checkIsInMultiOrPipeline(); - client.hdel(key, fields); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hdel(key, fields)); } /** @@ -989,10 +1220,9 @@ public long hdel(final String key, final String... fields) { * key does not exist, 0 is returned assuming an empty hash. */ @Override - public long hlen(final String key) { + public long hlen(final byte[] key) { checkIsInMultiOrPipeline(); - client.hlen(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hlen(key)); } /** @@ -1003,10 +1233,9 @@ public long hlen(final String key) { * @return All the fields names contained into a hash. */ @Override - public Set hkeys(final String key) { + public Set hkeys(final byte[] key) { checkIsInMultiOrPipeline(); - client.hkeys(key); - return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.hkeys(key)); } /** @@ -1017,10 +1246,9 @@ public Set hkeys(final String key) { * @return All the fields values contained into a hash. */ @Override - public List hvals(final String key) { + public List hvals(final byte[] key) { checkIsInMultiOrPipeline(); - client.hvals(key); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.hvals(key)); } /** @@ -1031,10 +1259,9 @@ public List hvals(final String key) { * @return All the fields and values contained into a hash. */ @Override - public Map hgetAll(final String key) { + public Map hgetAll(final byte[] key) { checkIsInMultiOrPipeline(); - client.hgetAll(key); - return BuilderFactory.STRING_MAP.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.hgetAll(key)); } /** @@ -1045,10 +1272,9 @@ public Map hgetAll(final String key) { * @return one random field from a hash. */ @Override - public String hrandfield(final String key) { + public byte[] hrandfield(final byte[] key) { checkIsInMultiOrPipeline(); - client.hrandfield(key); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.hrandfield(key)); } /** @@ -1056,14 +1282,12 @@ public String hrandfield(final String key) { *

* Time complexity: O(N), where N is the number of fields returned * @param key - * @param count * @return multiple random fields from a hash. */ @Override - public List hrandfield(final String key, final long count) { + public List hrandfield(final byte[] key, final long count) { checkIsInMultiOrPipeline(); - client.hrandfield(key, count); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.hrandfield(key, count)); } /** @@ -1071,14 +1295,12 @@ public List hrandfield(final String key, final long count) { *

* Time complexity: O(N), where N is the number of fields returned * @param key - * @param count * @return one or multiple random fields with values from a hash. */ @Override - public Map hrandfieldWithValues(final String key, final long count) { + public Map hrandfieldWithValues(final byte[] key, final long count) { checkIsInMultiOrPipeline(); - client.hrandfieldWithValues(key, count); - return BuilderFactory.STRING_MAP.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.hrandfieldWithValues(key, count)); } /** @@ -1093,10 +1315,9 @@ public Map hrandfieldWithValues(final String key, final long cou * operation. */ @Override - public long rpush(final String key, final String... strings) { + public long rpush(final byte[] key, final byte[]... strings) { checkIsInMultiOrPipeline(); - client.rpush(key, strings); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.rpush(key, strings)); } /** @@ -1111,10 +1332,9 @@ public long rpush(final String key, final String... strings) { * operation. */ @Override - public long lpush(final String key, final String... strings) { + public long lpush(final byte[] key, final byte[]... strings) { checkIsInMultiOrPipeline(); - client.lpush(key, strings); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.lpush(key, strings)); } /** @@ -1127,10 +1347,9 @@ public long lpush(final String key, final String... strings) { * @return The length of the list. */ @Override - public long llen(final String key) { + public long llen(final byte[] key) { checkIsInMultiOrPipeline(); - client.llen(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.llen(key)); } /** @@ -1166,10 +1385,9 @@ public long llen(final String key) { * @return Multi bulk reply, specifically a list of elements in the specified range. */ @Override - public List lrange(final String key, final long start, final long stop) { + public List lrange(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.lrange(key, start, stop); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.lrange(key, start, stop)); } /** @@ -1203,10 +1421,9 @@ public List lrange(final String key, final long start, final long stop) * @return Status code reply */ @Override - public String ltrim(final String key, final long start, final long stop) { + public String ltrim(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.ltrim(key, start, stop); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.ltrim(key, start, stop)); } /** @@ -1226,10 +1443,9 @@ public String ltrim(final String key, final long start, final long stop) { * @return Bulk reply, specifically the requested element */ @Override - public String lindex(final String key, final long index) { + public byte[] lindex(final byte[] key, final long index) { checkIsInMultiOrPipeline(); - client.lindex(key, index); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.lindex(key, index)); } /** @@ -1245,17 +1461,16 @@ public String lindex(final String key, final long index) { *

* O(N) (with N being the length of the list), setting the first or last elements of the list is * O(1). - * @see #lindex(String, long) + * @see #lindex(byte[], long) * @param key * @param index * @param value * @return Status code reply */ @Override - public String lset(final String key, final long index, final String value) { + public String lset(final byte[] key, final long index, final byte[] value) { checkIsInMultiOrPipeline(); - client.lset(key, index, value); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.lset(key, index, value)); } /** @@ -1274,10 +1489,9 @@ public String lset(final String key, final long index, final String value) { * @return Integer Reply, specifically: The number of removed elements if the operation succeeded */ @Override - public long lrem(final String key, final long count, final String value) { + public long lrem(final byte[] key, final long count, final byte[] value) { checkIsInMultiOrPipeline(); - client.lrem(key, count, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.lrem(key, count, value)); } /** @@ -1286,68 +1500,104 @@ public long lrem(final String key, final long count, final String value) { * "b","c". *

* If the key does not exist or the list is already empty the special value 'nil' is returned. - * @see #rpop(String) + * @see #rpop(byte[]) * @param key * @return Bulk reply */ @Override - public String lpop(final String key) { + public byte[] lpop(final byte[] key) { checkIsInMultiOrPipeline(); - client.lpop(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.lpop(key)); } @Override - public List lpop(final String key, final int count) { + public List lpop(final byte[] key, final int count) { checkIsInMultiOrPipeline(); - client.lpop(key, count); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.lpop(key, count)); } + /** + * Returns the index of the first matching element inside a redis list. If the element is found, + * its index (the zero-based position in the list) is returned. Otherwise, if no match is found, + * 'nil' is returned. + *

+ * Time complexity: O(N) where N is the number of elements in the list + * @see #lpos(byte[], byte[]) + * @param key + * @param element + * @return Integer Reply, specifically: The index of first matching element in the list. Value will + * be 'nil' when the element is not present in the list. + */ @Override - public Long lpos(final String key, final String element) { + public Long lpos(final byte[] key, final byte[] element) { checkIsInMultiOrPipeline(); - client.lpos(key, element); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.lpos(key, element)); } + /** + * In case there are multiple matches Rank option specifies the "rank" of the element to return. + * A rank of 1 returns the first match, 2 to return the second match, and so forth. + * If list `foo` has elements ("a","b","c","1","2","3","c","c"), The function call to get the + * index of second occurrence of "c" will be as follows lpos("foo","c", LPosParams.lPosParams().rank(2)). + *

+ * Maxlen option compares the element provided only with a given maximum number of list items. + * A value of 1000 will make sure that the command performs only 1000 comparisons. The + * comparison is made for the first part or the last part depending on the fact we use a positive or + * negative rank. + * Following is how we could use the Maxlen option lpos("foo", "b", LPosParams.lPosParams().rank(1).maxlen(2)). + * @see #lpos(byte[], byte[], LPosParams) + * @param key + * @param element + * @param params + * @return Integer Reply + */ @Override - public Long lpos(final String key, final String element, final LPosParams params) { + public Long lpos(final byte[] key, final byte[] element, final LPosParams params) { checkIsInMultiOrPipeline(); - client.lpos(key, element, params); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.lpos(key, element, params)); } + /** + * Count will return list of position of all the first N matching elements. It is possible to + * specify 0 as the number of matches, as a way to tell the command we want all the matches + * found returned as an array of indexes. When count is used and no match is found, an empty list + * is returned. + *

+ * Time complexity: O(N) where N is the number of elements in the list + * @see #lpos(byte[], byte[], LPosParams, long) + * @param key + * @param element + * @param params + * @param count + * @return Returns value will be a list containing position of the matching elements inside the list. + */ @Override - public List lpos(final String key, final String element, final LPosParams params, + public List lpos(final byte[] key, final byte[] element, final LPosParams params, final long count) { checkIsInMultiOrPipeline(); - client.lpos(key, element, params, count); - return client.getIntegerMultiBulkReply(); + return connection.executeCommand(commandObjects.lpos(key, element, params, count)); } /** * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example - * if the list contains the elements "a","b","c" RPOP will return "c" and the list will become - * "a","b". + * if the list contains the elements "a","b","c" LPOP will return "a" and the list will become + * "b","c". *

* If the key does not exist or the list is already empty the special value 'nil' is returned. - * @see #lpop(String) + * @see #lpop(byte[]) * @param key * @return Bulk reply */ @Override - public String rpop(final String key) { + public byte[] rpop(final byte[] key) { checkIsInMultiOrPipeline(); - client.rpop(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.rpop(key)); } @Override - public List rpop(final String key, final int count) { + public List rpop(final byte[] key, final int count) { checkIsInMultiOrPipeline(); - client.rpop(key, count); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.rpop(key, count)); } /** @@ -1366,10 +1616,9 @@ public List rpop(final String key, final int count) { * @return Bulk reply */ @Override - public String rpoplpush(final String srckey, final String dstkey) { + public byte[] rpoplpush(final byte[] srckey, final byte[] dstkey) { checkIsInMultiOrPipeline(); - client.rpoplpush(srckey, dstkey); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.rpoplpush(srckey, dstkey)); } /** @@ -1384,26 +1633,23 @@ public String rpoplpush(final String srckey, final String dstkey) { * already a member of the set */ @Override - public long sadd(final String key, final String... members) { + public long sadd(final byte[] key, final byte[]... members) { checkIsInMultiOrPipeline(); - client.sadd(key, members); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.sadd(key, members)); } /** * Return all the members (elements) of the set value stored at key. This is just syntax glue for - * {@link #sinter(String...) SINTER}. + * {@link #sinter(byte[]...)} SINTER}. *

* Time complexity O(N) - * @param key + * @param key the key of the set * @return Multi bulk reply */ @Override - public Set smembers(final String key) { + public Set smembers(final byte[] key) { checkIsInMultiOrPipeline(); - client.smembers(key); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.smembers(key)); } /** @@ -1411,23 +1657,22 @@ public Set smembers(final String key) { * set no operation is performed. If key does not hold a set value an error is returned. *

* Time complexity O(1) - * @param key - * @param members + * @param key the key of the set + * @param member the set member to remove * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was * not a member of the set */ @Override - public long srem(final String key, final String... members) { + public long srem(final byte[] key, final byte[]... member) { checkIsInMultiOrPipeline(); - client.srem(key, members); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.srem(key, member)); } /** * Remove a random element from a Set returning it as return value. If the Set is empty or the key * does not exist, a nil object is returned. *

- * The {@link #srandmember(String)} command does a similar work but the returned element is not + * The {@link #srandmember(byte[])} command does a similar work but the returned element is not * removed from the Set. *

* Time complexity O(1) @@ -1435,19 +1680,15 @@ public long srem(final String key, final String... members) { * @return Bulk reply */ @Override - public String spop(final String key) { + public byte[] spop(final byte[] key) { checkIsInMultiOrPipeline(); - client.spop(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.spop(key)); } @Override - public Set spop(final String key, final long count) { + public Set spop(final byte[] key, final long count) { checkIsInMultiOrPipeline(); - client.spop(key, count); - final List members = client.getMultiBulkReply(); - if (members == null) return null; - return SetFromList.of(members); + return connection.executeCommand(commandObjects.spop(key, count)); } /** @@ -1470,10 +1711,9 @@ public Set spop(final String key, final long count) { * on the first set and no operation was performed */ @Override - public long smove(final String srckey, final String dstkey, final String member) { + public long smove(final byte[] srckey, final byte[] dstkey, final byte[] member) { checkIsInMultiOrPipeline(); - client.smove(srckey, dstkey, member); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.smove(srckey, dstkey, member)); } /** @@ -1484,10 +1724,9 @@ public long smove(final String srckey, final String dstkey, final String member) * integer. */ @Override - public long scard(final String key) { + public long scard(final byte[] key) { checkIsInMultiOrPipeline(); - client.scard(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.scard(key)); } /** @@ -1496,14 +1735,13 @@ public long scard(final String key) { * Time complexity O(1) * @param key * @param member - * @return Boolean reply, specifically: true if the element is a member of the set false if the - * element is not a member of the set OR if the key does not exist + * @return Boolean reply, specifically: true if the element is a member of the set false if the element + * is not a member of the set OR if the key does not exist */ @Override - public boolean sismember(final String key, final String member) { + public boolean sismember(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); - client.sismember(key, member); - return client.getIntegerReply() == 1; + return connection.executeCommand(commandObjects.sismember(key, member)); } /** @@ -1512,22 +1750,20 @@ public boolean sismember(final String key, final String member) { * Time complexity O(N) where N is the number of elements being checked for membership * @param key * @param members - * @return List representing the membership of the given elements, in the same order as they are - * requested. + * @return List representing the membership of the given elements, in the same order as they are requested. */ @Override - public List smismember(final String key, final String... members) { + public List smismember(final byte[] key, final byte[]... members) { checkIsInMultiOrPipeline(); - client.smismember(key, members); - return BuilderFactory.BOOLEAN_LIST.build(client.getIntegerMultiBulkReply()); + return connection.executeCommand(commandObjects.smismember(key, members)); } /** * Return the members of a set resulting from the intersection of all the sets hold at the - * specified keys. Like in {@link #lrange(String, long, long) LRANGE} the result is sent to the - * client as a multi-bulk reply (see the protocol specification for more information). If just a - * single key is specified, then this command produces the same result as - * {@link #smembers(String) SMEMBERS}. Actually SMEMBERS is just syntax sugar for SINTER. + * specified keys. Like in {@link #lrange(byte[], long, long)} LRANGE} the result is sent to the + connection as a multi-bulk reply (see the protocol specification for more information). If just a + single key is specified, then this command produces the same result as + {@link #smembers(byte[]) SMEMBERS}. Actually SMEMBERS is just syntax sugar for SINTER. *

* Non existing keys are considered like empty sets, so if one of the keys is missing an empty set * is returned (since the intersection with an empty set always is an empty set). @@ -1538,15 +1774,13 @@ public List smismember(final String key, final String... members) { * @return Multi bulk reply, specifically the list of common elements. */ @Override - public Set sinter(final String... keys) { + public Set sinter(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.sinter(keys); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.sinter(keys)); } /** - * This command works exactly like {@link #sinter(String...) SINTER} but instead of being returned + * This commanad works exactly like {@link #sinter(byte[]...) SINTER} but instead of being returned * the resulting set is stored as dstkey. *

* Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the @@ -1556,17 +1790,16 @@ public Set sinter(final String... keys) { * @return Status code reply */ @Override - public long sinterstore(final String dstkey, final String... keys) { + public long sinterstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); - client.sinterstore(dstkey, keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.sinterstore(dstkey, keys)); } /** * Return the members of a set resulting from the union of all the sets hold at the specified - * keys. Like in {@link #lrange(String, long, long) LRANGE} the result is sent to the client as a - * multi-bulk reply (see the protocol specification for more information). If just a single key is - * specified, then this command produces the same result as {@link #smembers(String) SMEMBERS}. + * keys. Like in {@link #lrange(byte[], long, long)} LRANGE} the result is sent to the connection as a + multi-bulk reply (see the protocol specification for more information). If just a single key is + specified, then this command produces the same result as {@link #smembers(byte[]) SMEMBERS}. *

* Non existing keys are considered like empty sets. *

@@ -1575,15 +1808,13 @@ public long sinterstore(final String dstkey, final String... keys) { * @return Multi bulk reply, specifically the list of common elements. */ @Override - public Set sunion(final String... keys) { + public Set sunion(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.sunion(keys); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.sunion(keys)); } /** - * This command works exactly like {@link #sunion(String...) SUNION} but instead of being returned + * This command works exactly like {@link #sunion(byte[]...) SUNION} but instead of being returned * the resulting set is stored as dstkey. Any existing value in dstkey will be over-written. *

* Time complexity O(N) where N is the total number of elements in all the provided sets @@ -1592,10 +1823,9 @@ public Set sunion(final String... keys) { * @return Status code reply */ @Override - public long sunionstore(final String dstkey, final String... keys) { + public long sunionstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); - client.sunionstore(dstkey, keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.sunionstore(dstkey, keys)); } /** @@ -1620,24 +1850,22 @@ public long sunionstore(final String dstkey, final String... keys) { * provided and all the successive sets. */ @Override - public Set sdiff(final String... keys) { + public Set sdiff(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.sdiff(keys); - return BuilderFactory.STRING_SET.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.sdiff(keys)); } /** - * This command works exactly like {@link #sdiff(String...) SDIFF} but instead of being returned + * This command works exactly like {@link Jedis#sdiff(byte[][]) SDIFF} but instead of being returned * the resulting set is stored in dstkey. * @param dstkey * @param keys * @return Status code reply */ @Override - public long sdiffstore(final String dstkey, final String... keys) { + public long sdiffstore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); - client.sdiffstore(dstkey, keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.sdiffstore(dstkey, keys)); } /** @@ -1651,30 +1879,15 @@ public long sdiffstore(final String dstkey, final String... keys) { * @return Bulk reply */ @Override - public String srandmember(final String key) { + public byte[] srandmember(final byte[] key) { checkIsInMultiOrPipeline(); - client.srandmember(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.srandmember(key)); } - /** - * Return a random elements from a Set, without removing the elements. If the Set is empty or the - * key does not exist, an empty list is returned. - *

- * The SPOP command does a similar work but the returned elements is popped (removed) from the Set. - *

- * Time complexity O(1) - * @param key - * @param count if positive, return an array of distinct elements. - * If negative the behavior changes and the command is allowed to - * return the same element multiple times - * @return list of elements - */ @Override - public List srandmember(final String key, final int count) { + public List srandmember(final byte[] key, final int count) { checkIsInMultiOrPipeline(); - client.srandmember(key, count); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.srandmember(key, count)); } /** @@ -1694,68 +1907,40 @@ public List srandmember(final String key, final int count) { * already a member of the sorted set and the score was updated */ @Override - public long zadd(final String key, final double score, final String member) { + public long zadd(final byte[] key, final double score, final byte[] member) { checkIsInMultiOrPipeline(); - client.zadd(key, score, member); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zadd(key, score, member)); } @Override - public long zadd(final String key, final double score, final String member, + public long zadd(final byte[] key, final double score, final byte[] member, final ZAddParams params) { checkIsInMultiOrPipeline(); - client.zadd(key, score, member, params); - return client.getIntegerReply(); - } - - @Override - public long zadd(final String key, final Map scoreMembers) { - checkIsInMultiOrPipeline(); - client.zadd(key, scoreMembers); - return client.getIntegerReply(); - } - - @Override - public long zadd(final String key, final Map scoreMembers, final ZAddParams params) { - checkIsInMultiOrPipeline(); - client.zadd(key, scoreMembers, params); - return client.getIntegerReply(); - } - - @Override - public Double zaddIncr(final String key, final double score, final String member, final ZAddParams params) { - checkIsInMultiOrPipeline(); - client.zaddIncr(key, score, member, params); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.zadd(key, score, member, params)); } @Override - public Set zdiff(String... keys) { + public long zadd(final byte[] key, final Map scoreMembers) { checkIsInMultiOrPipeline(); - client.zdiff(keys); - return SetFromList.of(client.getMultiBulkReply()); + return connection.executeCommand(commandObjects.zadd(key, scoreMembers)); } @Override - public Set zdiffWithScores(String... keys) { + public long zadd(final byte[] key, final Map scoreMembers, final ZAddParams params) { checkIsInMultiOrPipeline(); - client.zdiffWithScores(keys); - return getTupledSet(); + return connection.executeCommand(commandObjects.zadd(key, scoreMembers, params)); } @Override - public long zdiffStore(final String dstkey, final String... keys) { + public Double zaddIncr(final byte[] key, final double score, final byte[] member, final ZAddParams params) { checkIsInMultiOrPipeline(); - client.zdiffStore(dstkey, keys); - return BuilderFactory.LONG.build(client.getOne()); + return connection.executeCommand(commandObjects.zaddIncr(key, score, member, params)); } @Override - public Set zrange(final String key, final long start, final long stop) { + public List zrange(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.zrange(key, start, stop); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrange(key, start, stop)); } /** @@ -1770,10 +1955,9 @@ public Set zrange(final String key, final long start, final long stop) { * not a member of the set */ @Override - public long zrem(final String key, final String... members) { + public long zrem(final byte[] key, final byte[]... members) { checkIsInMultiOrPipeline(); - client.zrem(key, members); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zrem(key, members)); } /** @@ -1795,22 +1979,20 @@ public long zrem(final String key, final String... members) { * @return The new score */ @Override - public double zincrby(final String key, final double increment, final String member) { + public double zincrby(final byte[] key, final double increment, final byte[] member) { checkIsInMultiOrPipeline(); - client.zincrby(key, increment, member); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.zincrby(key, increment, member)); } @Override - public Double zincrby(final String key, final double increment, final String member, + public Double zincrby(final byte[] key, final double increment, final byte[] member, final ZIncrByParams params) { checkIsInMultiOrPipeline(); - client.zincrby(key, increment, member, params); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.zincrby(key, increment, member, params)); } /** - * Return the rank (or index) of member in the sorted set at key, with scores being ordered from + * Return the rank (or index) or member in the sorted set at key, with scores being ordered from * low to high. *

* When the given member does not exist in the sorted set, the special value 'nil' is returned. @@ -1819,21 +2001,20 @@ public Double zincrby(final String key, final double increment, final String mem * Time complexity: *

* O(log(N)) - * @see #zrevrank(String, String) + * @see #zrevrank(byte[], byte[]) * @param key * @param member * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer * reply if the element exists. A nil bulk reply if there is no such element. */ @Override - public Long zrank(final String key, final String member) { + public Long zrank(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); - client.zrank(key, member); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zrank(key, member)); } /** - * Return the rank (or index) of member in the sorted set at key, with scores being ordered from + * Return the rank (or index) or member in the sorted set at key, with scores being ordered from * high to low. *

* When the given member does not exist in the sorted set, the special value 'nil' is returned. @@ -1842,61 +2023,52 @@ public Long zrank(final String key, final String member) { * Time complexity: *

* O(log(N)) - * @see #zrank(String, String) + * @see #zrank(byte[], byte[]) * @param key * @param member * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer * reply if the element exists. A nil bulk reply if there is no such element. */ @Override - public Long zrevrank(final String key, final String member) { + public Long zrevrank(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); - client.zrevrank(key, member); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zrevrank(key, member)); } @Override - public Set zrevrange(final String key, final long start, final long stop) { + public List zrevrange(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.zrevrange(key, start, stop); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrange(key, start, stop)); } @Override - public Set zrangeWithScores(final String key, final long start, final long stop) { + public List zrangeWithScores(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.zrangeWithScores(key, start, stop); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrangeWithScores(key, start, stop)); } @Override - public Set zrevrangeWithScores(final String key, final long start, final long stop) { + public List zrevrangeWithScores(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.zrevrangeWithScores(key, start, stop); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrevrangeWithScores(key, start, stop)); } @Override - public String zrandmember(final String key) { + public byte[] zrandmember(final byte[] key) { checkIsInMultiOrPipeline(); - client.zrandmember(key); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.zrandmember(key)); } @Override - public Set zrandmember(final String key, final long count) { + public List zrandmember(final byte[] key, final long count) { checkIsInMultiOrPipeline(); - client.zrandmember(key, count); - final List members = client.getMultiBulkReply(); - return members == null ? null : SetFromList.of(members); + return connection.executeCommand(commandObjects.zrandmember(key, count)); } @Override - public Set zrandmemberWithScores(final String key, final long count) { + public List zrandmemberWithScores(final byte[] key, final long count) { checkIsInMultiOrPipeline(); - client.zrandmemberWithScores(key, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrandmemberWithScores(key, count)); } /** @@ -1908,10 +2080,9 @@ public Set zrandmemberWithScores(final String key, final long count) { * @return the cardinality (number of elements) of the set as an integer. */ @Override - public long zcard(final String key) { + public long zcard(final byte[] key) { checkIsInMultiOrPipeline(); - client.zcard(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zcard(key)); } /** @@ -1925,15 +2096,14 @@ public long zcard(final String key) { * @return the score */ @Override - public Double zscore(final String key, final String member) { + public Double zscore(final byte[] key, final byte[] member) { checkIsInMultiOrPipeline(); - client.zscore(key, member); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.zscore(key, member)); } /** - * Returns the scores associated with the specified members in the sorted set stored at key. For - * every member that does not exist in the sorted set, a nil value is returned. + * Returns the scores associated with the specified members in the sorted set stored at key. + * For every member that does not exist in the sorted set, a nil value is returned. *

* Time complexity: O(N) where N is the number of members being requested. * @param key @@ -1941,45 +2111,48 @@ public Double zscore(final String key, final String member) { * @return the scores */ @Override - public List zmscore(final String key, final String... members) { + public List zmscore(final byte[] key, final byte[]... members) { checkIsInMultiOrPipeline(); - client.zmscore(key, members); - return BuilderFactory.DOUBLE_LIST.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.zmscore(key, members)); } @Override - public Tuple zpopmax(final String key) { + public Tuple zpopmax(final byte[] key) { checkIsInMultiOrPipeline(); - client.zpopmax(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.zpopmax(key)); } @Override - public Set zpopmax(final String key, final int count) { + public List zpopmax(final byte[] key, final int count) { checkIsInMultiOrPipeline(); - client.zpopmax(key, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zpopmax(key, count)); } @Override - public Tuple zpopmin(final String key) { + public Tuple zpopmin(final byte[] key) { checkIsInMultiOrPipeline(); - client.zpopmin(key); - return BuilderFactory.TUPLE.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.zpopmin(key)); } @Override - public Set zpopmin(final String key, final int count) { + public List zpopmin(final byte[] key, final int count) { checkIsInMultiOrPipeline(); - client.zpopmin(key, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zpopmin(key, count)); } - @Override - public String watch(final String... keys) { + public String watch(final byte[]... keys) { + checkIsInMultiOrPipeline(); + connection.sendCommand(WATCH, keys); +// return connection.getStatusCodeReply(); + String status = connection.getStatusCodeReply(); + isInWatch = true; + return status; + } + + public String unwatch() { checkIsInMultiOrPipeline(); - client.watch(keys); - return client.getStatusCodeReply(); + connection.sendCommand(UNWATCH); + return connection.getStatusCodeReply(); } /** @@ -1988,18 +2161,17 @@ public String watch(final String... keys) { * Sort the elements contained in the List, Set, or Sorted Set value at key. By default sorting is * numeric with elements being compared as double precision floating point numbers. This is the * simplest form of SORT. - * @see #sort(String, String) - * @see #sort(String, SortingParams) - * @see #sort(String, SortingParams, String) + * @see #sort(byte[], byte[]) + * @see #sort(byte[], SortingParams) + * @see #sort(byte[], SortingParams, byte[]) * @param key * @return Assuming the Set/List at key contains a list of numbers, the return value will be the * list of numbers ordered from the smallest to the biggest number. */ @Override - public List sort(final String key) { + public List sort(final byte[] key) { checkIsInMultiOrPipeline(); - client.sort(key); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.sort(key)); } /** @@ -2070,34 +2242,32 @@ public List sort(final String key) { * sort(x, sp.by(w*).get(#).get(k*)) * -> [3, x, 2, y, 1, z] * - * @see #sort(String) - * @see #sort(String, SortingParams, String) + * @see #sort(byte[]) + * @see #sort(byte[], SortingParams, byte[]) * @param key * @param sortingParameters * @return a list of sorted elements. */ @Override - public List sort(final String key, final SortingParams sortingParameters) { + public List sort(final byte[] key, final SortingParams sortingParameters) { checkIsInMultiOrPipeline(); - client.sort(key, sortingParameters); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.sort(key, sortingParameters)); } /** * Sort a Set or a List accordingly to the specified parameters and store the result at dstkey. - * @see #sort(String, SortingParams) - * @see #sort(String) - * @see #sort(String, String) + * @see #sort(byte[], SortingParams) + * @see #sort(byte[]) + * @see #sort(byte[], byte[]) * @param key * @param sortingParameters * @param dstkey * @return The number of elements of the list at dstkey. */ @Override - public long sort(final String key, final SortingParams sortingParameters, final String dstkey) { + public long sort(final byte[] key, final SortingParams sortingParameters, final byte[] dstkey) { checkIsInMultiOrPipeline(); - client.sort(key, sortingParameters, dstkey); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.sort(key, sortingParameters, dstkey)); } /** @@ -2106,39 +2276,44 @@ public long sort(final String key, final SortingParams sortingParameters, final * Sort the elements contained in the List, Set, or Sorted Set value at key and store the result * at dstkey. By default sorting is numeric with elements being compared as double precision * floating point numbers. This is the simplest form of SORT. - * @see #sort(String) - * @see #sort(String, SortingParams) - * @see #sort(String, SortingParams, String) + * @see #sort(byte[]) + * @see #sort(byte[], SortingParams) + * @see #sort(byte[], SortingParams, byte[]) * @param key * @param dstkey * @return The number of elements of the list at dstkey. */ @Override - public long sort(final String key, final String dstkey) { + public long sort(final byte[] key, final byte[] dstkey) { checkIsInMultiOrPipeline(); - client.sort(key, dstkey); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.sort(key, dstkey)); } + /** + * Pop an element from a list, push it to another list and return it + * @param srcKey + * @param dstKey + * @param from + * @param to + */ @Override - public String lmove(final String srcKey, final String dstKey, final ListDirection from, - final ListDirection to) { + public byte[] lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { checkIsInMultiOrPipeline(); - client.lmove(srcKey, dstKey, from, to); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.lmove(srcKey, dstKey, from, to)); } + /** + * Pop an element from a list, push it to another list and return it; or block until one is available + * @param srcKey + * @param dstKey + * @param from + * @param to + * @param timeout + */ @Override - public String blmove(final String srcKey, final String dstKey, final ListDirection from, - final ListDirection to, final double timeout) { + public byte[] blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { checkIsInMultiOrPipeline(); - client.blmove(srcKey, dstKey, from, to, timeout); - client.setTimeoutInfinite(); - try { - return client.getBulkReply(); - } finally { - client.rollbackTimeout(); - } + return connection.executeCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); } /** @@ -2164,16 +2339,16 @@ public String blmove(final String srcKey, final String dstKey, final ListDirecti *

* Blocking behavior *

- * If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other - * client performs a LPUSH or an RPUSH operation against one of the lists. - *

- * Once new data is present on one of the lists, the client finally returns with the name of the - * key unblocking it and the popped value. - *

- * When blocking, if a non-zero timeout is specified, the client will unblock returning a nil - * special value if the specified amount of seconds passed without a push operation against at - * least one of the specified keys. - *

+ If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other + connection performs a LPUSH or an RPUSH operation against one of the lists. +

+ Once new data is present on one of the lists, the connection finally returns with the name of the + key unblocking it and the popped value. +

+ When blocking, if a non-zero timeout is specified, the connection will unblock returning a nil + special value if the specified amount of seconds passed without a push operation against at + least one of the specified keys. +

* The timeout argument is interpreted as an integer value. A timeout of zero means instead to * block forever. *

@@ -2193,31 +2368,23 @@ public String blmove(final String srcKey, final String dstKey, final ListDirecti * it like if inside MULTI/EXEC the time will flow at infinite speed :) *

* Time complexity: O(1) - * @see #brpop(int, String...) * @param timeout * @param keys * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the * unblocking key and the popped value. *

- * When a non-zero timeout is specified, and the BLPOP operation timed out, the return - * value is a nil multi bulk reply. Most client values will return false or nil - * accordingly to the programming language used. + When a non-zero timeout is specified, and the BLPOP operation timed out, the return + value is a nil multi bulk reply. Most connection values will return false or nil + accordingly to the programming language used. */ @Override - public List blpop(final int timeout, final String... keys) { - return blpop(getKeysAndTimeout(timeout, keys)); + public List blpop(final int timeout, final byte[]... keys) { + return connection.executeCommand(commandObjects.blpop(timeout, keys)); } @Override - public KeyedListElement blpop(final double timeout, final String... keys) { - checkIsInMultiOrPipeline(); - client.blpop(timeout, keys); - client.setTimeoutInfinite(); - try { - return BuilderFactory.KEYED_LIST_ELEMENT.build(client.getBinaryMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } + public List blpop(final double timeout, final byte[]... keys) { + return connection.executeCommand(commandObjects.blpop(timeout, keys)); } /** @@ -2243,16 +2410,16 @@ public KeyedListElement blpop(final double timeout, final String... keys) { *

* Blocking behavior *

- * If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other - * client performs a LPUSH or an RPUSH operation against one of the lists. - *

- * Once new data is present on one of the lists, the client finally returns with the name of the - * key unblocking it and the popped value. - *

- * When blocking, if a non-zero timeout is specified, the client will unblock returning a nil - * special value if the specified amount of seconds passed without a push operation against at - * least one of the specified keys. - *

+ If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other + connection performs a LPUSH or an RPUSH operation against one of the lists. +

+ Once new data is present on one of the lists, the connection finally returns with the name of the + key unblocking it and the popped value. +

+ When blocking, if a non-zero timeout is specified, the connection will unblock returning a nil + special value if the specified amount of seconds passed without a push operation against at + least one of the specified keys. +

* The timeout argument is interpreted as an integer value. A timeout of zero means instead to * block forever. *

@@ -2272,123 +2439,97 @@ public KeyedListElement blpop(final double timeout, final String... keys) { * it like if inside MULTI/EXEC the time will flow at infinite speed :) *

* Time complexity: O(1) - * @see #blpop(int, String...) * @param timeout * @param keys * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the * unblocking key and the popped value. *

- * When a non-zero timeout is specified, and the BLPOP operation timed out, the return - * value is a nil multi bulk reply. Most client values will return false or nil - * accordingly to the programming language used. + When a non-zero timeout is specified, and the BLPOP operation timed out, the return + value is a nil multi bulk reply. Most connection values will return false or nil + accordingly to the programming language used. */ @Override - public List brpop(final int timeout, final String... keys) { - return brpop(getKeysAndTimeout(timeout, keys)); + public List brpop(final int timeout, final byte[]... keys) { + return connection.executeCommand(commandObjects.brpop(timeout, keys)); } @Override - public KeyedListElement brpop(final double timeout, final String... keys) { - checkIsInMultiOrPipeline(); - client.brpop(timeout, keys); - client.setTimeoutInfinite(); - try { - return BuilderFactory.KEYED_LIST_ELEMENT.build(client.getBinaryMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } - } - - private String[] getKeysAndTimeout(int timeout, String[] keys) { - final int keyCount = keys.length; - final String[] args = new String[keyCount + 1]; - - System.arraycopy(keys, 0, args, 0, keyCount); - - args[keyCount] = String.valueOf(timeout); - return args; + public List brpop(final double timeout, final byte[]... keys) { + return connection.executeCommand(commandObjects.brpop(timeout, keys)); } @Override - public List blpop(final String... args) { - checkIsInMultiOrPipeline(); - client.blpop(args); - client.setTimeoutInfinite(); - try { - return client.getMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } + public List bzpopmax(final double timeout, final byte[]... keys) { + return connection.executeCommand(commandObjects.bzpopmax(timeout, keys)); } @Override - public List brpop(final String... args) { - checkIsInMultiOrPipeline(); - client.brpop(args); - client.setTimeoutInfinite(); - try { - return client.getMultiBulkReply(); - } finally { - client.rollbackTimeout(); - } + public List bzpopmin(final double timeout, final byte[]... keys) { + return connection.executeCommand(commandObjects.bzpopmin(timeout, keys)); } + /** + * Request for authentication in a password protected Redis server. A Redis server can be + instructed to require a password before to allow clients to issue commands. This is done using + the requirepass directive in the Redis configuration file. If the password given by the connection + is correct the server replies with an OK status code reply and starts accepting commands from + the connection. Otherwise an error is returned and the clients needs to try a new password. Note + that for the high performance nature of Redis it is possible to try a lot of passwords in + parallel in very short time, so make sure to generate a strong and very long password so that + this attack is infeasible. + * @param password + * @return Status code reply + */ @Override - public KeyedZSetElement bzpopmax(double timeout, String... keys) { + public String auth(final String password) { checkIsInMultiOrPipeline(); - client.bzpopmax(timeout, keys); - client.setTimeoutInfinite(); - try { - return BuilderFactory.KEYED_ZSET_ELEMENT.build(client.getBinaryMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } + connection.sendCommand(Command.AUTH, password); + return connection.getStatusCodeReply(); } + /** + * Request for authentication with a Redis Server that is using ACL where user are authenticated with + * username and password. + * See https://redis.io/topics/acl + * @param user + * @param password + * @return OK + */ @Override - public KeyedZSetElement bzpopmin(double timeout, String... keys) { + public String auth(final String user, final String password) { checkIsInMultiOrPipeline(); - client.bzpopmin(timeout, keys); - client.setTimeoutInfinite(); - try { - return BuilderFactory.KEYED_ZSET_ELEMENT.build(client.getBinaryMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } + connection.sendCommand(Command.AUTH, user, password); + return connection.getStatusCodeReply(); } @Override - public List blpop(final int timeout, final String key) { - return blpop(key, String.valueOf(timeout)); - } - - @Override - public KeyedListElement blpop(double timeout, String key) { - return blpop(timeout, new String[]{key}); + public long zcount(final byte[] key, final double min, final double max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zcount(key, min, max)); } @Override - public List brpop(final int timeout, final String key) { - return brpop(key, String.valueOf(timeout)); + public long zcount(final byte[] key, final byte[] min, final byte[] max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zcount(key, min, max)); } @Override - public KeyedListElement brpop(double timeout, String key) { - return brpop(timeout, new String[]{key}); + public Set zdiff(final byte[]... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zdiff(keys)); } @Override - public long zcount(final String key, final double min, final double max) { + public Set zdiffWithScores(final byte[]... keys) { checkIsInMultiOrPipeline(); - client.zcount(key, min, max); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zdiffWithScores(keys)); } @Override - public long zcount(final String key, final String min, final String max) { + public long zdiffStore(final byte[] dstkey, final byte[]... keys) { checkIsInMultiOrPipeline(); - client.zcount(key, min, max); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zdiffStore(dstkey, keys)); } /** @@ -2398,13 +2539,13 @@ public long zcount(final String key, final String min, final String max) { * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). *

- * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. *

- * The {@link #zcount(String, double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. *

* Exclusive intervals and infinity @@ -2428,31 +2569,26 @@ public long zcount(final String key, final String min, final String max) { * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(String, double, double) - * @see #zrangeByScore(String, double, double, int, int) - * @see #zrangeByScoreWithScores(String, double, double) - * @see #zrangeByScoreWithScores(String, String, String) - * @see #zrangeByScoreWithScores(String, double, double, int, int) - * @see #zcount(String, double, double) + * @see #zrangeByScore(byte[], double, double) + * @see #zrangeByScore(byte[], double, double, int, int) + * @see #zrangeByScoreWithScores(byte[], double, double) + * @see #zrangeByScoreWithScores(byte[], double, double, int, int) + * @see #zcount(byte[], double, double) * @param key - * @param min a double or Double.NEGATIVE_INFINITY for "-inf" - * @param max a double or Double.POSITIVE_INFINITY for "+inf" + * @param min + * @param max * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override - public Set zrangeByScore(final String key, final double min, final double max) { + public List zrangeByScore(final byte[] key, final double min, final double max) { checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max)); } @Override - public Set zrangeByScore(final String key, final String min, final String max) { + public List zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max)); } /** @@ -2462,13 +2598,13 @@ public Set zrangeByScore(final String key, final String min, final Strin * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). *

- * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. *

- * The {@link #zcount(String, double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. *

* Exclusive intervals and infinity @@ -2492,11 +2628,11 @@ public Set zrangeByScore(final String key, final String min, final Strin * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(String, double, double) - * @see #zrangeByScore(String, double, double, int, int) - * @see #zrangeByScoreWithScores(String, double, double) - * @see #zrangeByScoreWithScores(String, double, double, int, int) - * @see #zcount(String, double, double) + * @see #zrangeByScore(byte[], double, double) + * @see #zrangeByScore(byte[], double, double, int, int) + * @see #zrangeByScoreWithScores(byte[], double, double) + * @see #zrangeByScoreWithScores(byte[], double, double, int, int) + * @see #zcount(byte[], double, double) * @param key * @param min * @param max @@ -2505,21 +2641,17 @@ public Set zrangeByScore(final String key, final String min, final Strin * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override - public Set zrangeByScore(final String key, final double min, final double max, + public List zrangeByScore(final byte[] key, final double min, final double max, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max, offset, count); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); } @Override - public Set zrangeByScore(final String key, final String min, final String max, + public List zrangeByScore(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrangeByScore(key, min, max, offset, count); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); } /** @@ -2529,13 +2661,13 @@ public Set zrangeByScore(final String key, final String min, final Strin * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). *

- * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. *

- * The {@link #zcount(String, double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. *

* Exclusive intervals and infinity @@ -2559,28 +2691,26 @@ public Set zrangeByScore(final String key, final String min, final Strin * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(String, double, double) - * @see #zrangeByScore(String, double, double, int, int) - * @see #zrangeByScoreWithScores(String, double, double) - * @see #zrangeByScoreWithScores(String, double, double, int, int) - * @see #zcount(String, double, double) + * @see #zrangeByScore(byte[], double, double) + * @see #zrangeByScore(byte[], double, double, int, int) + * @see #zrangeByScoreWithScores(byte[], double, double) + * @see #zrangeByScoreWithScores(byte[], double, double, int, int) + * @see #zcount(byte[], double, double) * @param key * @param min * @param max * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max) { + public List zrangeByScoreWithScores(final byte[] key, final double min, final double max) { checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); } @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max) { + public List zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); } /** @@ -2590,13 +2720,13 @@ public Set zrangeByScoreWithScores(final String key, final String min, fi * The elements having the same score are returned sorted lexicographically as ASCII strings (this * follows from a property of Redis sorted sets and does not involve further computation). *

- * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * Using the optional {@link #zrangeByScore(byte[], double, double, int, int) LIMIT} it's possible * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large * the commands needs to traverse the list for offset elements and this adds up to the O(M) * figure. *

- * The {@link #zcount(String, double, double) ZCOUNT} command is similar to - * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * The {@link #zcount(byte[], double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(byte[], double, double) ZRANGEBYSCORE} but instead of returning the * actual elements in the specified interval, it just returns the number of matching elements. *

* Exclusive intervals and infinity @@ -2620,11 +2750,11 @@ public Set zrangeByScoreWithScores(final String key, final String min, fi * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of * elements returned by the command, so if M is constant (for instance you always ask for the * first ten elements with LIMIT) you can consider it O(log(N)) - * @see #zrangeByScore(String, double, double) - * @see #zrangeByScore(String, double, double, int, int) - * @see #zrangeByScoreWithScores(String, double, double) - * @see #zrangeByScoreWithScores(String, double, double, int, int) - * @see #zcount(String, double, double) + * @see #zrangeByScore(byte[], double, double) + * @see #zrangeByScore(byte[], double, double, int, int) + * @see #zrangeByScoreWithScores(byte[], double, double) + * @see #zrangeByScoreWithScores(byte[], double, double, int, int) + * @see #zcount(byte[], double, double) * @param key * @param min * @param max @@ -2633,83 +2763,69 @@ public Set zrangeByScoreWithScores(final String key, final String min, fi * @return Multi bulk reply specifically a list of elements in the specified score range. */ @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max, + public List zrangeByScoreWithScores(final byte[] key, final double min, final double max, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max, offset, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); } @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max, + public List zrangeByScoreWithScores(final byte[] key, final byte[] min, final byte[] max, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrangeByScoreWithScores(key, min, max, offset, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); } @Override - public Set zrevrangeByScore(final String key, final double max, final double min) { + public List zrevrangeByScore(final byte[] key, final double max, final double min) { checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min)); } @Override - public Set zrevrangeByScore(final String key, final String max, final String min) { + public List zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min)); } @Override - public Set zrevrangeByScore(final String key, final double max, final double min, + public List zrevrangeByScore(final byte[] key, final double max, final double min, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min, offset, count); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); } @Override - public Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { + public List zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min, + final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); } @Override - public Set zrevrangeByScoreWithScores(final String key, final double max, - final double min, final int offset, final int count) { + public List zrevrangeByScoreWithScores(final byte[] key, final double max, final double min) { checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min, offset, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); } @Override - public Set zrevrangeByScoreWithScores(final String key, final String max, - final String min, final int offset, final int count) { + public List zrevrangeByScoreWithScores(final byte[] key, final double max, + final double min, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min, offset, count); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); } @Override - public Set zrevrangeByScore(final String key, final String max, final String min, - final int offset, final int count) { + public List zrevrangeByScoreWithScores(final byte[] key, final byte[] max, final byte[] min) { checkIsInMultiOrPipeline(); - client.zrevrangeByScore(key, max, min, offset, count); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); } @Override - public Set zrevrangeByScoreWithScores(final String key, final String max, final String min) { + public List zrevrangeByScoreWithScores(final byte[] key, final byte[] max, + final byte[] min, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrevrangeByScoreWithScores(key, max, min); - return getTupledSet(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); } /** @@ -2724,13 +2840,11 @@ public Set zrevrangeByScoreWithScores(final String key, final String max, * @param key * @param start * @param stop - * @return */ @Override - public long zremrangeByRank(final String key, final long start, final long stop) { + public long zremrangeByRank(final byte[] key, final long start, final long stop) { checkIsInMultiOrPipeline(); - client.zremrangeByRank(key, start, stop); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zremrangeByRank(key, start, stop)); } /** @@ -2747,45 +2861,39 @@ public long zremrangeByRank(final String key, final long start, final long stop) * @return Integer reply, specifically the number of elements removed. */ @Override - public long zremrangeByScore(final String key, final double min, final double max) { + public long zremrangeByScore(final byte[] key, final double min, final double max) { checkIsInMultiOrPipeline(); - client.zremrangeByScore(key, min, max); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zremrangeByScore(key, min, max)); } @Override - public long zremrangeByScore(final String key, final String min, final String max) { + public long zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { checkIsInMultiOrPipeline(); - client.zremrangeByScore(key, min, max); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zremrangeByScore(key, min, max)); } /** * Add multiple sorted sets, This command is similar to ZUNIONSTORE, but instead of storing the - * resulting sorted set, it is returned to the client. + resulting sorted set, it is returned to the connection. * @param params * @param keys - * @return */ @Override - public Set zunion(ZParams params, String... keys) { + public Set zunion(final ZParams params, final byte[]... keys) { checkIsInMultiOrPipeline(); - client.zunion(params, keys); - return BuilderFactory.STRING_ZSET.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.zunion(params, keys)); } /** * Add multiple sorted sets with scores, This command is similar to ZUNIONSTORE, but instead of storing the - * resulting sorted set, it is returned to the client. + resulting sorted set, it is returned to the connection. * @param params * @param keys - * @return */ @Override - public Set zunionWithScores(ZParams params, String... keys) { + public Set zunionWithScores(final ZParams params, final byte[]... keys) { checkIsInMultiOrPipeline(); - client.zunionWithScores(params, keys); - return getTupledSet(); + return connection.executeCommand(commandObjects.zunionWithScores(params, keys)); } /** @@ -2793,10 +2901,9 @@ public Set zunionWithScores(ZParams params, String... keys) { * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys * and the other (optional) arguments. *

- * As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an - * element to be present in each of the given inputs to be inserted in the result. The - * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all - * inputs. + * As the terms imply, the {@link #zinterstore(byte[], byte[]...)} ZINTERSTORE} command requires + * an element to be present in each of the given inputs to be inserted in the result. The {@link + * #zunionstore(byte[], byte[]...)} command inserts all elements across all inputs. *

* Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means * that the score of each element in the sorted set is first multiplied by this weight before @@ -2810,19 +2917,14 @@ public Set zunionWithScores(ZParams params, String... keys) { *

* Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input * sorted sets, and M being the number of elements in the resulting sorted set - * @see #zunionstore(String, String...) - * @see #zunionstore(String, ZParams, String...) - * @see #zinterstore(String, String...) - * @see #zinterstore(String, ZParams, String...) * @param dstkey * @param sets * @return Integer reply, specifically the number of elements in the sorted set at dstkey */ @Override - public long zunionstore(final String dstkey, final String... sets) { + public long zunionstore(final byte[] dstkey, final byte[]... sets) { checkIsInMultiOrPipeline(); - client.zunionstore(dstkey, sets); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zunionstore(dstkey, sets)); } /** @@ -2830,7 +2932,4011 @@ public long zunionstore(final String dstkey, final String... sets) { * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys * and the other (optional) arguments. *

- * As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an + * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an + * element to be present in each of the given inputs to be inserted in the result. The {@link + * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means + * that the score of each element in the sorted set is first multiplied by this weight before + * being passed to the aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of the union or + * intersection are aggregated. This option defaults to SUM, where the score of an element is + * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the + * resulting set will contain the minimum or maximum score of an element across the inputs where + * it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input + * sorted sets, and M being the number of elements in the resulting sorted set + * @param dstkey + * @param sets + * @param params + * @return Integer reply, specifically the number of elements in the sorted set at dstkey + */ + @Override + public long zunionstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zunionstore(dstkey, params, sets)); + } + + /** + * Intersect multiple sorted sets, This command is similar to ZINTERSTORE, but instead of storing + the resulting sorted set, it is returned to the connection. + * @param params + * @param keys + */ + @Override + public Set zinter(final ZParams params, final byte[]... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zinter(params, keys)); + } + + /** + * Intersect multiple sorted sets, This command is similar to ZINTERSTORE, but instead of storing + the resulting sorted set, it is returned to the connection. + * @param params + * @param keys + */ + @Override + public Set zinterWithScores(final ZParams params, final byte[]... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zinterWithScores(params, keys)); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at + * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys + * and the other (optional) arguments. + *

+ * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an + * element to be present in each of the given inputs to be inserted in the result. The {@link + * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means + * that the score of each element in the sorted set is first multiplied by this weight before + * being passed to the aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of the union or + * intersection are aggregated. This option defaults to SUM, where the score of an element is + * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the + * resulting set will contain the minimum or maximum score of an element across the inputs where + * it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input + * sorted sets, and M being the number of elements in the resulting sorted set + * @param dstkey + * @param sets + * @return Integer reply, specifically the number of elements in the sorted set at dstkey + */ + @Override + public long zinterstore(final byte[] dstkey, final byte[]... sets) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zinterstore(dstkey, sets)); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at + * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys + * and the other (optional) arguments. + *

+ * As the terms imply, the {@link #zinterstore(byte[], byte[]...) ZINTERSTORE} command requires an + * element to be present in each of the given inputs to be inserted in the result. The {@link + * #zunionstore(byte[], byte[]...) ZUNIONSTORE} command inserts all elements across all inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means + * that the score of each element in the sorted set is first multiplied by this weight before + * being passed to the aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of the union or + * intersection are aggregated. This option defaults to SUM, where the score of an element is + * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the + * resulting set will contain the minimum or maximum score of an element across the inputs where + * it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input + * sorted sets, and M being the number of elements in the resulting sorted set + * @param dstkey + * @param sets + * @param params + * @return Integer reply, specifically the number of elements in the sorted set at dstkey + */ + @Override + public long zinterstore(final byte[] dstkey, final ZParams params, final byte[]... sets) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zinterstore(dstkey, params, sets)); + } + + @Override + public long zlexcount(final byte[] key, final byte[] min, final byte[] max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public List zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public List zrangeByLex(final byte[] key, final byte[] min, final byte[] max, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public List zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public long zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + /** + * Synchronously save the DB on disk. + *

+ * Save the whole dataset on disk (this means that all the databases are saved, as well as keys + * with an EXPIRE set (the expire is preserved). The server hangs while the saving is not + * completed, no connection is served in the meanwhile. An OK code is returned when the DB was + * fully stored in disk. + *

+ * The background variant of this command is {@link #bgsave() BGSAVE} that is able to perform the + * saving in the background while the server continues serving other clients. + *

+ * @return Status code reply + */ + @Override + public String save() { + connection.sendCommand(Command.SAVE); + return connection.getStatusCodeReply(); + } + + /** + * Asynchronously save the DB on disk. + *

+ Save the DB in background. The OK code is immediately returned. Redis forks, the parent + continues to server the clients, the child saves the DB on disk then exit. A connection my be able + to check if the operation succeeded using the LASTSAVE command. + * @return Status code reply + */ + @Override + public String bgsave() { + connection.sendCommand(BGSAVE); + return connection.getStatusCodeReply(); + } + + /** + * Rewrite the append only file in background when it gets too big. Please for detailed + * information about the Redis Append Only File check the Append Only File Howto. + *

+ * BGREWRITEAOF rewrites the Append Only File in background when it gets too big. The Redis Append + * Only File is a Journal, so every operation modifying the dataset is logged in the Append Only + * File (and replayed at startup). This means that the Append Only File always grows. In order to + * rebuild its content the BGREWRITEAOF creates a new version of the append only file starting + * directly form the dataset in memory in order to guarantee the generation of the minimal number + * of commands needed to rebuild the database. + *

+ * @return Status code reply + */ + @Override + public String bgrewriteaof() { + connection.sendCommand(BGREWRITEAOF); + return connection.getStatusCodeReply(); + } + + /** + * Return the UNIX time stamp of the last successfully saving of the dataset on disk. + *

+ Return the UNIX TIME of the last DB save executed with success. A connection may check if a + {@link #bgsave() BGSAVE} command succeeded reading the LASTSAVE value, then issuing a BGSAVE + * command and checking at regular intervals every N seconds if LASTSAVE changed. + * @return Integer reply, specifically an UNIX time stamp. + */ + @Override + public long lastsave() { + connection.sendCommand(LASTSAVE); + return connection.getIntegerReply(); + } + + /** + * Synchronously save the DB on disk, then shutdown the server. + *

+ * Stop all the clients, save the DB, then quit the server. This commands makes sure that the DB + * is switched off without the lost of any data. This is not guaranteed if the connection uses + * simply {@link #save() SAVE} and then {@link #quit() QUIT} because other clients may alter the + * DB data between the two commands. + * @throws JedisException with the status code reply on error. On success nothing is thrown since + * the server quits and the connection is closed. + */ + @Override + public void shutdown() throws JedisException { + connection.sendCommand(SHUTDOWN); + try { + throw new JedisException(connection.getStatusCodeReply()); + } catch (JedisConnectionException jce) { + // expected + connection.setBroken(); + } + } + + @Override + public void shutdown(final SaveMode saveMode) throws JedisException { + connection.sendCommand(SHUTDOWN, saveMode.getRaw()); + try { + throw new JedisException(connection.getStatusCodeReply()); + } catch (JedisConnectionException jce) { + // expected + connection.setBroken(); + } + } + + /** + * Provide information and statistics about the server. + *

+ * The info command returns different information and statistics about the server in an format + * that's simple to parse by computers and easy to read by humans. + *

+ * Format of the returned String: + *

+ * All the fields are in the form field:value + * + *

+   * edis_version:0.07
+   * connected_clients:1
+   * connected_slaves:0
+   * used_memory:3187
+   * changes_since_last_save:0
+   * last_save_time:1237655729
+   * total_connections_received:1
+   * total_commands_processed:1
+   * uptime_in_seconds:25
+   * uptime_in_days:0
+   * 
+ * + * Notes + *

+ * used_memory is returned in bytes, and is the total number of bytes allocated by the program + * using malloc. + *

+ * uptime_in_days is redundant since the uptime in seconds contains already the full uptime + * information, this field is only mainly present for humans. + *

+ * changes_since_last_save does not refer to the number of key changes, but to the number of + * operations that produced some kind of change in the dataset. + *

+ * @return Bulk reply + */ + @Override + public String info() { + connection.sendCommand(Command.INFO); + return connection.getBulkReply(); + } + + @Override + public String info(final String section) { + connection.sendCommand(Command.INFO, section); + return connection.getBulkReply(); + } + + /** + * Dump all the received requests in real time. + *

+ * MONITOR is a debugging command that outputs the whole sequence of commands received by the + * Redis server. is very handy in order to understand what is happening into the database. This + * command is used directly via telnet. + * @param jedisMonitor + */ + public void monitor(final JedisMonitor jedisMonitor) { +// connection.monitor(); + connection.sendCommand(MONITOR); + connection.getStatusCodeReply(); + jedisMonitor.proceed(connection); + } + + /** + * Change the replication settings. + *

+ * The SLAVEOF command can change the replication settings of a slave on the fly. If a Redis + * server is already acting as slave, the command SLAVEOF NO ONE will turn off the replication + * turning the Redis server into a MASTER. In the proper form SLAVEOF hostname port will make the + * server a slave of the specific server listening at the specified hostname and port. + *

+ * If a server is already a slave of some master, SLAVEOF hostname port will stop the replication + * against the old server and start the synchronization against the new one discarding the old + * dataset. + *

+ * The form SLAVEOF no one will stop replication turning the server into a MASTER but will not + * discard the replication. So if the old master stop working it is possible to turn the slave + * into a master and set the application to use the new master in read/write. Later when the other + * Redis server will be fixed it can be configured in order to work as slave. + *

+ * @param host + * @param port + * @return Status code reply + */ + @Override + public String slaveof(final String host, final int port) { + connection.sendCommand(SLAVEOF, encode(host), toByteArray(port)); + return connection.getStatusCodeReply(); + } + + @Override + public String slaveofNoOne() { + connection.sendCommand(SLAVEOF, NO.getRaw(), ONE.getRaw()); + return connection.getStatusCodeReply(); + } + + @Override + public List roleBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ROLE); + return BuilderFactory.RAW_OBJECT_LIST.build(connection.getOne()); + } + + /** + * Retrieve the configuration of a running Redis server. Not all the configuration parameters are + * supported. + *

+ * CONFIG GET returns the current configuration parameters. This sub command only accepts a single + * argument, that is glob style pattern. All the configuration parameters matching this parameter + * are reported as a list of key-value pairs. + *

+ * Example: + * + *

+   * $ redis-cli config get '*'
+   * 1. "dbfilename"
+   * 2. "dump.rdb"
+   * 3. "requirepass"
+   * 4. (nil)
+   * 5. "masterauth"
+   * 6. (nil)
+   * 7. "maxmemory"
+   * 8. "0\n"
+   * 9. "appendfsync"
+   * 10. "everysec"
+   * 11. "save"
+   * 12. "3600 1 300 100 60 10000"
+   *
+   * $ redis-cli config get 'm*'
+   * 1. "masterauth"
+   * 2. (nil)
+   * 3. "maxmemory"
+   * 4. "0\n"
+   * 
+ * @param pattern + * @return Bulk reply. + */ + @Override + public List configGet(final byte[] pattern) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CONFIG, Keyword.GET.getRaw(), pattern); + return connection.getBinaryMultiBulkReply(); + } + + /** + * Reset the stats returned by INFO + */ + @Override + public String configResetStat() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CONFIG, Keyword.RESETSTAT); + return connection.getStatusCodeReply(); + } + + /** + * The CONFIG REWRITE command rewrites the redis.conf file the server was started with, applying + * the minimal changes needed to make it reflect the configuration currently used by the server, + * which may be different compared to the original one because of the use of the CONFIG SET + * command. + *

+ * The rewrite is performed in a very conservative way: + *

    + *
  • Comments and the overall structure of the original redis.conf are preserved as much as + * possible.
  • + *
  • If an option already exists in the old redis.conf file, it will be rewritten at the same + * position (line number).
  • + *
  • If an option was not already present, but it is set to its default value, it is not added + * by the rewrite process.
  • + *
  • If an option was not already present, but it is set to a non-default value, it is appended + * at the end of the file.
  • + *
  • Non used lines are blanked. For instance if you used to have multiple save directives, but + * the current configuration has fewer or none as you disabled RDB persistence, all the lines will + * be blanked.
  • + *
+ *

+ * CONFIG REWRITE is also able to rewrite the configuration file from scratch if the original one + * no longer exists for some reason. However if the server was started without a configuration + * file at all, the CONFIG REWRITE will just return an error. + * @return OK when the configuration was rewritten properly. Otherwise an error is returned. + */ + @Override + public String configRewrite() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CONFIG, Keyword.REWRITE); + return connection.getStatusCodeReply(); + } + + /** + * Alter the configuration of a running Redis server. Not all the configuration parameters are + * supported. + *

+ * The list of configuration parameters supported by CONFIG SET can be obtained issuing a + * {@link #configGet(byte[]) CONFIG GET *} command. + *

+ * The configuration set using CONFIG SET is immediately loaded by the Redis server that will + * start acting as specified starting from the next command. + *

+ * Parameters value format + *

+ * The value of the configuration parameter is the same as the one of the same parameter in the + * Redis configuration file, with the following exceptions: + *

+ *

    + *
  • The save parameter is a list of space-separated integers. Every pair of integers specify + * the time and number of changes limit to trigger a save. For instance the command CONFIG SET + * save "3600 10 60 10000" will configure the server to issue a background saving of the RDB file + * every 3600 seconds if there are at least 10 changes in the dataset, and every 60 seconds if + * there are at least 10000 changes. To completely disable automatic snapshots just set the + * parameter as an empty string. + *
  • All the integer parameters representing memory are returned and accepted only using bytes + * as unit. + *
+ * @param parameter + * @param value + * @return Status code reply + */ + @Override + public String configSet(final byte[] parameter, final byte[] value) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CONFIG, Keyword.SET.getRaw(), parameter, value); + return connection.getStatusCodeReply(); + } + + @Override + public long strlen(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.strlen(key)); + } + + @Override + public LCSMatchResult strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); + } + + public LCSMatchResult strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public long lpushx(final byte[] key, final byte[]... string) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpushx(key, string)); + } + + /** + * Undo a {@link #expire(byte[], int) expire} at turning the expire key into a normal key. + *

+ * Time complexity: O(1) + * @param key + * @return Integer reply, specifically: 1: the key is now persist. 0: the key is not persist (only + * happens when key not set). + */ + @Override + public long persist(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.persist(key)); + } + + @Override + public long rpushx(final byte[] key, final byte[]... string) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.rpushx(key, string)); + } + + @Override + public byte[] echo(final byte[] string) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ECHO, string); + return connection.getBinaryBulkReply(); + } + + @Override + public long linsert(final byte[] key, final ListPosition where, final byte[] pivot, + final byte[] value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.linsert(key, where, pivot, value)); + } + + /** + * Pop a value from a list, push it to another list and return it; or block until one is available + */ + @Override + public byte[] brpoplpush(final byte[] source, final byte[] destination, final int timeout) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + /** + * Sets or clears the bit at offset in the string value stored at key + */ + @Override + public boolean setbit(final byte[] key, final long offset, final boolean value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.setbit(key, offset, value)); + } + + /** + * Returns the bit value at offset in the string value stored at key + */ + @Override + public boolean getbit(final byte[] key, final long offset) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.getbit(key, offset)); + } + + @Override + public long bitpos(final byte[] key, final boolean value) { + return bitpos(key, value, new BitPosParams()); + } + + @Override + public long bitpos(final byte[] key, final boolean value, final BitPosParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public long setrange(final byte[] key, final long offset, final byte[] value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public byte[] getrange(final byte[] key, final long startOffset, final long endOffset) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + public long publish(final byte[] channel, final byte[] message) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.publish(channel, message)); + } + + public void subscribe(BinaryJedisPubSub jedisPubSub, final byte[]... channels) { + connection.setTimeoutInfinite(); + try { + jedisPubSub.proceed(connection, channels); + } finally { + connection.rollbackTimeout(); + } + } + + public void psubscribe(BinaryJedisPubSub jedisPubSub, final byte[]... patterns) { + connection.setTimeoutInfinite(); + try { + jedisPubSub.proceedWithPatterns(connection, patterns); + } finally { + connection.rollbackTimeout(); + } + } + + /** + * Evaluates scripts using the Lua interpreter built into Redis starting from version 2.6.0. + *

+ * @param script + * @param keys + * @param args + * @return Script result + */ + @Override + public Object eval(final byte[] script, final List keys, final List args) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.eval(script, keys, args)); + } + + protected static byte[][] getParamsWithBinary(List keys, List args) { + final int keyCount = keys.size(); + final int argCount = args.size(); + byte[][] params = new byte[keyCount + argCount][]; + + for (int i = 0; i < keyCount; i++) + params[i] = keys.get(i); + + for (int i = 0; i < argCount; i++) + params[keyCount + i] = args.get(i); + + return params; + } + + @Override + public Object eval(final byte[] script, final int keyCount, final byte[]... params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Object eval(final byte[] script) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.eval(script)); + } + + @Override + public Object evalsha(final byte[] sha1) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Object evalsha(final byte[] sha1, final List keys, final List args) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Object evalsha(final byte[] sha1, final int keyCount, final byte[]... params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public String scriptFlush() { + connection.sendCommand(SCRIPT, FLUSH); + return connection.getStatusCodeReply(); + } + + @Override + public String scriptFlush(final FlushMode flushMode) { + connection.sendCommand(SCRIPT, FLUSH.getRaw(), flushMode.getRaw()); + return connection.getStatusCodeReply(); + } + + @Override + public Boolean scriptExists(final byte[] sha1) { + byte[][] a = new byte[1][]; + a[0] = sha1; + return scriptExists(a).get(0); + } + + @Override + public List scriptExists(final byte[]... sha1) { + connection.sendCommand(SCRIPT, joinParameters(Keyword.EXISTS.getRaw(), sha1)); + return BuilderFactory.BOOLEAN_LIST.build(connection.getOne()); + } + + @Override + public byte[] scriptLoad(final byte[] script) { + connection.sendCommand(SCRIPT, LOAD.getRaw(), script); + return connection.getBinaryBulkReply(); + } + + @Override + public String scriptKill() { + connection.sendCommand(SCRIPT, KILL); + return connection.getStatusCodeReply(); + } + + @Override + public String slowlogReset() { + connection.sendCommand(SLOWLOG, RESET); + return connection.getBulkReply(); + } + + @Override + public long slowlogLen() { + connection.sendCommand(SLOWLOG, LEN); + return connection.getIntegerReply(); + } + + @Override + public List slowlogGetBinary() { + connection.sendCommand(SLOWLOG, Keyword.GET); + return connection.getObjectMultiBulkReply(); + } + + @Override + public List slowlogGetBinary(final long entries) { + connection.sendCommand(SLOWLOG, Keyword.GET.getRaw(), toByteArray(entries)); + return connection.getObjectMultiBulkReply(); + } + + @Override + public Long objectRefcount(final byte[] key) { + connection.sendCommand(OBJECT, REFCOUNT.getRaw(), key); + return connection.getIntegerReply(); + } + + @Override + public byte[] objectEncoding(final byte[] key) { + connection.sendCommand(OBJECT, ENCODING.getRaw(), key); + return connection.getBinaryBulkReply(); + } + + @Override + public Long objectIdletime(final byte[] key) { + connection.sendCommand(OBJECT, IDLETIME.getRaw(), key); + return connection.getIntegerReply(); + } + + @Override + public List objectHelpBinary() { + connection.sendCommand(OBJECT, HELP); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public Long objectFreq(final byte[] key) { + connection.sendCommand(OBJECT, FREQ.getRaw(), key); + return connection.getIntegerReply(); + } + + @Override + public long bitcount(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitcount(key)); + } + + @Override + public long bitcount(final byte[] key, final long start, final long end) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public long bitop(final BitOP op, final byte[] destKey, final byte[]... srcKeys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public byte[] dump(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.dump(key)); + } + + @Override + public String restore(final byte[] key, final long ttl, final byte[] serializedValue) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public String restore(final byte[] key, final long ttl, final byte[] serializedValue, + final RestoreParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + /** + * Set a timeout on the specified key. After the timeout the key will be automatically deleted by + * the server. A key with an associated timeout is said to be volatile in Redis terminology. + *

+ * Volatile keys are stored on disk like the other keys, the timeout is persistent too like all + * the other aspects of the dataset. Saving a dataset containing expires and stopping the server + * does not stop the flow of time as Redis stores on disk the time when the key will no longer be + * available as Unix time, and not the remaining milliseconds. + *

+ * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire + * set. It is also possible to undo the expire at all turning the key into a normal key using the + * {@link #persist(byte[]) PERSIST} command. + *

+ * Time complexity: O(1) + * @see PEXPIRE Command + * @param key + * @param milliseconds + * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since + * the key already has an associated timeout (this may happen only in Redis versions < + * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. + */ + @Override + public long pexpire(final byte[] key, final long milliseconds) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public long pexpireAt(final byte[] key, final long millisecondsTimestamp) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public long pttl(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pttl(key)); + } + + /** + * PSETEX works exactly like {@link #setex(byte[], int, byte[])} with the sole difference that the + * expire time is specified in milliseconds instead of seconds. Time complexity: O(1) + * @param key + * @param milliseconds + * @param value + * @return Status code reply + */ + @Override + public String psetex(final byte[] key, final long milliseconds, final byte[] value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public byte[] memoryDoctorBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(MEMORY, DOCTOR); + return connection.getBinaryBulkReply(); + } + + @Override + public Long memoryUsage(final byte[] key) { + checkIsInMultiOrPipeline(); + connection.sendCommand(MEMORY, USAGE.getRaw(), key); + return connection.getIntegerReply(); + } + + @Override + public Long memoryUsage(final byte[] key, final int samples) { + checkIsInMultiOrPipeline(); + connection.sendCommand(MEMORY, USAGE.getRaw(), key, SAMPLES.getRaw(), toByteArray(samples)); + return connection.getIntegerReply(); + } + + @Override + public String failover() { + checkIsInMultiOrPipeline(); + connection.sendCommand(FAILOVER); + connection.setTimeoutInfinite(); + try { + return connection.getStatusCodeReply(); + } finally { + connection.rollbackTimeout(); + } + } + + @Override + public String failover(FailoverParams failoverParams) { + checkIsInMultiOrPipeline(); + CommandArguments args = new ClusterCommandArguments(FAILOVER).addParams(failoverParams); + connection.sendCommand(args); + connection.setTimeoutInfinite(); + try { + return connection.getStatusCodeReply(); + } finally { + connection.rollbackTimeout(); + } + } + + @Override + public String failoverAbort() { + checkIsInMultiOrPipeline(); + connection.sendCommand(FAILOVER, ABORT); + return connection.getStatusCodeReply(); + } + + @Override + public byte[] aclWhoAmIBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, WHOAMI); + return connection.getBinaryBulkReply(); + } + + @Override + public byte[] aclGenPassBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, GENPASS); + return connection.getBinaryBulkReply(); + } + + @Override + public byte[] aclGenPassBinary(int bits) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, GENPASS.getRaw(), toByteArray(bits)); + return connection.getBinaryBulkReply(); + } + + @Override + public List aclListBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, LIST); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public List aclUsersBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, USERS); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public AccessControlUser aclGetUser(byte[] name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, GETUSER.getRaw(), name); + return BuilderFactory.ACCESS_CONTROL_USER.build(connection.getObjectMultiBulkReply()); + } + + @Override + public String aclSetUser(byte[] name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, SETUSER.getRaw(), name); + return connection.getStatusCodeReply(); + } + + @Override + public String aclSetUser(byte[] name, byte[]... keys) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, joinParameters(SETUSER.getRaw(), name, keys)); + return connection.getStatusCodeReply(); + } + + @Override + public long aclDelUser(byte[] name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, DELUSER.getRaw(), name); + return connection.getIntegerReply(); + } + + @Override + public long aclDelUser(byte[] name, byte[]... names) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, joinParameters(DELUSER.getRaw(), name, names)); + return connection.getIntegerReply(); + } + + @Override + public List aclCatBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, CAT); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public List aclCat(byte[] category) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, CAT.getRaw(), category); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public List aclLogBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, LOG); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public List aclLogBinary(int limit) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, LOG.getRaw(), toByteArray(limit)); + return connection.getBinaryMultiBulkReply(); + } + + @Override + public String aclLogReset() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, LOG.getRaw(), RESET.getRaw()); + return connection.getStatusCodeReply(); + } + + @Override + public String clientKill(final byte[] ipPort) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, KILL.getRaw(), ipPort); + return this.connection.getStatusCodeReply(); + } + + @Override + public String clientKill(final String ip, final int port) { + return clientKill(ip + ':' + port); + } + + @Override + public long clientKill(ClientKillParams params) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, joinParameters(KILL.getRaw(), params.getByteParams())); + return this.connection.getIntegerReply(); + } + + @Override + public byte[] clientGetnameBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, GETNAME); + return connection.getBinaryBulkReply(); + } + + @Override + public byte[] clientListBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, LIST); + return connection.getBinaryBulkReply(); + } + + @Override + public byte[] clientListBinary(ClientType type) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, LIST.getRaw(), type.getRaw()); + return connection.getBinaryBulkReply(); + } + + @Override + public byte[] clientListBinary(final long... clientIds) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, clientListParams(clientIds)); + return connection.getBinaryBulkReply(); + } + + private byte[][] clientListParams(final long... clientIds) { + final byte[][] params = new byte[2 + clientIds.length][]; + int index = 0; + params[index++] = Keyword.LIST.getRaw(); + params[index++] = ID.getRaw(); + for (final long clientId : clientIds) { + params[index++] = toByteArray(clientId); + } + return params; + } + + @Override + public byte[] clientInfoBinary() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, Keyword.INFO); + return connection.getBinaryBulkReply(); + } + + @Override + public String clientSetname(final byte[] name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, SETNAME.getRaw(), name); + return connection.getBulkReply(); + } + + @Override + public long clientId() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, ID); + return connection.getIntegerReply(); + } + + /** + * Unblock a connection blocked in a blocking command from a different connection. + * @param clientId + */ + @Override + public long clientUnblock(final long clientId) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, UNBLOCK.getRaw(), toByteArray(clientId)); + return connection.getIntegerReply(); + } + + /** + * Unblock a connection blocked in a blocking command from a different connection. + * @param clientId + * @param unblockType + */ + @Override + public long clientUnblock(final long clientId, final UnblockType unblockType) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, UNBLOCK.getRaw(), toByteArray(clientId), unblockType.getRaw()); + return connection.getIntegerReply(); + } + + @Override + public String clientPause(final long timeout) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, PAUSE.getRaw(), toByteArray(timeout)); + return connection.getBulkReply(); + } + + @Override + public String clientPause(final long timeout, final ClientPauseMode mode) { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLIENT, PAUSE.getRaw(), toByteArray(timeout), mode.getRaw()); + return connection.getBulkReply(); + } + + public List time() { + checkIsInMultiOrPipeline(); + connection.sendCommand(Command.TIME); + return connection.getMultiBulkReply(); + } + + @Override + public String migrate(final String host, final int port, final byte[] key, + final int destinationDb, final int timeout) { + checkIsInMultiOrPipeline(); + CommandArguments args = new CommandArguments(MIGRATE).add(host).add(port).key(key).add(destinationDb).add(timeout); + connection.sendCommand(args); + return connection.getStatusCodeReply(); + } + + @Override + public String migrate(final String host, final int port, final int destinationDB, + final int timeout, final MigrateParams params, final byte[]... keys) { + checkIsInMultiOrPipeline(); + CommandArguments args = new CommandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(destinationDB) + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys); + connection.sendCommand(args); + return connection.getStatusCodeReply(); + } + + @Override + public String migrate(String host, int port, byte[] key, int timeout) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public String migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public long waitReplicas(final int replicas, final long timeout) { + checkIsInMultiOrPipeline(); + connection.sendCommand(WAIT, toByteArray(replicas), toByteArray(timeout)); + return connection.getIntegerReply(); + } + + @Override + public long pfadd(final byte[] key, final byte[]... elements) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public long pfcount(final byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pfcount(key)); + } + + @Override + public String pfmerge(final byte[] destkey, final byte[]... sourcekeys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public long pfcount(final byte[]... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pfcount(keys)); + } + + @Override + public ScanResult scan(final byte[] cursor) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.scan(cursor)); + } + + @Override + public ScanResult scan(final byte[] cursor, final ScanParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.scan(cursor, params)); + } + + @Override + public ScanResult scan(final byte[] cursor, final ScanParams params, final byte[] type) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public ScanResult> hscan(final byte[] key, final byte[] cursor) { + return hscan(key, cursor, new ScanParams()); + } + + @Override + public ScanResult> hscan(final byte[] key, final byte[] cursor, + final ScanParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public ScanResult sscan(final byte[] key, final byte[] cursor) { + return sscan(key, cursor, new ScanParams()); + } + + @Override + public ScanResult sscan(final byte[] key, final byte[] cursor, final ScanParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public ScanResult zscan(final byte[] key, final byte[] cursor) { + return zscan(key, cursor, new ScanParams()); + } + + @Override + public ScanResult zscan(final byte[] key, final byte[] cursor, final ScanParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public long geoadd(final byte[] key, final double longitude, final double latitude, + final byte[] member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public long geoadd(final byte[] key, final Map memberCoordinateMap) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public long geoadd(final byte[] key, final GeoAddParams params, final Map memberCoordinateMap) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Double geodist(final byte[] key, final byte[] member1, final byte[] member2) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Double geodist(final byte[] key, final byte[] member1, final byte[] member2, + final GeoUnit unit) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public List geohash(final byte[] key, final byte[]... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geohash(key, members)); + } + + @Override + public List geopos(final byte[] key, final byte[]... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.geopos(key, members)); + } + + @Override + public List georadius(final byte[] key, final double longitude, + final double latitude, final double radius, final GeoUnit unit) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public List georadiusReadonly(final byte[] key, final double longitude, + final double latitude, final double radius, final GeoUnit unit) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public List georadius(final byte[] key, final double longitude, + final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public long georadiusStore(final byte[] key, final double longitude, final double latitude, + final double radius, final GeoUnit unit, final GeoRadiusParam param, + final GeoRadiusStoreParam storeParam) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public List georadiusReadonly(final byte[] key, final double longitude, + final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public List georadiusByMember(final byte[] key, final byte[] member, + final double radius, final GeoUnit unit) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public List georadiusByMemberReadonly(final byte[] key, final byte[] member, + final double radius, final GeoUnit unit) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public List georadiusByMember(final byte[] key, final byte[] member, + final double radius, final GeoUnit unit, final GeoRadiusParam param) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public long georadiusByMemberStore(final byte[] key, final byte[] member, final double radius, + final GeoUnit unit, final GeoRadiusParam param, final GeoRadiusStoreParam storeParam) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public List georadiusByMemberReadonly(final byte[] key, final byte[] member, + final double radius, final GeoUnit unit, final GeoRadiusParam param) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public List bitfield(final byte[] key, final byte[]... arguments) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public List bitfieldReadonly(byte[] key, final byte[]... arguments) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public long hstrlen(final byte[] key, final byte[] field) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public List xread(XReadParams xReadParams, Entry... streams) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public List xreadGroup(byte[] groupname, byte[] consumer, + XReadGroupParams xReadGroupParams, Entry... streams) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public byte[] xadd(final byte[] key, final XAddParams params, final Map hash) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public long xlen(byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xlen(key)); + } + + @Override + public List xrange(byte[] key, byte[] start, byte[] end) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public List xrange(byte[] key, byte[] start, byte[] end, int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public List xrevrange(byte[] key, byte[] end, byte[] start) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public List xrevrange(byte[] key, byte[] end, byte[] start, int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public long xack(byte[] key, byte[] group, byte[]... ids) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public String xgroupCreate(byte[] key, byte[] consumer, byte[] id, boolean makeStream) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xgroupCreate(key, consumer, id, makeStream)); + } + + @Override + public String xgroupSetID(byte[] key, byte[] consumer, byte[] id) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xgroupSetID(key, consumer, id)); + } + + @Override + public long xgroupDestroy(byte[] key, byte[] consumer) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xgroupDestroy(key, consumer)); + } + + @Override + public long xgroupDelConsumer(byte[] key, byte[] consumer, byte[] consumerName) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xgroupDelConsumer(key, consumer, consumerName)); + } + + @Override + public long xdel(byte[] key, byte[]... ids) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xdel(key, ids)); + } + + @Override + public long xtrim(byte[] key, long maxLen, boolean approximateLength) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xtrim(key, maxLen, approximateLength)); + } + + @Override + public long xtrim(byte[] key, XTrimParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xtrim(key, params)); + } + + @Override + public List xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, + byte[] consumername) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Object xpending(final byte[] key, final byte[] groupname) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public List xpending(final byte[] key, final byte[] groupname, final XPendingParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, + XClaimParams params, byte[]... ids) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, + XClaimParams params, byte[]... ids) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public List xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, + long minIdleTime, byte[] start, XAutoClaimParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xautoclaim(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public List xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, + long minIdleTime, byte[] start, XAutoClaimParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Object xinfoStream(byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xinfoStream(key)); + } + + @Override + public List xinfoGroup(byte[] key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public List xinfoConsumers(byte[] key, byte[] group) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.xinfoConsumers(key, group)); + } + + public Object sendCommand(ProtocolCommand cmd, byte[]... args) { + checkIsInMultiOrPipeline(); + connection.sendCommand(cmd, args); + return connection.getOne(); + } + + public Object sendBlockingCommand(ProtocolCommand cmd, byte[]... args) { + checkIsInMultiOrPipeline(); + connection.sendCommand(cmd, args); + connection.setTimeoutInfinite(); + try { + return connection.getOne(); + } finally { + connection.rollbackTimeout(); + } + } + + public Object sendCommand(ProtocolCommand cmd) { + return sendCommand(cmd, DUMMY_ARRAY); + } + + /** + * COPY source destination [DB destination-db] [REPLACE] + * + * @param srcKey the source key. + * @param dstKey the destination key. + * @param db + * @param replace + * @return + */ + @Override + public boolean copy(String srcKey, String dstKey, int db, boolean replace) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.copy(srcKey, dstKey, db, replace)); + } + + /** + * COPY source destination [DB destination-db] [REPLACE] + * + * @param srcKey the source key. + * @param dstKey the destination key. + * @param replace + * @return + */ + @Override + public boolean copy(String srcKey, String dstKey, boolean replace) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + /** + * Works same as ping() but returns argument message instead of PONG. + * @param message + * @return message + */ + @Override + public String ping(final String message) { + checkIsInMultiOrPipeline(); + connection.sendCommand(Command.PING, message); + return connection.getBulkReply(); + } + + /** + * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 + * GB). + *

+ * Time complexity: O(1) + * @param key + * @param value + * @return Status code reply + */ + @Override + public String set(final String key, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.set(key, value)); + } + + /** + * Set the string value as value of the key. The string can't be longer than 1073741824 bytes (1 + * GB). + * @param key + * @param value + * @param params NX|XX, NX -- Only set the key if it does not already exist. XX -- Only set the + * key if it already exist. EX|PX, expire time units: EX = seconds; PX = milliseconds + * @return Status code reply + */ + @Override + public String set(final String key, final String value, final SetParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.set(key, value, params)); + } + + /** + * Get the value of the specified key. If the key does not exist the special value 'nil' is + * returned. If the value stored at key is not a string an error is returned because GET can only + * handle string values. + *

+ * Time complexity: O(1) + * @param key + * @return Bulk reply + */ + @Override + public String get(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.get(key)); + } + + /** + * Get the value of key and delete the key. This command is similar to GET, except for the fact + * that it also deletes the key on success (if and only if the key's value type is a string). + *

+ * Time complexity: O(1) + * @param key + * @return the value of key + * @since Redis 6.2 + */ + @Override + public String getDel(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.getDel(key)); + } + + @Override + public String getEx(String key, GetExParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.getEx(key, params)); + } + + /** + * Test if the specified keys exist. The command returns the number of keys exist. + * Time complexity: O(N) + * @param keys + * @return Integer reply, specifically: an integer greater than 0 if one or more keys exist, + * 0 if none of the specified keys exist. + */ + @Override + public long exists(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.exists(keys)); + } + + /** + * Test if the specified key exists. The command returns true if the key exists, otherwise false is + * returned. Note that even keys set with an empty string as value will return true. Time + * complexity: O(1) + * @param key + * @return Boolean reply, true if the key exists, otherwise false + */ + @Override + public boolean exists(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.exists(key)); + } + + /** + * Remove the specified keys. If a given key does not exist no operation is performed for this + * key. The command returns the number of keys removed. Time complexity: O(1) + * @param keys + * @return Integer reply, specifically: an integer greater than 0 if one or more keys were removed + * 0 if none of the specified key existed + */ + @Override + public long del(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.del(keys)); + } + + @Override + public long del(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.del(key)); + } + + /** + * This command is very similar to DEL: it removes the specified keys. Just like DEL a key is + * ignored if it does not exist. However the command performs the actual memory reclaiming in a + * different thread, so it is not blocking, while DEL is. This is where the command name comes + * from: the command just unlinks the keys from the keyspace. The actual removal will happen later + * asynchronously. + *

+ * Time complexity: O(1) for each key removed regardless of its size. Then the command does O(N) + * work in a different thread in order to reclaim memory, where N is the number of allocations the + * deleted objects where composed of. + * @param keys + * @return Integer reply: The number of keys that were unlinked + */ + @Override + public long unlink(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.unlink(keys)); + } + + @Override + public long unlink(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.unlink(key)); + } + + /** + * Return the type of the value stored at key in form of a string. The type can be one of "none", + * "string", "list", "set". "none" is returned if the key does not exist. Time complexity: O(1) + * @param key + * @return Status code reply, specifically: "none" if the key does not exist "string" if the key + * contains a String value "list" if the key contains a List value "set" if the key + * contains a Set value "zset" if the key contains a Sorted Set value "hash" if the key + * contains a Hash value + */ + @Override + public String type(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.type(key)); + } + + @Override + public Set keys(final String pattern) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.keys(pattern)); + } + + /** + * Return a randomly selected key from the currently selected DB. + *

+ * Time complexity: O(1) + * @return Singe line reply, specifically the randomly selected key or an empty string is the + * database is empty + */ + @Override + public String randomKey() { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.randomKey()); + } + + /** + * Atomically renames the key oldkey to newkey. If the source and destination name are the same an + * error is returned. If newkey already exists it is overwritten. + *

+ * Time complexity: O(1) + * @param oldkey + * @param newkey + * @return Status code repy + */ + @Override + public String rename(final String oldkey, final String newkey) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.rename(oldkey, newkey)); + } + + /** + * Rename oldkey into newkey but fails if the destination key newkey already exists. + *

+ * Time complexity: O(1) + * @param oldkey + * @param newkey + * @return Integer reply, specifically: 1 if the key was renamed 0 if the target key already exist + */ + @Override + public long renamenx(final String oldkey, final String newkey) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.renamenx(oldkey, newkey)); + } + + /** + * Set a timeout on the specified key. After the timeout the key will be automatically deleted by + * the server. A key with an associated timeout is said to be volatile in Redis terminology. + *

+ * Volatile keys are stored on disk like the other keys, the timeout is persistent too like all + * the other aspects of the dataset. Saving a dataset containing expires and stopping the server + * does not stop the flow of time as Redis stores on disk the time when the key will no longer be + * available as Unix time, and not the remaining seconds. + *

+ * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire + * set. It is also possible to undo the expire at all turning the key into a normal key using the + * {@link #persist(String) PERSIST} command. + *

+ * Time complexity: O(1) + * @see Expire Command + * @param key + * @param seconds + * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since + * the key already has an associated timeout (this may happen only in Redis versions < + * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. + */ + @Override + public long expire(final String key, final long seconds) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.expire(key, seconds)); + } + + /** + * EXPIREAT works exactly like {@link #expire(String, int) EXPIRE} but instead to get the number + * of seconds representing the Time To Live of the key as a second argument (that is a relative + * way of specifying the TTL), it takes an absolute one in the form of a UNIX timestamp (Number of + * seconds elapsed since 1 Gen 1970). + *

+ * EXPIREAT was introduced in order to implement the Append Only File persistence mode so that + * EXPIRE commands are automatically translated into EXPIREAT commands for the append only file. + * Of course EXPIREAT can also used by programmers that need a way to simply specify that a given + * key should expire at a given time in the future. + *

+ * Since Redis 2.1.3 you can update the value of the timeout of a key already having an expire + * set. It is also possible to undo the expire at all turning the key into a normal key using the + * {@link #persist(String) PERSIST} command. + *

+ * Time complexity: O(1) + * @see Expire Command + * @param key + * @param unixTime + * @return Integer reply, specifically: 1: the timeout was set. 0: the timeout was not set since + * the key already has an associated timeout (this may happen only in Redis versions < + * 2.1.3, Redis >= 2.1.3 will happily update the timeout), or the key does not exist. + */ + @Override + public long expireAt(final String key, final long unixTime) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.expireAt(key, unixTime)); + } + + /** + * The TTL command returns the remaining time to live in seconds of a key that has an + * {@link #expire(String, int) EXPIRE} set. This introspection capability allows a Redis connection to + check how many seconds a given key will continue to be part of the dataset. + * @param key + * @return Integer reply, returns the remaining time to live in seconds of a key that has an + * EXPIRE. In Redis 2.6 or older, if the Key does not exists or does not have an + * associated expire, -1 is returned. In Redis 2.8 or newer, if the Key does not have an + * associated expire, -1 is returned or if the Key does not exists, -2 is returned. + */ + @Override + public long ttl(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.ttl(key)); + } + + /** + * Alters the last access time of a key(s). A key is ignored if it does not exist. + * Time complexity: O(N) where N is the number of keys that will be touched. + * @param keys + * @return Integer reply: The number of keys that were touched. + */ + @Override + public long touch(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.touch(keys)); + } + + @Override + public long touch(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.touch(key)); + } + + /** + * Move the specified key from the currently selected DB to the specified destination DB. Note + * that this command returns 1 only if the key was successfully moved, and 0 if the target key was + * already there or if the source key was not found at all, so it is possible to use MOVE as a + * locking primitive. + * @param key + * @param dbIndex + * @return Integer reply, specifically: 1 if the key was moved 0 if the key was not moved because + * already present on the target DB or was not found in the current DB. + */ + @Override + public long move(final String key, final int dbIndex) { + checkIsInMultiOrPipeline(); + connection.sendCommand(MOVE, encode(key), toByteArray(dbIndex)); + return connection.getIntegerReply(); + } + + /** + * GETSET is an atomic set this value and return the old value command. Set key to the string + * value and return the old value stored at key. The string can't be longer than 1073741824 bytes + * (1 GB). + *

+ * Time complexity: O(1) + * @param key + * @param value + * @return Bulk reply + */ + @Override + public String getSet(final String key, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.getSet(key, value)); + } + + /** + * Get the values of all the specified keys. If one or more keys don't exist or is not of type + * String, a 'nil' value is returned instead of the value of the specified key, but the operation + * never fails. + *

+ * Time complexity: O(1) for every key + * @param keys + * @return Multi bulk reply + */ + @Override + public List mget(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.mget(keys)); + } + + /** + * SETNX works exactly like {@link #set(String, String) SET} with the only difference that if the + * key already exists no operation is performed. SETNX actually means "SET if Not eXists". + *

+ * Time complexity: O(1) + * @param key + * @param value + * @return Integer reply, specifically: 1 if the key was set 0 if the key was not set + */ + @Override + public long setnx(final String key, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.setnx(key, value)); + } + + /** + * The command is exactly equivalent to the following group of commands: + * {@link #set(String, String) SET} + {@link #expire(String, int) EXPIRE}. The operation is + * atomic. + *

+ * Time complexity: O(1) + * @param key + * @param seconds + * @param value + * @return Status code reply + */ + @Override + public String setex(final String key, final long seconds, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.setex(key, seconds, value)); + } + + /** + * Set the the respective keys to the respective values. MSET will replace old values with new + * values, while {@link #msetnx(String...) MSETNX} will not perform any operation at all even if + * just a single key already exists. + *

+ * Because of this semantic MSETNX can be used in order to set different keys representing + * different fields of an unique logic object in a way that ensures that either all the fields or + * none at all are set. + *

+ Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B + are modified, another connection talking to Redis can either see the changes to both A and B at + once, or no modification at all. + * @see #msetnx(String...) + * @param keysvalues + * @return Status code reply Basically +OK as MSET can't fail + */ + @Override + public String mset(final String... keysvalues) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.mset(keysvalues)); + } + + /** + * Set the the respective keys to the respective values. {@link #mset(String...) MSET} will + * replace old values with new values, while MSETNX will not perform any operation at all even if + * just a single key already exists. + *

+ * Because of this semantic MSETNX can be used in order to set different keys representing + * different fields of an unique logic object in a way that ensures that either all the fields or + * none at all are set. + *

+ Both MSET and MSETNX are atomic operations. This means that for instance if the keys A and B + are modified, another connection talking to Redis can either see the changes to both A and B at + once, or no modification at all. + * @see #mset(String...) + * @param keysvalues + * @return Integer reply, specifically: 1 if the all the keys were set 0 if no key was set (at + * least one key already existed) + */ + @Override + public long msetnx(final String... keysvalues) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.msetnx(keysvalues)); + } + + /** + * IDECRBY work just like {@link #decr(String) INCR} but instead to decrement by 1 the decrement + * is integer. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are not "integer" types. + * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, + * and then converted back as a string. + *

+ * Time complexity: O(1) + * @see #incr(String) + * @see #decr(String) + * @see #incrBy(String, long) + * @param key + * @param decrement + * @return Integer reply, this commands will reply with the new value of key after the increment. + */ + @Override + public long decrBy(final String key, final long decrement) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.decrBy(key, decrement)); + } + + /** + * Decrement the number stored at key by one. If the key does not exist or contains a value of a + * wrong type, set the key to the value of "0" before to perform the decrement operation. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are not "integer" types. + * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, + * and then converted back as a string. + *

+ * Time complexity: O(1) + * @see #incr(String) + * @see #incrBy(String, long) + * @see #decrBy(String, long) + * @param key + * @return Integer reply, this commands will reply with the new value of key after the increment. + */ + @Override + public long decr(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.decr(key)); + } + + /** + * INCRBY work just like {@link #incr(String) INCR} but instead to increment by 1 the increment is + * integer. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are not "integer" types. + * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, + * and then converted back as a string. + *

+ * Time complexity: O(1) + * @see #incr(String) + * @see #decr(String) + * @see #decrBy(String, long) + * @param key + * @param increment + * @return Integer reply, this commands will reply with the new value of key after the increment. + */ + @Override + public long incrBy(final String key, final long increment) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.incrBy(key, increment)); + } + + /** + * INCRBYFLOAT + *

+ * INCRBYFLOAT commands are limited to double precision floating point values. + *

+ * Note: this is actually a string operation, that is, in Redis there are not "double" types. + * Simply the string stored at the key is parsed as a base double precision floating point value, + * incremented, and then converted back as a string. There is no DECRYBYFLOAT but providing a + * negative value will work as expected. + *

+ * Time complexity: O(1) + * @param key + * @param increment + * @return Double reply, this commands will reply with the new value of key after the increment. + */ + @Override + public double incrByFloat(final String key, final double increment) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.incrByFloat(key, increment)); + } + + /** + * Increment the number stored at key by one. If the key does not exist or contains a value of a + * wrong type, set the key to the value of "0" before to perform the increment operation. + *

+ * INCR commands are limited to 64 bit signed integers. + *

+ * Note: this is actually a string operation, that is, in Redis there are not "integer" types. + * Simply the string stored at the key is parsed as a base 10 64 bit signed integer, incremented, + * and then converted back as a string. + *

+ * Time complexity: O(1) + * @see #incrBy(String, long) + * @see #decr(String) + * @see #decrBy(String, long) + * @param key + * @return Integer reply, this commands will reply with the new value of key after the increment. + */ + @Override + public long incr(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.incr(key)); + } + + /** + * If the key already exists and is a string, this command appends the provided value at the end + * of the string. If the key does not exist it is created and set as an empty string, so APPEND + * will be very similar to SET in this special case. + *

+ * Time complexity: O(1). The amortized time complexity is O(1) assuming the appended value is + * small and the already present value is of any size, since the dynamic string library used by + * Redis will double the free space available on every reallocation. + * @param key + * @param value + * @return Integer reply, specifically the total length of the string after the append operation. + */ + @Override + public long append(final String key, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.append(key, value)); + } + + /** + * Return a subset of the string from offset start to offset end (both offsets are inclusive). + * Negative offsets can be used in order to provide an offset starting from the end of the string. + * So -1 means the last char, -2 the penultimate and so forth. + *

+ * The function handles out of range requests without raising an error, but just limiting the + * resulting range to the actual length of the string. + *

+ * Time complexity: O(start+n) (with start being the start index and n the total length of the + * requested range). Note that the lookup part of this command is O(1) so for small strings this + * is actually an O(1) command. + * @param key + * @param start + * @param end + * @return Bulk reply + */ + @Override + public String substr(final String key, final int start, final int end) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.substr(key, start, end)); + } + + /** + * Set the specified hash field to the specified value. + *

+ * If key does not exist, a new key holding a hash is created. + *

+ * Time complexity: O(1) + * @param key + * @param field + * @param value + * @return If the field already exists, and the HSET just produced an update of the value, 0 is + * returned, otherwise if a new field is created 1 is returned. + */ + @Override + public long hset(final String key, final String field, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hset(key, field, value)); + } + + @Override + public long hset(final String key, final Map hash) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hset(key, hash)); + } + + /** + * If key holds a hash, retrieve the value associated to the specified field. + *

+ * If the field is not found or the key does not exist, a special 'nil' value is returned. + *

+ * Time complexity: O(1) + * @param key + * @param field + * @return Bulk reply + */ + @Override + public String hget(final String key, final String field) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hget(key, field)); + } + + /** + * Set the specified hash field to the specified value if the field not exists. Time + * complexity: O(1) + * @param key + * @param field + * @param value + * @return If the field already exists, 0 is returned, otherwise if a new field is created 1 is + * returned. + */ + @Override + public long hsetnx(final String key, final String field, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hsetnx(key, field, value)); + } + + /** + * Set the respective fields to the respective values. HMSET replaces old values with new values. + *

+ * If key does not exist, a new key holding a hash is created. + *

+ * Time complexity: O(N) (with N being the number of fields) + * @param key + * @param hash + * @return Return OK or Exception if hash is empty + */ + @Override + public String hmset(final String key, final Map hash) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hmset(key, hash)); + } + + /** + * Retrieve the values associated to the specified fields. + *

+ * If some of the specified fields do not exist, nil values are returned. Non existing keys are + * considered like empty hashes. + *

+ * Time complexity: O(N) (with N being the number of fields) + * @param key + * @param fields + * @return Multi Bulk Reply specifically a list of all the values associated with the specified + * fields, in the same order of the request. + */ + @Override + public List hmget(final String key, final String... fields) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hmget(key, fields)); + } + + /** + * Increment the number stored at field in the hash at key by value. If key does not exist, a new + * key holding a hash is created. If field does not exist or holds a string, the value is set to 0 + * before applying the operation. Since the value argument is signed you can use this command to + * perform both increments and decrements. + *

+ * The range of values supported by HINCRBY is limited to 64 bit signed integers. + *

+ * Time complexity: O(1) + * @param key + * @param field + * @param value + * @return Integer reply The new value at field after the increment operation. + */ + @Override + public long hincrBy(final String key, final String field, final long value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hincrBy(key, field, value)); + } + + /** + * Increment the number stored at field in the hash at key by a double precision floating point + * value. If key does not exist, a new key holding a hash is created. If field does not exist or + * holds a string, the value is set to 0 before applying the operation. Since the value argument + * is signed you can use this command to perform both increments and decrements. + *

+ * The range of values supported by HINCRBYFLOAT is limited to double precision floating point + * values. + *

+ * Time complexity: O(1) + * @param key + * @param field + * @param value + * @return Double precision floating point reply The new value at field after the increment + * operation. + */ + @Override + public double hincrByFloat(final String key, final String field, final double value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hincrByFloat(key, field, value)); + } + + /** + * Test for existence of a specified field in a hash. Time complexity: O(1) + * @param key + * @param field + * @return Return true if the hash stored at key contains the specified field. Return false if the key is + * not found or the field is not present. + */ + @Override + public boolean hexists(final String key, final String field) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hexists(key, field)); + } + + /** + * Remove the specified field from an hash stored at key. + *

+ * Time complexity: O(1) + * @param key + * @param fields + * @return If the field was present in the hash it is deleted and 1 is returned, otherwise 0 is + * returned and no operation is performed. + */ + @Override + public long hdel(final String key, final String... fields) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hdel(key, fields)); + } + + /** + * Return the number of items in a hash. + *

+ * Time complexity: O(1) + * @param key + * @return The number of entries (fields) contained in the hash stored at key. If the specified + * key does not exist, 0 is returned assuming an empty hash. + */ + @Override + public long hlen(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hlen(key)); + } + + /** + * Return all the fields in a hash. + *

+ * Time complexity: O(N), where N is the total number of entries + * @param key + * @return All the fields names contained into a hash. + */ + @Override + public Set hkeys(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hkeys(key)); + } + + /** + * Return all the values in a hash. + *

+ * Time complexity: O(N), where N is the total number of entries + * @param key + * @return All the fields values contained into a hash. + */ + @Override + public List hvals(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hvals(key)); + } + + /** + * Return all the fields and associated values in a hash. + *

+ * Time complexity: O(N), where N is the total number of entries + * @param key + * @return All the fields and values contained into a hash. + */ + @Override + public Map hgetAll(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hgetAll(key)); + } + + /** + * Get one random field from a hash. + *

+ * Time complexity: O(N), where N is the number of fields returned + * @param key + * @return one random field from a hash. + */ + @Override + public String hrandfield(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hrandfield(key)); + } + + /** + * Get multiple random fields from a hash. + *

+ * Time complexity: O(N), where N is the number of fields returned + * @param key + * @param count + * @return multiple random fields from a hash. + */ + @Override + public List hrandfield(final String key, final long count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hrandfield(key, count)); + } + + /** + * Get one or multiple random fields with values from a hash. + *

+ * Time complexity: O(N), where N is the number of fields returned + * @param key + * @param count + * @return one or multiple random fields with values from a hash. + */ + @Override + public Map hrandfieldWithValues(final String key, final long count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + /** + * Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key + * does not exist an empty list is created just before the append operation. If the key exists but + * is not a List an error is returned. + *

+ * Time complexity: O(1) + * @param key + * @param strings + * @return Integer reply, specifically, the number of elements inside the list after the push + * operation. + */ + @Override + public long rpush(final String key, final String... strings) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.rpush(key, strings)); + } + + /** + * Add the string value to the head (LPUSH) or tail (RPUSH) of the list stored at key. If the key + * does not exist an empty list is created just before the append operation. If the key exists but + * is not a List an error is returned. + *

+ * Time complexity: O(1) + * @param key + * @param strings + * @return Integer reply, specifically, the number of elements inside the list after the push + * operation. + */ + @Override + public long lpush(final String key, final String... strings) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpush(key, strings)); + } + + /** + * Return the length of the list stored at the specified key. If the key does not exist zero is + * returned (the same behaviour as for empty lists). If the value stored at key is not a list an + * error is returned. + *

+ * Time complexity: O(1) + * @param key + * @return The length of the list. + */ + @Override + public long llen(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.llen(key)); + } + + /** + * Return the specified elements of the list stored at the specified key. Start and end are + * zero-based indexes. 0 is the first element of the list (the list head), 1 the next element and + * so on. + *

+ * For example LRANGE foobar 0 2 will return the first three elements of the list. + *

+ * start and end can also be negative numbers indicating offsets from the end of the list. For + * example -1 is the last element of the list, -2 the penultimate element and so on. + *

+ * Consistency with range functions in various programming languages + *

+ * Note that if you have a list of numbers from 0 to 100, LRANGE 0 10 will return 11 elements, + * that is, rightmost item is included. This may or may not be consistent with behavior of + * range-related functions in your programming language of choice (think Ruby's Range.new, + * Array#slice or Python's range() function). + *

+ * LRANGE behavior is consistent with one of Tcl. + *

+ * Out-of-range indexes + *

+ * Indexes out of range will not produce an error: if start is over the end of the list, or start + * > end, an empty list is returned. If end is over the end of the list Redis will threat it + * just like the last element of the list. + *

+ * Time complexity: O(start+n) (with n being the length of the range and start being the start + * offset) + * @param key + * @param start + * @param stop + * @return Multi bulk reply, specifically a list of elements in the specified range. + */ + @Override + public List lrange(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lrange(key, start, stop)); + } + + /** + * Trim an existing list so that it will contain only the specified range of elements specified. + * Start and end are zero-based indexes. 0 is the first element of the list (the list head), 1 the + * next element and so on. + *

+ * For example LTRIM foobar 0 2 will modify the list stored at foobar key so that only the first + * three elements of the list will remain. + *

+ * start and end can also be negative numbers indicating offsets from the end of the list. For + * example -1 is the last element of the list, -2 the penultimate element and so on. + *

+ * Indexes out of range will not produce an error: if start is over the end of the list, or start + * > end, an empty list is left as value. If end over the end of the list Redis will threat it + * just like the last element of the list. + *

+ * Hint: the obvious use of LTRIM is together with LPUSH/RPUSH. For example: + *

+ * {@code lpush("mylist", "someelement"); ltrim("mylist", 0, 99); * } + *

+ * The above two commands will push elements in the list taking care that the list will not grow + * without limits. This is very useful when using Redis to store logs for example. It is important + * to note that when used in this way LTRIM is an O(1) operation because in the average case just + * one element is removed from the tail of the list. + *

+ * Time complexity: O(n) (with n being len of list - len of range) + * @param key + * @param start + * @param stop + * @return Status code reply + */ + @Override + public String ltrim(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.ltrim(key, start, stop)); + } + + /** + * Return the specified element of the list stored at the specified key. 0 is the first element, 1 + * the second and so on. Negative indexes are supported, for example -1 is the last element, -2 + * the penultimate and so on. + *

+ * If the value stored at key is not of list type an error is returned. If the index is out of + * range a 'nil' reply is returned. + *

+ * Note that even if the average time complexity is O(n) asking for the first or the last element + * of the list is O(1). + *

+ * Time complexity: O(n) (with n being the length of the list) + * @param key + * @param index + * @return Bulk reply, specifically the requested element + */ + @Override + public String lindex(final String key, final long index) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lindex(key, index)); + } + + /** + * Set a new value as the element at index position of the List at key. + *

+ * Out of range indexes will generate an error. + *

+ * Similarly to other list commands accepting indexes, the index can be negative to access + * elements starting from the end of the list. So -1 is the last element, -2 is the penultimate, + * and so forth. + *

+ * Time complexity: + *

+ * O(N) (with N being the length of the list), setting the first or last elements of the list is + * O(1). + * @see #lindex(String, long) + * @param key + * @param index + * @param value + * @return Status code reply + */ + @Override + public String lset(final String key, final long index, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lset(key, index, value)); + } + + /** + * Remove the first count occurrences of the value element from the list. If count is zero all the + * elements are removed. If count is negative elements are removed from tail to head, instead to + * go from head to tail that is the normal behaviour. So for example LREM with count -2 and hello + * as value to remove against the list (a,b,c,hello,x,hello,hello) will leave the list + * (a,b,c,hello,x). The number of removed elements is returned as an integer, see below for more + * information about the returned value. Note that non existing keys are considered like empty + * lists by LREM, so LREM against non existing keys will always return 0. + *

+ * Time complexity: O(N) (with N being the length of the list) + * @param key + * @param count + * @param value + * @return Integer Reply, specifically: The number of removed elements if the operation succeeded + */ + @Override + public long lrem(final String key, final long count, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lrem(key, count, value)); + } + + /** + * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example + * if the list contains the elements "a","b","c" LPOP will return "a" and the list will become + * "b","c". + *

+ * If the key does not exist or the list is already empty the special value 'nil' is returned. + * @see #rpop(String) + * @param key + * @return Bulk reply + */ + @Override + public String lpop(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpop(key)); + } + + @Override + public List lpop(final String key, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpop(key, count)); + } + + @Override + public Long lpos(final String key, final String element) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpos(key, element)); + } + + @Override + public Long lpos(final String key, final String element, final LPosParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public List lpos(final String key, final String element, final LPosParams params, + final long count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lpos(key, element, params, count)); + } + + /** + * Atomically return and remove the first (LPOP) or last (RPOP) element of the list. For example + * if the list contains the elements "a","b","c" RPOP will return "c" and the list will become + * "a","b". + *

+ * If the key does not exist or the list is already empty the special value 'nil' is returned. + * @see #lpop(String) + * @param key + * @return Bulk reply + */ + @Override + public String rpop(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.rpop(key)); + } + + @Override + public List rpop(final String key, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.rpop(key, count)); + } + + /** + * Atomically return and remove the last (tail) element of the srckey list, and push the element + * as the first (head) element of the dstkey list. For example if the source list contains the + * elements "a","b","c" and the destination list contains the elements "foo","bar" after an + * RPOPLPUSH command the content of the two lists will be "a","b" and "c","foo","bar". + *

+ * If the key does not exist or the list is already empty the special value 'nil' is returned. If + * the srckey and dstkey are the same the operation is equivalent to removing the last element + * from the list and pushing it as first element of the list, so it's a "list rotation" command. + *

+ * Time complexity: O(1) + * @param srckey + * @param dstkey + * @return Bulk reply + */ + @Override + public String rpoplpush(final String srckey, final String dstkey) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.rpoplpush(srckey, dstkey)); + } + + /** + * Add the specified member to the set value stored at key. If member is already a member of the + * set no operation is performed. If key does not exist a new set with the specified member as + * sole member is created. If the key exists but does not hold a set value an error is returned. + *

+ * Time complexity O(1) + * @param key + * @param members + * @return Integer reply, specifically: 1 if the new element was added 0 if the element was + * already a member of the set + */ + @Override + public long sadd(final String key, final String... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sadd(key, members)); + } + + /** + * Return all the members (elements) of the set value stored at key. This is just syntax glue for + * {@link #sinter(String...) SINTER}. + *

+ * Time complexity O(N) + * @param key + * @return Multi bulk reply + */ + @Override + public Set smembers(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.smembers(key)); + } + + /** + * Remove the specified member from the set value stored at key. If member was not a member of the + * set no operation is performed. If key does not hold a set value an error is returned. + *

+ * Time complexity O(1) + * @param key + * @param members + * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was + * not a member of the set + */ + @Override + public long srem(final String key, final String... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.srem(key, members)); + } + + /** + * Remove a random element from a Set returning it as return value. If the Set is empty or the key + * does not exist, a nil object is returned. + *

+ * The {@link #srandmember(String)} command does a similar work but the returned element is not + * removed from the Set. + *

+ * Time complexity O(1) + * @param key + * @return Bulk reply + */ + @Override + public String spop(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.spop(key)); + } + + @Override + public Set spop(final String key, final long count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.spop(key, count)); + } + + /** + * Move the specified member from the set at srckey to the set at dstkey. This operation is + * atomic, in every given moment the element will appear to be in the source or destination set + * for accessing clients. + *

+ * If the source set does not exist or does not contain the specified element no operation is + * performed and zero is returned, otherwise the element is removed from the source set and added + * to the destination set. On success one is returned, even if the element was already present in + * the destination set. + *

+ * An error is raised if the source or destination keys contain a non Set value. + *

+ * Time complexity O(1) + * @param srckey + * @param dstkey + * @param member + * @return Integer reply, specifically: 1 if the element was moved 0 if the element was not found + * on the first set and no operation was performed + */ + @Override + public long smove(final String srckey, final String dstkey, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.smove(srckey, dstkey, member)); + } + + /** + * Return the set cardinality (number of elements). If the key does not exist 0 is returned, like + * for empty sets. + * @param key + * @return Integer reply, specifically: the cardinality (number of elements) of the set as an + * integer. + */ + @Override + public long scard(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.scard(key)); + } + + /** + * Return true if member is a member of the set stored at key, otherwise false is returned. + *

+ * Time complexity O(1) + * @param key + * @param member + * @return Boolean reply, specifically: true if the element is a member of the set false if the + * element is not a member of the set OR if the key does not exist + */ + @Override + public boolean sismember(final String key, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sismember(key, member)); + } + + /** + * Returns whether each member is a member of the set stored at key. + *

+ * Time complexity O(N) where N is the number of elements being checked for membership + * @param key + * @param members + * @return List representing the membership of the given elements, in the same order as they are + * requested. + */ + @Override + public List smismember(final String key, final String... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.smismember(key, members)); + } + + /** + * Return the members of a set resulting from the intersection of all the sets hold at the + * specified keys. Like in {@link #lrange(String, long, long) LRANGE} the result is sent to the + connection as a multi-bulk reply (see the protocol specification for more information). If just a + single key is specified, then this command produces the same result as + {@link #smembers(String) SMEMBERS}. Actually SMEMBERS is just syntax sugar for SINTER. + *

+ * Non existing keys are considered like empty sets, so if one of the keys is missing an empty set + * is returned (since the intersection with an empty set always is an empty set). + *

+ * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the + * number of sets + * @param keys + * @return Multi bulk reply, specifically the list of common elements. + */ + @Override + public Set sinter(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sinter(keys)); + } + + /** + * This command works exactly like {@link #sinter(String...) SINTER} but instead of being returned + * the resulting set is stored as dstkey. + *

+ * Time complexity O(N*M) worst case where N is the cardinality of the smallest set and M the + * number of sets + * @param dstkey + * @param keys + * @return Status code reply + */ + @Override + public long sinterstore(final String dstkey, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sinterstore(dstkey, keys)); + } + + /** + * Return the members of a set resulting from the union of all the sets hold at the specified + * keys. Like in {@link #lrange(String, long, long) LRANGE} the result is sent to the connection as a + multi-bulk reply (see the protocol specification for more information). If just a single key is + specified, then this command produces the same result as {@link #smembers(String) SMEMBERS}. + *

+ * Non existing keys are considered like empty sets. + *

+ * Time complexity O(N) where N is the total number of elements in all the provided sets + * @param keys + * @return Multi bulk reply, specifically the list of common elements. + */ + @Override + public Set sunion(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sunion(keys)); + } + + /** + * This command works exactly like {@link #sunion(String...) SUNION} but instead of being returned + * the resulting set is stored as dstkey. Any existing value in dstkey will be over-written. + *

+ * Time complexity O(N) where N is the total number of elements in all the provided sets + * @param dstkey + * @param keys + * @return Status code reply + */ + @Override + public long sunionstore(final String dstkey, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sunionstore(dstkey, keys)); + } + + /** + * Return the difference between the Set stored at key1 and all the Sets key2, ..., keyN + *

+ * Example: + * + *

+   * key1 = [x, a, b, c]
+   * key2 = [c]
+   * key3 = [a, d]
+   * SDIFF key1,key2,key3 => [x, b]
+   * 
+ * + * Non existing keys are considered like empty sets. + *

+ * Time complexity: + *

+ * O(N) with N being the total number of elements of all the sets + * @param keys + * @return Return the members of a set resulting from the difference between the first set + * provided and all the successive sets. + */ + @Override + public Set sdiff(final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sdiff(keys)); + } + + /** + * This command works exactly like {@link #sdiff(String...) SDIFF} but instead of being returned + * the resulting set is stored in dstkey. + * @param dstkey + * @param keys + * @return Status code reply + */ + @Override + public long sdiffstore(final String dstkey, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sdiffstore(dstkey, keys)); + } + + /** + * Return a random element from a Set, without removing the element. If the Set is empty or the + * key does not exist, a nil object is returned. + *

+ * The SPOP command does a similar work but the returned element is popped (removed) from the Set. + *

+ * Time complexity O(1) + * @param key + * @return Bulk reply + */ + @Override + public String srandmember(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.srandmember(key)); + } + + /** + * Return a random elements from a Set, without removing the elements. If the Set is empty or the + * key does not exist, an empty list is returned. + *

+ * The SPOP command does a similar work but the returned elements is popped (removed) from the Set. + *

+ * Time complexity O(1) + * @param key + * @param count if positive, return an array of distinct elements. + * If negative the behavior changes and the command is allowed to + * return the same element multiple times + * @return list of elements + */ + @Override + public List srandmember(final String key, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.srandmember(key, count)); + } + + /** + * Add the specified member having the specified score to the sorted set stored at key. If member + * is already a member of the sorted set the score is updated, and the element reinserted in the + * right position to ensure sorting. If key does not exist a new sorted set with the specified + * member as sole member is created. If the key exists but does not hold a sorted set value an + * error is returned. + *

+ * The score value can be the string representation of a double precision floating point number. + *

+ * Time complexity O(log(N)) with N being the number of elements in the sorted set + * @param key + * @param score + * @param member + * @return Integer reply, specifically: 1 if the new element was added 0 if the element was + * already a member of the sorted set and the score was updated + */ + @Override + public long zadd(final String key, final double score, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public long zadd(final String key, final double score, final String member, + final ZAddParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public long zadd(final String key, final Map scoreMembers) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public long zadd(final String key, final Map scoreMembers, final ZAddParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Double zaddIncr(final String key, final double score, final String member, final ZAddParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Set zdiff(String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zdiff(keys)); + } + + @Override + public Set zdiffWithScores(String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public long zdiffStore(final String dstkey, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zdiffStore(dstkey, keys)); + } + + @Override + public List zrange(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrange(key, start, stop)); + } + + /** + * Remove the specified member from the sorted set value stored at key. If member was not a member + * of the set no operation is performed. If key does not not hold a set value an error is + * returned. + *

+ * Time complexity O(log(N)) with N being the number of elements in the sorted set + * @param key + * @param members + * @return Integer reply, specifically: 1 if the new element was removed 0 if the new element was + * not a member of the set + */ + @Override + public long zrem(final String key, final String... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrem(key, members)); + } + + /** + * If member already exists in the sorted set adds the increment to its score and updates the + * position of the element in the sorted set accordingly. If member does not already exist in the + * sorted set it is added with increment as score (that is, like if the previous score was + * virtually zero). If key does not exist a new sorted set with the specified member as sole + * member is created. If the key exists but does not hold a sorted set value an error is returned. + *

+ * The score value can be the string representation of a double precision floating point number. + * It's possible to provide a negative value to perform a decrement. + *

+ * For an introduction to sorted sets check the Introduction to Redis data types page. + *

+ * Time complexity O(log(N)) with N being the number of elements in the sorted set + * @param key + * @param increment + * @param member + * @return The new score + */ + @Override + public double zincrby(final String key, final double increment, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Double zincrby(final String key, final double increment, final String member, + final ZIncrByParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zincrby(key, increment, member, params)); + } + + /** + * Return the rank (or index) of member in the sorted set at key, with scores being ordered from + * low to high. + *

+ * When the given member does not exist in the sorted set, the special value 'nil' is returned. + * The returned rank (or index) of the member is 0-based for both commands. + *

+ * Time complexity: + *

+ * O(log(N)) + * @see #zrevrank(String, String) + * @param key + * @param member + * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer + * reply if the element exists. A nil bulk reply if there is no such element. + */ + @Override + public Long zrank(final String key, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrank(key, member)); + } + + /** + * Return the rank (or index) of member in the sorted set at key, with scores being ordered from + * high to low. + *

+ * When the given member does not exist in the sorted set, the special value 'nil' is returned. + * The returned rank (or index) of the member is 0-based for both commands. + *

+ * Time complexity: + *

+ * O(log(N)) + * @see #zrank(String, String) + * @param key + * @param member + * @return Integer reply or a nil bulk reply, specifically: the rank of the element as an integer + * reply if the element exists. A nil bulk reply if there is no such element. + */ + @Override + public Long zrevrank(final String key, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public List zrevrange(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public List zrangeWithScores(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public List zrevrangeWithScores(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public String zrandmember(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrandmember(key)); + } + + @Override + public List zrandmember(final String key, final long count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public List zrandmemberWithScores(final String key, final long count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + /** + * Return the sorted set cardinality (number of elements). If the key does not exist 0 is + * returned, like for empty sorted sets. + *

+ * Time complexity O(1) + * @param key + * @return the cardinality (number of elements) of the set as an integer. + */ + @Override + public long zcard(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zcard(key)); + } + + /** + * Return the score of the specified element of the sorted set at key. If the specified element + * does not exist in the sorted set, or the key does not exist at all, a special 'nil' value is + * returned. + *

+ * Time complexity: O(1) + * @param key + * @param member + * @return the score + */ + @Override + public Double zscore(final String key, final String member) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zscore(key, member)); + } + + /** + * Returns the scores associated with the specified members in the sorted set stored at key. For + * every member that does not exist in the sorted set, a nil value is returned. + *

+ * Time complexity: O(N) where N is the number of members being requested. + * @param key + * @param members + * @return the scores + */ + @Override + public List zmscore(final String key, final String... members) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Tuple zpopmax(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zpopmax(key)); + } + + @Override + public List zpopmax(final String key, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Tuple zpopmin(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zpopmin(key)); + } + + @Override + public List zpopmin(final String key, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zpopmin(key, count)); + } + + public String watch(final String... keys) { + checkIsInMultiOrPipeline(); + connection.sendCommand(WATCH, keys); +// return connection.getStatusCodeReply(); + String status = connection.getStatusCodeReply(); + isInWatch = true; + return status; + } + + /** + * Sort a Set or a List. + *

+ * Sort the elements contained in the List, Set, or Sorted Set value at key. By default sorting is + * numeric with elements being compared as double precision floating point numbers. This is the + * simplest form of SORT. + * @see #sort(String, String) + * @see #sort(String, SortingParams) + * @see #sort(String, SortingParams, String) + * @param key + * @return Assuming the Set/List at key contains a list of numbers, the return value will be the + * list of numbers ordered from the smallest to the biggest number. + */ + @Override + public List sort(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sort(key)); + } + + /** + * Sort a Set or a List accordingly to the specified parameters. + *

+ * examples: + *

+ * Given are the following sets and key/values: + * + *

+   * x = [1, 2, 3]
+   * y = [a, b, c]
+   *
+   * k1 = z
+   * k2 = y
+   * k3 = x
+   *
+   * w1 = 9
+   * w2 = 8
+   * w3 = 7
+   * 
+ * + * Sort Order: + * + *
+   * sort(x) or sort(x, sp.asc())
+   * -> [1, 2, 3]
+   *
+   * sort(x, sp.desc())
+   * -> [3, 2, 1]
+   *
+   * sort(y)
+   * -> [c, a, b]
+   *
+   * sort(y, sp.alpha())
+   * -> [a, b, c]
+   *
+   * sort(y, sp.alpha().desc())
+   * -> [c, a, b]
+   * 
+ * + * Limit (e.g. for Pagination): + * + *
+   * sort(x, sp.limit(0, 2))
+   * -> [1, 2]
+   *
+   * sort(y, sp.alpha().desc().limit(1, 2))
+   * -> [b, a]
+   * 
+ * + * Sorting by external keys: + * + *
+   * sort(x, sb.by(w*))
+   * -> [3, 2, 1]
+   *
+   * sort(x, sb.by(w*).desc())
+   * -> [1, 2, 3]
+   * 
+ * + * Getting external keys: + * + *
+   * sort(x, sp.by(w*).get(k*))
+   * -> [x, y, z]
+   *
+   * sort(x, sp.by(w*).get(#).get(k*))
+   * -> [3, x, 2, y, 1, z]
+   * 
+ * @see #sort(String) + * @see #sort(String, SortingParams, String) + * @param key + * @param sortingParameters + * @return a list of sorted elements. + */ + @Override + public List sort(final String key, final SortingParams sortingParameters) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sort(key, sortingParameters)); + } + + /** + * Sort a Set or a List accordingly to the specified parameters and store the result at dstkey. + * @see #sort(String, SortingParams) + * @see #sort(String) + * @see #sort(String, String) + * @param key + * @param sortingParameters + * @param dstkey + * @return The number of elements of the list at dstkey. + */ + @Override + public long sort(final String key, final SortingParams sortingParameters, final String dstkey) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sort(key, sortingParameters, dstkey)); + } + + /** + * Sort a Set or a List and Store the Result at dstkey. + *

+ * Sort the elements contained in the List, Set, or Sorted Set value at key and store the result + * at dstkey. By default sorting is numeric with elements being compared as double precision + * floating point numbers. This is the simplest form of SORT. + * @see #sort(String) + * @see #sort(String, SortingParams) + * @see #sort(String, SortingParams, String) + * @param key + * @param dstkey + * @return The number of elements of the list at dstkey. + */ + @Override + public long sort(final String key, final String dstkey) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.sort(key, dstkey)); + } + + @Override + public String lmove(final String srcKey, final String dstKey, final ListDirection from, + final ListDirection to) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public String blmove(final String srcKey, final String dstKey, final ListDirection from, + final ListDirection to, final double timeout) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + /** + * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking + * versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty + * lists. + *

+ * The following is a description of the exact semantic. We describe BLPOP but the two commands + * are identical, the only difference is that BLPOP pops the element from the left (head) of the + * list, and BRPOP pops from the right (tail). + *

+ * Non blocking behavior + *

+ * When BLPOP is called, if at least one of the specified keys contain a non empty list, an + * element is popped from the head of the list and returned to the caller together with the name + * of the key (BLPOP returns a two elements array, the first element is the key, the second the + * popped value). + *

+ * Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0 + * against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP + * guarantees to return an element from the list stored at list2 (since it is the first non empty + * list starting from the left). + *

+ * Blocking behavior + *

+ If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other + connection performs a LPUSH or an RPUSH operation against one of the lists. +

+ Once new data is present on one of the lists, the connection finally returns with the name of the + key unblocking it and the popped value. +

+ When blocking, if a non-zero timeout is specified, the connection will unblock returning a nil + special value if the specified amount of seconds passed without a push operation against at + least one of the specified keys. +

+ * The timeout argument is interpreted as an integer value. A timeout of zero means instead to + * block forever. + *

+ * Multiple clients blocking for the same keys + *

+ * Multiple clients can block for the same key. They are put into a queue, so the first to be + * served will be the one that started to wait earlier, in a first-blpopping first-served fashion. + *

+ * blocking POP inside a MULTI/EXEC transaction + *

+ * BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies + * in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis + * transaction). + *

+ * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil + * reply, exactly what happens when the timeout is reached. If you like science fiction, think at + * it like if inside MULTI/EXEC the time will flow at infinite speed :) + *

+ * Time complexity: O(1) + * @see #brpop(int, String...) + * @param timeout + * @param keys + * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the + * unblocking key and the popped value. + *

+ When a non-zero timeout is specified, and the BLPOP operation timed out, the return + value is a nil multi bulk reply. Most connection values will return false or nil + accordingly to the programming language used. + */ + @Override + public List blpop(final int timeout, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public KeyedListElement blpop(final double timeout, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.blpop(timeout, keys)); + } + + /** + * BLPOP (and BRPOP) is a blocking list pop primitive. You can see this commands as blocking + * versions of LPOP and RPOP able to block if the specified keys don't exist or contain empty + * lists. + *

+ * The following is a description of the exact semantic. We describe BLPOP but the two commands + * are identical, the only difference is that BLPOP pops the element from the left (head) of the + * list, and BRPOP pops from the right (tail). + *

+ * Non blocking behavior + *

+ * When BLPOP is called, if at least one of the specified keys contain a non empty list, an + * element is popped from the head of the list and returned to the caller together with the name + * of the key (BLPOP returns a two elements array, the first element is the key, the second the + * popped value). + *

+ * Keys are scanned from left to right, so for instance if you issue BLPOP list1 list2 list3 0 + * against a dataset where list1 does not exist but list2 and list3 contain non empty lists, BLPOP + * guarantees to return an element from the list stored at list2 (since it is the first non empty + * list starting from the left). + *

+ * Blocking behavior + *

+ If none of the specified keys exist or contain non empty lists, BLPOP blocks until some other + connection performs a LPUSH or an RPUSH operation against one of the lists. +

+ Once new data is present on one of the lists, the connection finally returns with the name of the + key unblocking it and the popped value. +

+ When blocking, if a non-zero timeout is specified, the connection will unblock returning a nil + special value if the specified amount of seconds passed without a push operation against at + least one of the specified keys. +

+ * The timeout argument is interpreted as an integer value. A timeout of zero means instead to + * block forever. + *

+ * Multiple clients blocking for the same keys + *

+ * Multiple clients can block for the same key. They are put into a queue, so the first to be + * served will be the one that started to wait earlier, in a first-blpopping first-served fashion. + *

+ * blocking POP inside a MULTI/EXEC transaction + *

+ * BLPOP and BRPOP can be used with pipelining (sending multiple commands and reading the replies + * in batch), but it does not make sense to use BLPOP or BRPOP inside a MULTI/EXEC block (a Redis + * transaction). + *

+ * The behavior of BLPOP inside MULTI/EXEC when the list is empty is to return a multi-bulk nil + * reply, exactly what happens when the timeout is reached. If you like science fiction, think at + * it like if inside MULTI/EXEC the time will flow at infinite speed :) + *

+ * Time complexity: O(1) + * @see #blpop(int, String...) + * @param timeout + * @param keys + * @return BLPOP returns a two-elements array via a multi bulk reply in order to return both the + * unblocking key and the popped value. + *

+ When a non-zero timeout is specified, and the BLPOP operation timed out, the return + value is a nil multi bulk reply. Most connection values will return false or nil + accordingly to the programming language used. + */ + @Override + public List brpop(final int timeout, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public KeyedListElement brpop(final double timeout, final String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public KeyedZSetElement bzpopmax(double timeout, String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public KeyedZSetElement bzpopmin(double timeout, String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public List blpop(final int timeout, final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public KeyedListElement blpop(double timeout, String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public List brpop(final int timeout, final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public KeyedListElement brpop(double timeout, String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public long zcount(final String key, final double min, final double max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public long zcount(final String key, final String min, final String max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zcount(key, min, max)); + } + + /** + * Return the all the elements in the sorted set at key with a score between min and max + * (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically as ASCII strings (this + * follows from a property of Redis sorted sets and does not involve further computation). + *

+ * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large + * the commands needs to traverse the list for offset elements and this adds up to the O(M) + * figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * actual elements in the specified interval, it just returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know what's the greatest or + * smallest element in order to take, for instance, elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible to specify open + * intervals prefixing the score with a "(" character, so for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of + * elements returned by the command, so if M is constant (for instance you always ask for the + * first ten elements with LIMIT) you can consider it O(log(N)) + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, String, String) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * @param key + * @param min a double or Double.NEGATIVE_INFINITY for "-inf" + * @param max a double or Double.POSITIVE_INFINITY for "+inf" + * @return Multi bulk reply specifically a list of elements in the specified score range. + */ + @Override + public List zrangeByScore(final String key, final double min, final double max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public List zrangeByScore(final String key, final String min, final String max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max)); + } + + /** + * Return the all the elements in the sorted set at key with a score between min and max + * (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically as ASCII strings (this + * follows from a property of Redis sorted sets and does not involve further computation). + *

+ * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large + * the commands needs to traverse the list for offset elements and this adds up to the O(M) + * figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * actual elements in the specified interval, it just returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know what's the greatest or + * smallest element in order to take, for instance, elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible to specify open + * intervals prefixing the score with a "(" character, so for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of + * elements returned by the command, so if M is constant (for instance you always ask for the + * first ten elements with LIMIT) you can consider it O(log(N)) + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * @param key + * @param min + * @param max + * @param offset + * @param count + * @return Multi bulk reply specifically a list of elements in the specified score range. + */ + @Override + public List zrangeByScore(final String key, final double min, final double max, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public List zrangeByScore(final String key, final String min, final String max, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + /** + * Return the all the elements in the sorted set at key with a score between min and max + * (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically as ASCII strings (this + * follows from a property of Redis sorted sets and does not involve further computation). + *

+ * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large + * the commands needs to traverse the list for offset elements and this adds up to the O(M) + * figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * actual elements in the specified interval, it just returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know what's the greatest or + * smallest element in order to take, for instance, elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible to specify open + * intervals prefixing the score with a "(" character, so for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of + * elements returned by the command, so if M is constant (for instance you always ask for the + * first ten elements with LIMIT) you can consider it O(log(N)) + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * @param key + * @param min + * @param max + * @return Multi bulk reply specifically a list of elements in the specified score range. + */ + @Override + public List zrangeByScoreWithScores(final String key, final double min, final double max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public List zrangeByScoreWithScores(final String key, final String min, final String max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + /** + * Return the all the elements in the sorted set at key with a score between min and max + * (including elements with score equal to min or max). + *

+ * The elements having the same score are returned sorted lexicographically as ASCII strings (this + * follows from a property of Redis sorted sets and does not involve further computation). + *

+ * Using the optional {@link #zrangeByScore(String, double, double, int, int) LIMIT} it's possible + * to get only a range of the matching elements in an SQL-alike way. Note that if offset is large + * the commands needs to traverse the list for offset elements and this adds up to the O(M) + * figure. + *

+ * The {@link #zcount(String, double, double) ZCOUNT} command is similar to + * {@link #zrangeByScore(String, double, double) ZRANGEBYSCORE} but instead of returning the + * actual elements in the specified interval, it just returns the number of matching elements. + *

+ * Exclusive intervals and infinity + *

+ * min and max can be -inf and +inf, so that you are not required to know what's the greatest or + * smallest element in order to take, for instance, elements "up to a given value". + *

+ * Also while the interval is for default closed (inclusive) it's possible to specify open + * intervals prefixing the score with a "(" character, so for instance: + *

+ * {@code ZRANGEBYSCORE zset (1.3 5} + *

+ * Will return all the values with score > 1.3 and <= 5, while for instance: + *

+ * {@code ZRANGEBYSCORE zset (5 (10} + *

+ * Will return all the values with score > 5 and < 10 (5 and 10 excluded). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of + * elements returned by the command, so if M is constant (for instance you always ask for the + * first ten elements with LIMIT) you can consider it O(log(N)) + * @see #zrangeByScore(String, double, double) + * @see #zrangeByScore(String, double, double, int, int) + * @see #zrangeByScoreWithScores(String, double, double) + * @see #zrangeByScoreWithScores(String, double, double, int, int) + * @see #zcount(String, double, double) + * @param key + * @param min + * @param max + * @param offset + * @param count + * @return Multi bulk reply specifically a list of elements in the specified score range. + */ + @Override + public List zrangeByScoreWithScores(final String key, final double min, final double max, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public List zrangeByScoreWithScores(final String key, final String min, final String max, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(final String key, final double max, final double min) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public List zrevrangeByScore(final String key, final String max, final String min) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public List zrevrangeByScore(final String key, final double max, final double min, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(final String key, final double max, final double min) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public List zrevrangeByScoreWithScores(final String key, final double max, + final double min, final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(final String key, final String max, + final String min, final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public List zrevrangeByScore(final String key, final String max, final String min, + final int offset, final int count) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(final String key, final String max, final String min) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + /** + * Remove all elements in the sorted set at key with rank between start and end. Start and end are + * 0-based with rank 0 being the element with the lowest score. Both start and end can be negative + * numbers, where they indicate offsets starting at the element with the highest rank. For + * example: -1 is the element with the highest score, -2 the element with the second highest score + * and so forth. + *

+ * Time complexity: O(log(N))+O(M) with N being the number of elements in the sorted set + * and M the number of elements removed by the operation + * @param key + * @param start + * @param stop + * @return + */ + @Override + public long zremrangeByRank(final String key, final long start, final long stop) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + /** + * Remove all the elements in the sorted set at key with a score between min and max (including + * elements with score equal to min or max). + *

+ * Time complexity: + *

+ * O(log(N))+O(M) with N being the number of elements in the sorted set and M the number of + * elements removed by the operation + * @param key + * @param min + * @param max + * @return Integer reply, specifically the number of elements removed. + */ + @Override + public long zremrangeByScore(final String key, final double min, final double max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public long zremrangeByScore(final String key, final String min, final String max) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + /** + * Add multiple sorted sets, This command is similar to ZUNIONSTORE, but instead of storing the + resulting sorted set, it is returned to the connection. + * @param params + * @param keys + * @return + */ + @Override + public Set zunion(ZParams params, String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zunion(params, keys)); + } + + /** + * Add multiple sorted sets with scores, This command is similar to ZUNIONSTORE, but instead of storing the + resulting sorted set, it is returned to the connection. + * @param params + * @param keys + * @return + */ + @Override + public Set zunionWithScores(ZParams params, String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zunionWithScores(params, keys)); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at + * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys + * and the other (optional) arguments. + *

+ * As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an + * element to be present in each of the given inputs to be inserted in the result. The + * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all + * inputs. + *

+ * Using the WEIGHTS option, it is possible to add weight to each input sorted set. This means + * that the score of each element in the sorted set is first multiplied by this weight before + * being passed to the aggregation. When this option is not given, all weights default to 1. + *

+ * With the AGGREGATE option, it's possible to specify how the results of the union or + * intersection are aggregated. This option defaults to SUM, where the score of an element is + * summed across the inputs where it exists. When this option is set to be either MIN or MAX, the + * resulting set will contain the minimum or maximum score of an element across the inputs where + * it exists. + *

+ * Time complexity: O(N) + O(M log(M)) with N being the sum of the sizes of the input + * sorted sets, and M being the number of elements in the resulting sorted set + * @see #zunionstore(String, String...) + * @see #zunionstore(String, ZParams, String...) + * @see #zinterstore(String, String...) + * @see #zinterstore(String, ZParams, String...) + * @param dstkey + * @param sets + * @return Integer reply, specifically the number of elements in the sorted set at dstkey + */ + @Override + public long zunionstore(final String dstkey, final String... sets) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.zunionstore(dstkey, sets)); + } + + /** + * Creates a union or intersection of N sorted sets given by keys k1 through kN, and stores it at + * dstkey. It is mandatory to provide the number of input keys N, before passing the input keys + * and the other (optional) arguments. + *

+ * As the terms imply, the {@link #zinterstore(String, String...) ZINTERSTORE} command requires an * element to be present in each of the given inputs to be inserted in the result. The * {@link #zunionstore(String, String...) ZUNIONSTORE} command inserts all elements across all * inputs. @@ -2859,13 +6965,12 @@ public long zunionstore(final String dstkey, final String... sets) { @Override public long zunionstore(final String dstkey, final ZParams params, final String... sets) { checkIsInMultiOrPipeline(); - client.zunionstore(dstkey, params, sets); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zunionstore(dstkey, params, sets)); } /** * Intersect multiple sorted sets, This command is similar to ZINTERSTORE, but instead of storing - * the resulting sorted set, it is returned to the client. + the resulting sorted set, it is returned to the connection. * @param params * @param keys * @return @@ -2873,13 +6978,12 @@ public long zunionstore(final String dstkey, final ZParams params, final String. @Override public Set zinter(final ZParams params, final String... keys) { checkIsInMultiOrPipeline(); - client.zinter(params, keys); - return BuilderFactory.STRING_ZSET.build(client.getBinaryMultiBulkReply()); + return connection.executeCommand(commandObjects.zinter(params, keys)); } /** * Intersect multiple sorted sets, This command is similar to ZINTERSTORE, but instead of storing - * the resulting sorted set, it is returned to the client. + the resulting sorted set, it is returned to the connection. * @param params * @param keys * @return @@ -2887,8 +6991,7 @@ public Set zinter(final ZParams params, final String... keys) { @Override public Set zinterWithScores(final ZParams params, final String... keys) { checkIsInMultiOrPipeline(); - client.zinterWithScores(params, keys); - return getTupledSet(); + return connection.executeCommand(commandObjects.zinterWithScores(params, keys)); } /** @@ -2924,8 +7027,7 @@ public Set zinterWithScores(final ZParams params, final String... keys) { @Override public long zinterstore(final String dstkey, final String... sets) { checkIsInMultiOrPipeline(); - client.zinterstore(dstkey, sets); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zinterstore(dstkey, sets)); } /** @@ -2962,63 +7064,51 @@ public long zinterstore(final String dstkey, final String... sets) { @Override public long zinterstore(final String dstkey, final ZParams params, final String... sets) { checkIsInMultiOrPipeline(); - client.zinterstore(dstkey, params, sets); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zinterstore(dstkey, params, sets)); } @Override public long zlexcount(final String key, final String min, final String max) { checkIsInMultiOrPipeline(); - client.zlexcount(key, min, max); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zlexcount(key, min, max)); } @Override - public Set zrangeByLex(final String key, final String min, final String max) { + public List zrangeByLex(final String key, final String min, final String max) { checkIsInMultiOrPipeline(); - client.zrangeByLex(key, min, max); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrangeByLex(key, min, max)); } @Override - public Set zrangeByLex(final String key, final String min, final String max, + public List zrangeByLex(final String key, final String min, final String max, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrangeByLex(key, min, max, offset, count); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); } @Override - public Set zrevrangeByLex(final String key, final String max, final String min) { + public List zrevrangeByLex(final String key, final String max, final String min) { checkIsInMultiOrPipeline(); - client.zrevrangeByLex(key, max, min); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrangeByLex(key, max, min)); } @Override - public Set zrevrangeByLex(final String key, final String max, final String min, + public List zrevrangeByLex(final String key, final String max, final String min, final int offset, final int count) { checkIsInMultiOrPipeline(); - client.zrevrangeByLex(key, max, min, offset, count); - final List members = client.getMultiBulkReply(); - return SetFromList.of(members); + return connection.executeCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); } @Override public long zremrangeByLex(final String key, final String min, final String max) { checkIsInMultiOrPipeline(); - client.zremrangeByLex(key, min, max); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.zremrangeByLex(key, min, max)); } @Override public long strlen(final String key) { checkIsInMultiOrPipeline(); - client.strlen(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.strlen(key)); } /** @@ -3031,8 +7121,7 @@ public long strlen(final String key) { @Override public LCSMatchResult strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params) { checkIsInMultiOrPipeline(); - client.strAlgoLCSKeys(keyA, keyB, params); - return BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER.build(client.getOne()); + return connection.executeCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); } /** @@ -3042,18 +7131,15 @@ public LCSMatchResult strAlgoLCSKeys(final String keyA, final String keyB, final * @param params the params * @return According to StrAlgoLCSParams to decide to return content to fill LCSMatchResult. */ - @Override public LCSMatchResult strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params) { checkIsInMultiOrPipeline(); - client.strAlgoLCSStrings(strA, strB, params); - return BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER.build(client.getOne()); + return connection.executeCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); } @Override public long lpushx(final String key, final String... string) { checkIsInMultiOrPipeline(); - client.lpushx(key, string); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.lpushx(key, string)); } /** @@ -3067,30 +7153,27 @@ public long lpushx(final String key, final String... string) { @Override public long persist(final String key) { checkIsInMultiOrPipeline(); - client.persist(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.persist(key)); } @Override public long rpushx(final String key, final String... string) { checkIsInMultiOrPipeline(); - client.rpushx(key, string); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.rpushx(key, string)); } @Override public String echo(final String string) { checkIsInMultiOrPipeline(); - client.echo(string); - return client.getBulkReply(); + connection.sendCommand(ECHO, string); + return connection.getBulkReply(); } @Override public long linsert(final String key, final ListPosition where, final String pivot, final String value) { checkIsInMultiOrPipeline(); - client.linsert(key, where, pivot, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.linsert(key, where, pivot, value)); } /** @@ -3103,13 +7186,7 @@ public long linsert(final String key, final ListPosition where, final String piv @Override public String brpoplpush(final String source, final String destination, final int timeout) { checkIsInMultiOrPipeline(); - client.brpoplpush(source, destination, timeout); - client.setTimeoutInfinite(); - try { - return client.getBulkReply(); - } finally { - client.rollbackTimeout(); - } + return connection.executeCommand(commandObjects.brpoplpush(source, destination, timeout)); } /** @@ -3122,16 +7199,7 @@ public String brpoplpush(final String source, final String destination, final in @Override public boolean setbit(final String key, final long offset, final boolean value) { checkIsInMultiOrPipeline(); - client.setbit(key, offset, value); - return client.getIntegerReply() == 1; - } - - @Override - @Deprecated - public Boolean setbit(final String key, final long offset, final String value) { - checkIsInMultiOrPipeline(); - client.setbit(key, offset, value); - return client.getIntegerReply() == 1; + return connection.executeCommand(commandObjects.setbit(key, offset, value)); } /** @@ -3143,41 +7211,38 @@ public Boolean setbit(final String key, final long offset, final String value) { @Override public boolean getbit(final String key, final long offset) { checkIsInMultiOrPipeline(); - client.getbit(key, offset); - return client.getIntegerReply() == 1; + return connection.executeCommand(commandObjects.getbit(key, offset)); } @Override public long setrange(final String key, final long offset, final String value) { checkIsInMultiOrPipeline(); - client.setrange(key, offset, value); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.setrange(key, offset, value)); } @Override public String getrange(final String key, final long startOffset, final long endOffset) { checkIsInMultiOrPipeline(); - client.getrange(key, startOffset, endOffset); - return client.getBulkReply(); + return connection.executeCommand(commandObjects.getrange(key, startOffset, endOffset)); } @Override public long bitpos(final String key, final boolean value) { - return bitpos(key, value, new BitPosParams()); + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.bitpos(key, value)); } @Override public long bitpos(final String key, final boolean value, final BitPosParams params) { checkIsInMultiOrPipeline(); - client.bitpos(key, value, params); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.bitpos(key, value, params)); } @Override public List role() { checkIsInMultiOrPipeline(); - client.role(); - return BuilderFactory.ENCODED_OBJECT_LIST.build(client.getOne()); + connection.sendCommand(ROLE); + return BuilderFactory.ENCODED_OBJECT_LIST.build(connection.getOne()); } /** @@ -3217,8 +7282,8 @@ public List role() { @Override public List configGet(final String pattern) { checkIsInMultiOrPipeline(); - client.configGet(pattern); - return client.getMultiBulkReply(); + connection.sendCommand(CONFIG, Keyword.GET.name(), pattern); + return connection.getMultiBulkReply(); } /** @@ -3253,85 +7318,93 @@ public List configGet(final String pattern) { @Override public String configSet(final String parameter, final String value) { checkIsInMultiOrPipeline(); - client.configSet(parameter, value); - return client.getStatusCodeReply(); + connection.sendCommand(CONFIG, Keyword.SET.name(), parameter, value); + return connection.getStatusCodeReply(); + } + + public long publish(final String channel, final String message) { + checkIsInMultiOrPipeline(); + connection.sendCommand(PUBLISH, channel, message); + return connection.getIntegerReply(); } - @Override public void subscribe(final JedisPubSub jedisPubSub, final String... channels) { - client.setTimeoutInfinite(); + connection.setTimeoutInfinite(); try { - jedisPubSub.proceed(client, channels); + jedisPubSub.proceed(connection, channels); } finally { - client.rollbackTimeout(); + connection.rollbackTimeout(); } } - @Override - public Long publish(final String channel, final String message) { - checkIsInMultiOrPipeline(); - client.publish(channel, message); - return client.getIntegerReply(); - } - - @Override public void psubscribe(final JedisPubSub jedisPubSub, final String... patterns) { checkIsInMultiOrPipeline(); - client.setTimeoutInfinite(); + connection.setTimeoutInfinite(); try { - jedisPubSub.proceedWithPatterns(client, patterns); + jedisPubSub.proceedWithPatterns(connection, patterns); } finally { - client.rollbackTimeout(); + connection.rollbackTimeout(); } } - protected static String[] getParams(List keys, List args) { - int keyCount = keys.size(); - int argCount = args.size(); - - String[] params = new String[keyCount + args.size()]; + public List pubsubChannels() { + checkIsInMultiOrPipeline(); + connection.sendCommand(PUBSUB, CHANNELS); + return connection.getMultiBulkReply(); + } - for (int i = 0; i < keyCount; i++) - params[i] = keys.get(i); + public List pubsubChannels(final String pattern) { + checkIsInMultiOrPipeline(); + connection.sendCommand(PUBSUB, CHANNELS.name(), pattern); + return connection.getMultiBulkReply(); + } - for (int i = 0; i < argCount; i++) - params[keyCount + i] = args.get(i); + public Long pubsubNumPat() { + checkIsInMultiOrPipeline(); + connection.sendCommand(PUBSUB, NUMPAT); + return connection.getIntegerReply(); + } - return params; + public Map pubsubNumSub(String... channels) { + checkIsInMultiOrPipeline(); + connection.sendCommand(PUBSUB, joinParameters(NUMSUB.name(), channels)); + return BuilderFactory.PUBSUB_NUMSUB_MAP.build(connection.getOne()); } @Override public Object eval(final String script, final int keyCount, final String... params) { checkIsInMultiOrPipeline(); - client.eval(script, keyCount, params); - return SafeEncoder.encodeObject(client.getOne()); + return connection.executeCommand(commandObjects.eval(script, keyCount, params)); } @Override public Object eval(final String script, final List keys, final List args) { - return eval(script, keys.size(), getParams(keys, args)); + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.eval(script, keys, args)); } @Override public Object eval(final String script) { - return eval(script, 0); + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.eval(script)); } @Override public Object evalsha(final String sha1) { - return evalsha(sha1, 0); + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.evalsha(sha1)); } @Override public Object evalsha(final String sha1, final List keys, final List args) { - return evalsha(sha1, keys.size(), getParams(keys, args)); + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.evalsha(sha1, keys, args)); } @Override public Object evalsha(final String sha1, final int keyCount, final String... params) { checkIsInMultiOrPipeline(); - client.evalsha(sha1, keyCount, params); - return SafeEncoder.encodeObject(client.getOne()); + return connection.executeCommand(commandObjects.evalsha(sha1, keyCount, params)); } @Override @@ -3343,1052 +7416,771 @@ public Boolean scriptExists(final String sha1) { @Override public List scriptExists(final String... sha1) { - client.scriptExists(sha1); - List result = client.getIntegerMultiBulkReply(); - List exists = new ArrayList<>(); - - for (Long value : result) - exists.add(value == 1); - - return exists; + connection.sendCommand(SCRIPT, joinParameters(Keyword.EXISTS.name(), sha1)); + return BuilderFactory.BOOLEAN_LIST.build(connection.getOne()); } @Override public String scriptLoad(final String script) { - client.scriptLoad(script); - return client.getBulkReply(); + connection.sendCommand(SCRIPT, LOAD.name(), script); + return connection.getBulkReply(); } @Override public List slowlogGet() { - client.slowlogGet(); - return Slowlog.from(client.getObjectMultiBulkReply()); + connection.sendCommand(SLOWLOG, Keyword.GET); + return Slowlog.from(connection.getObjectMultiBulkReply()); } @Override public List slowlogGet(final long entries) { - client.slowlogGet(entries); - return Slowlog.from(client.getObjectMultiBulkReply()); + connection.sendCommand(SLOWLOG, Keyword.GET.getRaw(), toByteArray(entries)); + return Slowlog.from(connection.getObjectMultiBulkReply()); } @Override public Long objectRefcount(final String key) { - client.objectRefcount(key); - return client.getIntegerReply(); + connection.sendCommand(OBJECT, REFCOUNT.name(), key); + return connection.getIntegerReply(); } @Override public String objectEncoding(final String key) { - client.objectEncoding(key); - return client.getBulkReply(); + connection.sendCommand(OBJECT, ENCODING.name(), key); + return connection.getBulkReply(); } @Override public Long objectIdletime(final String key) { - client.objectIdletime(key); - return client.getIntegerReply(); + connection.sendCommand(OBJECT, IDLETIME.name(), key); + return connection.getIntegerReply(); } @Override public List objectHelp() { - client.objectHelp(); - return client.getMultiBulkReply(); + connection.sendCommand(OBJECT, HELP); + return connection.getMultiBulkReply(); } @Override public Long objectFreq(final String key) { - client.objectFreq(key); - return client.getIntegerReply(); + connection.sendCommand(OBJECT, FREQ.name(), key); + return connection.getIntegerReply(); } @Override public long bitcount(final String key) { checkIsInMultiOrPipeline(); - client.bitcount(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.bitcount(key)); } @Override public long bitcount(final String key, final long start, final long end) { checkIsInMultiOrPipeline(); - client.bitcount(key, start, end); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.bitcount(key, start, end)); } @Override public long bitop(final BitOP op, final String destKey, final String... srcKeys) { checkIsInMultiOrPipeline(); - client.bitop(op, destKey, srcKeys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.bitop(op, destKey, srcKeys)); } @Override - public String sentinelMyId() { - client.sentinel(SentinelKeyword.MYID); - return BuilderFactory.STRING.build(client.getBinaryBulkReply()); + public byte[] dump(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.dump(key)); } - /** - *
-   * redis 127.0.0.1:26381> sentinel masters
-   * 1)  1) "name"
-   *     2) "mymaster"
-   *     3) "ip"
-   *     4) "127.0.0.1"
-   *     5) "port"
-   *     6) "6379"
-   *     7) "runid"
-   *     8) "93d4d4e6e9c06d0eea36e27f31924ac26576081d"
-   *     9) "flags"
-   *    10) "master"
-   *    11) "pending-commands"
-   *    12) "0"
-   *    13) "last-ok-ping-reply"
-   *    14) "423"
-   *    15) "last-ping-reply"
-   *    16) "423"
-   *    17) "info-refresh"
-   *    18) "6107"
-   *    19) "num-slaves"
-   *    20) "1"
-   *    21) "num-other-sentinels"
-   *    22) "2"
-   *    23) "quorum"
-   *    24) "2"
-   *
-   * 
- * @return - */ @Override - @SuppressWarnings("rawtypes") - public List> sentinelMasters() { - client.sentinel(Protocol.SENTINEL_MASTERS); - final List reply = client.getObjectMultiBulkReply(); - - final List> masters = new ArrayList<>(); - for (Object obj : reply) { - masters.add(BuilderFactory.STRING_MAP.build(obj)); - } - return masters; + public String restore(final String key, final long ttl, final byte[] serializedValue) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.restore(key, ttl, serializedValue)); } @Override - public Map sentinelMaster(String masterName) { - client.sentinel(SentinelKeyword.MASTER, masterName); - return BuilderFactory.STRING_MAP.build(client.getBinaryMultiBulkReply()); + public String restore(final String key, final long ttl, final byte[] serializedValue, + final RestoreParams params) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.restore(key, ttl, serializedValue, params)); } @Override - public List> sentinelSentinels(String masterName) { - client.sentinel(SentinelKeyword.SENTINELS, masterName); - return client.getObjectMultiBulkReply().stream() - .map(BuilderFactory.STRING_MAP::build).collect(Collectors.toList()); + public long pexpire(final String key, final long milliseconds) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pexpire(key, milliseconds)); } - /** - *
-   * redis 127.0.0.1:26381> sentinel get-master-addr-by-name mymaster
-   * 1) "127.0.0.1"
-   * 2) "6379"
-   * 
- * @param masterName - * @return two elements list of strings : host and port. - */ @Override - public List sentinelGetMasterAddrByName(final String masterName) { - client.sentinel(Protocol.SENTINEL_GET_MASTER_ADDR_BY_NAME, masterName); - final List reply = client.getObjectMultiBulkReply(); - return BuilderFactory.STRING_LIST.build(reply); + public long pexpireAt(final String key, final long millisecondsTimestamp) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); } - /** - *
-   * redis 127.0.0.1:26381> sentinel reset mymaster
-   * (integer) 1
-   * 
- * @param pattern - * @return - */ @Override - public Long sentinelReset(final String pattern) { - client.sentinel(Protocol.SENTINEL_RESET, pattern); - return client.getIntegerReply(); + public long pttl(final String key) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.pttl(key)); } /** - * @deprecated Use {@link Jedis#sentinelReplicas(java.lang.String)}. + * PSETEX works exactly like {@link #setex(String, int, String)} with the sole difference that the + * expire time is specified in milliseconds instead of seconds. Time complexity: O(1) + * @param key + * @param milliseconds + * @param value + * @return Status code reply */ + @Override - @Deprecated - public List> sentinelSlaves(final String masterName) { - client.sentinel(Protocol.SENTINEL_SLAVES, masterName); - final List reply = client.getObjectMultiBulkReply(); + public String psetex(final String key, final long milliseconds, final String value) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.psetex(key, milliseconds, value)); + } - final List> slaves = new ArrayList<>(); - for (Object obj : reply) { - slaves.add(BuilderFactory.STRING_MAP.build(obj)); - } - return slaves; + @Override + public String aclSetUser(final String name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, SETUSER.name(), name); + return connection.getStatusCodeReply(); } - /** - *
-   * redis 127.0.0.1:26381> sentinel replicas mymaster
-   * 1)  1) "name"
-   *     2) "127.0.0.1:6380"
-   *     3) "ip"
-   *     4) "127.0.0.1"
-   *     5) "port"
-   *     6) "6380"
-   *     7) "runid"
-   *     8) "d7f6c0ca7572df9d2f33713df0dbf8c72da7c039"
-   *     9) "flags"
-   *    10) "slave"
-   *    11) "pending-commands"
-   *    12) "0"
-   *    13) "last-ok-ping-reply"
-   *    14) "47"
-   *    15) "last-ping-reply"
-   *    16) "47"
-   *    17) "info-refresh"
-   *    18) "657"
-   *    19) "master-link-down-time"
-   *    20) "0"
-   *    21) "master-link-status"
-   *    22) "ok"
-   *    23) "master-host"
-   *    24) "localhost"
-   *    25) "master-port"
-   *    26) "6379"
-   *    27) "slave-priority"
-   *    28) "100"
-   * 
- * @param masterName - * @return - */ @Override - public List> sentinelReplicas(final String masterName) { - client.sentinel(SentinelKeyword.REPLICAS, masterName); - return client.getObjectMultiBulkReply().stream() - .map(BuilderFactory.STRING_MAP::build).collect(Collectors.toList()); + public String aclSetUser(String name, String... params) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, joinParameters(SETUSER.name(), name, params)); + return connection.getStatusCodeReply(); } @Override - public String sentinelFailover(final String masterName) { - client.sentinel(Protocol.SENTINEL_FAILOVER, masterName); - return client.getStatusCodeReply(); + public long aclDelUser(final String name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, DELUSER.name(), name); + return connection.getIntegerReply(); } @Override - public String sentinelMonitor(final String masterName, final String ip, final int port, - final int quorum) { - client.sentinel(Protocol.SENTINEL_MONITOR, masterName, ip, String.valueOf(port), - String.valueOf(quorum)); - return client.getStatusCodeReply(); + public long aclDelUser(final String name, String... names) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, joinParameters(DELUSER.name(), name, names)); + return connection.getIntegerReply(); } @Override - public String sentinelRemove(final String masterName) { - client.sentinel(Protocol.SENTINEL_REMOVE, masterName); - return client.getStatusCodeReply(); + public AccessControlUser aclGetUser(final String name) { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, GETUSER.name(), name); + return BuilderFactory.ACCESS_CONTROL_USER.build(connection.getObjectMultiBulkReply()); } @Override - public String sentinelSet(final String masterName, final Map parameterMap) { - int index = 0; - int paramsLength = parameterMap.size() * 2 + 2; - String[] params = new String[paramsLength]; - - params[index++] = Protocol.SENTINEL_SET; - params[index++] = masterName; - for (Entry entry : parameterMap.entrySet()) { - params[index++] = entry.getKey(); - params[index++] = entry.getValue(); - } + public List aclUsers() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, USERS); + return BuilderFactory.STRING_LIST.build(connection.getObjectMultiBulkReply()); + } - client.sentinel(params); - return client.getStatusCodeReply(); + @Override + public List aclList() { + checkIsInMultiOrPipeline(); + connection.sendCommand(ACL, LIST); + return connection.getMultiBulkReply(); } @Override - public byte[] dump(final String key) { + public String aclWhoAmI() { checkIsInMultiOrPipeline(); - client.dump(key); - return client.getBinaryBulkReply(); + connection.sendCommand(ACL, WHOAMI); + return connection.getStatusCodeReply(); } @Override - public String restore(final String key, final long ttl, final byte[] serializedValue) { + public List aclCat() { checkIsInMultiOrPipeline(); - client.restore(key, ttl, serializedValue); - return client.getStatusCodeReply(); + connection.sendCommand(ACL, CAT); + return BuilderFactory.STRING_LIST.build(connection.getObjectMultiBulkReply()); } @Override - public String restoreReplace(final String key, final long ttl, final byte[] serializedValue) { + public List aclCat(String category) { checkIsInMultiOrPipeline(); - client.restoreReplace(key, ttl, serializedValue); - return client.getStatusCodeReply(); + connection.sendCommand(ACL, CAT.name(), category); + return BuilderFactory.STRING_LIST.build(connection.getObjectMultiBulkReply()); } @Override - public String restore(final String key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { + public List aclLog() { checkIsInMultiOrPipeline(); - client.restore(key, ttl, serializedValue, params); - return client.getStatusCodeReply(); + connection.sendCommand(ACL, LOG); + return BuilderFactory.ACCESS_CONTROL_LOG_ENTRY_LIST.build(connection.getObjectMultiBulkReply()); } @Override - public long pexpire(final String key, final long milliseconds) { + public List aclLog(int limit) { checkIsInMultiOrPipeline(); - client.pexpire(key, milliseconds); - return client.getIntegerReply(); + connection.sendCommand(ACL, LOG.getRaw(), toByteArray(limit)); + return BuilderFactory.ACCESS_CONTROL_LOG_ENTRY_LIST.build(connection.getObjectMultiBulkReply()); } @Override - public long pexpireAt(final String key, final long millisecondsTimestamp) { + public String aclLoad() { checkIsInMultiOrPipeline(); - client.pexpireAt(key, millisecondsTimestamp); - return client.getIntegerReply(); + connection.sendCommand(ACL, LOAD); + return connection.getStatusCodeReply(); } @Override - public long pttl(final String key) { + public String aclSave() { checkIsInMultiOrPipeline(); - client.pttl(key); - return client.getIntegerReply(); + connection.sendCommand(ACL, Keyword.SAVE); + return connection.getStatusCodeReply(); } - /** - * PSETEX works exactly like {@link #setex(String, int, String)} with the sole difference that the - * expire time is specified in milliseconds instead of seconds. Time complexity: O(1) - * @param key - * @param milliseconds - * @param value - * @return Status code reply - */ + @Override + public String aclGenPass() { + connection.sendCommand(ACL, GENPASS); + return connection.getBulkReply(); + } @Override - public String psetex(final String key, final long milliseconds, final String value) { + public String aclGenPass(int bits) { checkIsInMultiOrPipeline(); - client.psetex(key, milliseconds, value); - return client.getStatusCodeReply(); + connection.sendCommand(ACL, GENPASS.getRaw(), toByteArray(bits)); + return connection.getBulkReply(); } + @Override public String clientKill(final String ipPort) { checkIsInMultiOrPipeline(); - this.client.clientKill(ipPort); - return this.client.getStatusCodeReply(); + connection.sendCommand(CLIENT, KILL.name(), ipPort); + return connection.getStatusCodeReply(); } @Override public String clientGetname() { checkIsInMultiOrPipeline(); - client.clientGetname(); - return client.getBulkReply(); + connection.sendCommand(CLIENT, GETNAME); + return connection.getBulkReply(); } @Override public String clientList() { checkIsInMultiOrPipeline(); - client.clientList(); - return client.getBulkReply(); + connection.sendCommand(CLIENT, LIST); + return connection.getBulkReply(); } @Override public String clientList(ClientType type) { checkIsInMultiOrPipeline(); - client.clientList(type); - return client.getBulkReply(); + connection.sendCommand(CLIENT, LIST.getRaw(), Keyword.TYPE.getRaw(), type.getRaw()); + return connection.getBulkReply(); } @Override public String clientList(final long... clientIds) { checkIsInMultiOrPipeline(); - client.clientList(clientIds); - return client.getBulkReply(); + connection.sendCommand(CLIENT, clientListParams(clientIds)); + return connection.getBulkReply(); } @Override public String clientInfo() { checkIsInMultiOrPipeline(); - client.clientInfo(); - return client.getBulkReply(); + connection.sendCommand(CLIENT, Keyword.INFO); + return connection.getBulkReply(); } @Override public String clientSetname(final String name) { checkIsInMultiOrPipeline(); - client.clientSetname(name); - return client.getStatusCodeReply(); + connection.sendCommand(CLIENT, SETNAME.name(), name); + return connection.getStatusCodeReply(); } @Override public String migrate(final String host, final int port, final String key, final int destinationDb, final int timeout) { checkIsInMultiOrPipeline(); - client.migrate(host, port, key, destinationDb, timeout); - return client.getStatusCodeReply(); + CommandArguments args = new CommandArguments(MIGRATE).add(host).add(port).key(key).add(destinationDb).add(timeout); + connection.sendCommand(args); + return connection.getStatusCodeReply(); } @Override public String migrate(final String host, final int port, final int destinationDB, final int timeout, final MigrateParams params, final String... keys) { checkIsInMultiOrPipeline(); - client.migrate(host, port, destinationDB, timeout, params, keys); - return client.getStatusCodeReply(); + CommandArguments args = new CommandArguments(MIGRATE).add(host).add(port).add(new byte[0]).add(destinationDB) + .add(timeout).addParams(params).add(Keyword.KEYS).keys((Object[]) keys); + connection.sendCommand(args); + return connection.getStatusCodeReply(); + } + + @Override + public String migrate(String host, int port, String key, int timeout) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public String migrate(String host, int port, int timeout, MigrateParams params, String... keys) { + checkIsInMultiOrPipeline(); + return connection.executeCommand(commandObjects.migrate(host, port, timeout, params, keys)); } @Override public ScanResult scan(final String cursor) { - return scan(cursor, new ScanParams()); + return connection.executeCommand(commandObjects.scan(cursor)); } @Override public ScanResult scan(final String cursor, final ScanParams params) { - return scan(cursor, params, null); + return connection.executeCommand(commandObjects.scan(cursor, params)); } @Override public ScanResult scan(final String cursor, final ScanParams params, final String type) { checkIsInMultiOrPipeline(); - client.scan(cursor, params, type); - List result = client.getObjectMultiBulkReply(); - String newcursor = new String((byte[]) result.get(0)); - List results = new ArrayList<>(); - List rawResults = (List) result.get(1); - for (byte[] bs : rawResults) { - results.add(SafeEncoder.encode(bs)); - } - return new ScanResult<>(newcursor, results); + return connection.executeCommand(commandObjects.scan(cursor, params, type)); } @Override public ScanResult> hscan(final String key, final String cursor, final ScanParams params) { checkIsInMultiOrPipeline(); - client.hscan(key, cursor, params); - List result = client.getObjectMultiBulkReply(); - String newcursor = new String((byte[]) result.get(0)); - List> results = new ArrayList<>(); - List rawResults = (List) result.get(1); - Iterator iterator = rawResults.iterator(); - while (iterator.hasNext()) { - results.add(new AbstractMap.SimpleEntry<>(SafeEncoder.encode(iterator.next()), - SafeEncoder.encode(iterator.next()))); - } - return new ScanResult<>(newcursor, results); + return connection.executeCommand(commandObjects.hscan(key, cursor, params)); } @Override public ScanResult sscan(final String key, final String cursor, final ScanParams params) { checkIsInMultiOrPipeline(); - client.sscan(key, cursor, params); - List result = client.getObjectMultiBulkReply(); - String newcursor = new String((byte[]) result.get(0)); - List results = new ArrayList<>(); - List rawResults = (List) result.get(1); - for (byte[] bs : rawResults) { - results.add(SafeEncoder.encode(bs)); - } - return new ScanResult<>(newcursor, results); + return connection.executeCommand(commandObjects.sscan(key, cursor, params)); } @Override public ScanResult zscan(final String key, final String cursor, final ScanParams params) { checkIsInMultiOrPipeline(); - client.zscan(key, cursor, params); - List result = client.getObjectMultiBulkReply(); - String newcursor = new String((byte[]) result.get(0)); - List results = new ArrayList<>(); - List rawResults = (List) result.get(1); - Iterator iterator = rawResults.iterator(); - while (iterator.hasNext()) { - results.add(new Tuple(iterator.next(), BuilderFactory.DOUBLE.build(iterator.next()))); - } - return new ScanResult<>(newcursor, results); + return connection.executeCommand(commandObjects.zscan(key, cursor, params)); } @Override public String readonly() { checkIsInMultiOrPipeline(); - client.readonly(); - return client.getStatusCodeReply(); + connection.sendCommand(READONLY); + return connection.getStatusCodeReply(); } @Override public String readwrite() { checkIsInMultiOrPipeline(); - client.readwrite(); - return client.getStatusCodeReply(); + connection.sendCommand(READWRITE); + return connection.getStatusCodeReply(); } @Override public String clusterNodes() { checkIsInMultiOrPipeline(); - client.clusterNodes(); - return client.getBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.NODES); + return connection.getBulkReply(); } @Override public String clusterReplicas(final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterReplicas(nodeId); - return client.getBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.REPLICAS.name(), nodeId); + return connection.getBulkReply(); } @Override public String clusterMeet(final String ip, final int port) { checkIsInMultiOrPipeline(); - client.clusterMeet(ip, port); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.MEET.name(), ip, Integer.toString(port)); + return connection.getStatusCodeReply(); } @Override - public String clusterReset(final ClusterReset resetType) { + public String clusterReset() { checkIsInMultiOrPipeline(); - client.clusterReset(resetType); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.RESET); + return connection.getStatusCodeReply(); } @Override public String clusterReset(final ClusterResetType resetType) { checkIsInMultiOrPipeline(); - client.clusterReset(resetType); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.RESET.getRaw(), resetType.getRaw()); + return connection.getStatusCodeReply(); } @Override public String clusterAddSlots(final int... slots) { checkIsInMultiOrPipeline(); - client.clusterAddSlots(slots); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, joinParameters(ClusterKeyword.ADDSLOTS.getRaw(), joinParameters(slots))); + return connection.getStatusCodeReply(); } @Override public String clusterDelSlots(final int... slots) { checkIsInMultiOrPipeline(); - client.clusterDelSlots(slots); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, joinParameters(ClusterKeyword.DELSLOTS.getRaw(), joinParameters(slots))); + return connection.getStatusCodeReply(); } @Override public String clusterInfo() { checkIsInMultiOrPipeline(); - client.clusterInfo(); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.INFO); + return connection.getStatusCodeReply(); } @Override public List clusterGetKeysInSlot(final int slot, final int count) { checkIsInMultiOrPipeline(); - client.clusterGetKeysInSlot(slot, count); - return client.getMultiBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.GETKEYSINSLOT.getRaw(), toByteArray(slot), toByteArray(count)); + return connection.getMultiBulkReply(); } @Override public List clusterGetKeysInSlotBinary(final int slot, final int count) { checkIsInMultiOrPipeline(); - client.clusterGetKeysInSlot(slot, count); - return client.getBinaryMultiBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.GETKEYSINSLOT.getRaw(), toByteArray(slot), toByteArray(count)); + return connection.getBinaryMultiBulkReply(); } @Override public String clusterSetSlotNode(final int slot, final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterSetSlotNode(slot, nodeId); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SETSLOT.getRaw(), toByteArray(slot), ClusterKeyword.NODE.getRaw(), encode(nodeId)); + return connection.getStatusCodeReply(); } @Override public String clusterSetSlotMigrating(final int slot, final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterSetSlotMigrating(slot, nodeId); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SETSLOT.getRaw(), toByteArray(slot), ClusterKeyword.MIGRATING.getRaw(), encode(nodeId)); + return connection.getStatusCodeReply(); } @Override public String clusterSetSlotImporting(final int slot, final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterSetSlotImporting(slot, nodeId); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SETSLOT.getRaw(), toByteArray(slot), ClusterKeyword.IMPORTING.getRaw(), encode(nodeId)); + return connection.getStatusCodeReply(); } @Override public String clusterSetSlotStable(final int slot) { checkIsInMultiOrPipeline(); - client.clusterSetSlotStable(slot); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SETSLOT.getRaw(), toByteArray(slot), ClusterKeyword.STABLE.getRaw()); + return connection.getStatusCodeReply(); } @Override public String clusterForget(final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterForget(nodeId); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.FORGET.name(), nodeId); + return connection.getStatusCodeReply(); } @Override public String clusterFlushSlots() { checkIsInMultiOrPipeline(); - client.clusterFlushSlots(); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.FLUSHSLOTS); + return connection.getStatusCodeReply(); } @Override public long clusterKeySlot(final String key) { checkIsInMultiOrPipeline(); - client.clusterKeySlot(key); - return client.getIntegerReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.KEYSLOT.name(), key); + return connection.getIntegerReply(); } @Override public long clusterCountKeysInSlot(final int slot) { checkIsInMultiOrPipeline(); - client.clusterCountKeysInSlot(slot); - return client.getIntegerReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.COUNTKEYSINSLOT.getRaw(), toByteArray(slot)); + return connection.getIntegerReply(); } @Override public String clusterSaveConfig() { checkIsInMultiOrPipeline(); - client.clusterSaveConfig(); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SAVECONFIG); + return connection.getStatusCodeReply(); } @Override public String clusterReplicate(final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterReplicate(nodeId); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.REPLICATE.name(), nodeId); + return connection.getStatusCodeReply(); } @Override public List clusterSlaves(final String nodeId) { checkIsInMultiOrPipeline(); - client.clusterSlaves(nodeId); - return client.getMultiBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SLAVES.name(), nodeId); + return connection.getMultiBulkReply(); + } + + @Override + public String clusterFailover() { + checkIsInMultiOrPipeline(); + connection.sendCommand(CLUSTER, ClusterKeyword.FAILOVER); + return connection.getStatusCodeReply(); } @Override public String clusterFailover(ClusterFailoverOption failoverOption) { checkIsInMultiOrPipeline(); - client.clusterFailover(failoverOption); - return client.getStatusCodeReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.FAILOVER.getRaw(), failoverOption.getRaw()); + return connection.getStatusCodeReply(); } @Override public List clusterSlots() { checkIsInMultiOrPipeline(); - client.clusterSlots(); - return client.getObjectMultiBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.SLOTS); + return connection.getObjectMultiBulkReply(); } @Override public String clusterMyId() { checkIsInMultiOrPipeline(); - client.clusterMyId(); - return client.getBulkReply(); + connection.sendCommand(CLUSTER, ClusterKeyword.MYID); + return connection.getBulkReply(); } + @Override public String asking() { checkIsInMultiOrPipeline(); - client.asking(); - return client.getStatusCodeReply(); - } - - public List pubsubChannels() { - checkIsInMultiOrPipeline(); - client.pubsubChannels(); - return client.getMultiBulkReply(); - } - - public List pubsubChannels(final String pattern) { - checkIsInMultiOrPipeline(); - client.pubsubChannels(pattern); - return client.getMultiBulkReply(); - } - - public Long pubsubNumPat() { - checkIsInMultiOrPipeline(); - client.pubsubNumPat(); - return client.getIntegerReply(); - } - - public Map pubsubNumSub(String... channels) { - checkIsInMultiOrPipeline(); - client.pubsubNumSub(channels); - return BuilderFactory.PUBSUB_NUMSUB_MAP.build(client.getBinaryMultiBulkReply()); - } - - @Override - public void close() { - if (dataSource != null) { - Pool pool = this.dataSource; - this.dataSource = null; - if (isBroken()) { - pool.returnBrokenResource(this); - } else { - pool.returnResource(this); - } - } else { - super.close(); - } - } - - protected void setDataSource(Pool jedisPool) { - this.dataSource = jedisPool; + connection.sendCommand(ASKING); + return connection.getStatusCodeReply(); } @Override public long pfadd(final String key, final String... elements) { checkIsInMultiOrPipeline(); - client.pfadd(key, elements); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.pfadd(key, elements)); } @Override public long pfcount(final String key) { checkIsInMultiOrPipeline(); - client.pfcount(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.pfcount(key)); } @Override public long pfcount(final String... keys) { checkIsInMultiOrPipeline(); - client.pfcount(keys); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.pfcount(keys)); } @Override public String pfmerge(final String destkey, final String... sourcekeys) { checkIsInMultiOrPipeline(); - client.pfmerge(destkey, sourcekeys); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.pfmerge(destkey, sourcekeys)); } @Override public long geoadd(final String key, final double longitude, final double latitude, final String member) { checkIsInMultiOrPipeline(); - client.geoadd(key, longitude, latitude, member); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.geoadd(key, longitude, latitude, member)); } @Override public long geoadd(final String key, final Map memberCoordinateMap) { checkIsInMultiOrPipeline(); - client.geoadd(key, memberCoordinateMap); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.geoadd(key, memberCoordinateMap)); } @Override public long geoadd(final String key, final GeoAddParams params, final Map memberCoordinateMap) { checkIsInMultiOrPipeline(); - client.geoadd(key, params, memberCoordinateMap); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); } @Override public Double geodist(final String key, final String member1, final String member2) { checkIsInMultiOrPipeline(); - client.geodist(key, member1, member2); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.geodist(key, member1, member2)); } @Override public Double geodist(final String key, final String member1, final String member2, final GeoUnit unit) { checkIsInMultiOrPipeline(); - client.geodist(key, member1, member2, unit); - return BuilderFactory.DOUBLE.build(client.getOne()); + return connection.executeCommand(commandObjects.geodist(key, member1, member2, unit)); } @Override public List geohash(final String key, String... members) { checkIsInMultiOrPipeline(); - client.geohash(key, members); - return client.getMultiBulkReply(); + return connection.executeCommand(commandObjects.geohash(key, members)); } @Override public List geopos(final String key, String... members) { checkIsInMultiOrPipeline(); - client.geopos(key, members); - return BuilderFactory.GEO_COORDINATE_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.geopos(key, members)); } @Override public List georadius(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit) { checkIsInMultiOrPipeline(); - client.georadius(key, longitude, latitude, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); } @Override public List georadiusReadonly(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit) { checkIsInMultiOrPipeline(); - client.georadiusReadonly(key, longitude, latitude, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); } @Override public List georadius(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { checkIsInMultiOrPipeline(); - client.georadius(key, longitude, latitude, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); } @Override public long georadiusStore(final String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { checkIsInMultiOrPipeline(); - client.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); } @Override public List georadiusReadonly(final String key, final double longitude, final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { checkIsInMultiOrPipeline(); - client.georadiusReadonly(key, longitude, latitude, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); } @Override public List georadiusByMember(final String key, final String member, final double radius, final GeoUnit unit) { checkIsInMultiOrPipeline(); - client.georadiusByMember(key, member, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadiusByMember(key, member, radius, unit)); } @Override public List georadiusByMemberReadonly(final String key, final String member, final double radius, final GeoUnit unit) { checkIsInMultiOrPipeline(); - client.georadiusByMemberReadonly(key, member, radius, unit); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); } @Override public List georadiusByMember(final String key, final String member, final double radius, final GeoUnit unit, final GeoRadiusParam param) { checkIsInMultiOrPipeline(); - client.georadiusByMember(key, member, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); } @Override public long georadiusByMemberStore(final String key, String member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { checkIsInMultiOrPipeline(); - client.georadiusByMemberStore(key, member, radius, unit, param, storeParam); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); } @Override public List georadiusByMemberReadonly(final String key, final String member, final double radius, final GeoUnit unit, final GeoRadiusParam param) { checkIsInMultiOrPipeline(); - client.georadiusByMemberReadonly(key, member, radius, unit, param); - return BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); } @Override public String moduleLoad(final String path) { checkIsInMultiOrPipeline(); - client.moduleLoad(path); - return client.getStatusCodeReply(); + connection.sendCommand(MODULE, LOAD.name(), path); + return connection.getStatusCodeReply(); } @Override public String moduleUnload(final String name) { checkIsInMultiOrPipeline(); - client.moduleUnload(name); - return client.getStatusCodeReply(); + connection.sendCommand(MODULE, UNLOAD.name(), name); + return connection.getStatusCodeReply(); } @Override public List moduleList() { checkIsInMultiOrPipeline(); - client.moduleList(); - return BuilderFactory.MODULE_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public String aclSetUser(final String name) { - client.aclSetUser(name); - return client.getStatusCodeReply(); - } - - @Override - public String aclSetUser(String name, String... params) { - client.aclSetUser(name, params); - return client.getStatusCodeReply(); - } - - @Override - public long aclDelUser(final String name) { - client.aclDelUser(name); - return client.getIntegerReply(); - } - - @Override - public AccessControlUser aclGetUser(final String name) { - client.aclGetUser(name); - return BuilderFactory.ACCESS_CONTROL_USER.build(client.getObjectMultiBulkReply()); - } - - @Override - public List aclUsers() { - client.aclUsers(); - return BuilderFactory.STRING_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public List aclList() { - client.aclList(); - return client.getMultiBulkReply(); - } - - @Override - public String aclWhoAmI() { - client.aclWhoAmI(); - return client.getStatusCodeReply(); - } - - @Override - public List aclCat() { - client.aclCat(); - return BuilderFactory.STRING_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public List aclCat(String category) { - client.aclCat(category); - return BuilderFactory.STRING_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public List aclLog() { - client.aclLog(); - return BuilderFactory.ACCESS_CONTROL_LOG_ENTRY_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public List aclLog(int limit) { - client.aclLog(limit); - return BuilderFactory.ACCESS_CONTROL_LOG_ENTRY_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public String aclLog(String options) { - client.aclLog(options); - return client.getStatusCodeReply(); - } - - @Override - public String aclGenPass() { - client.aclGenPass(); - return client.getStatusCodeReply(); - } - - @Override - public String aclLoad() { - checkIsInMultiOrPipeline(); - client.aclLoad(); - return client.getStatusCodeReply(); - } - - @Override - public String aclSave() { - checkIsInMultiOrPipeline(); - client.aclSave(); - return client.getStatusCodeReply(); + connection.sendCommand(MODULE, LIST); + return BuilderFactory.MODULE_LIST.build(connection.getObjectMultiBulkReply()); } @Override public List bitfield(final String key, final String... arguments) { checkIsInMultiOrPipeline(); - client.bitfield(key, arguments); - return client.getIntegerMultiBulkReply(); + return connection.executeCommand(commandObjects.bitfield(key, arguments)); } @Override public List bitfieldReadonly(final String key, final String... arguments) { checkIsInMultiOrPipeline(); - client.bitfieldReadonly(key, arguments); - return client.getIntegerMultiBulkReply(); + return connection.executeCommand(commandObjects.bitfieldReadonly(key, arguments)); } @Override public long hstrlen(final String key, final String field) { checkIsInMultiOrPipeline(); - client.hstrlen(key, field); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.hstrlen(key, field)); } @Override public String memoryDoctor() { checkIsInMultiOrPipeline(); - client.memoryDoctor(); - return client.getBulkReply(); + connection.sendCommand(MEMORY, DOCTOR); + return connection.getBulkReply(); } @Override public Long memoryUsage(final String key) { checkIsInMultiOrPipeline(); - client.memoryUsage(key); - return client.getIntegerReply(); + connection.sendCommand(MEMORY, USAGE.name(), key); + return connection.getIntegerReply(); } @Override public Long memoryUsage(final String key, final int samples) { checkIsInMultiOrPipeline(); - client.memoryUsage(key, samples); - return client.getIntegerReply(); + connection.sendCommand(MEMORY, USAGE.getRaw(), encode(key), SAMPLES.getRaw(), toByteArray(samples)); + return connection.getIntegerReply(); } @Override public StreamEntryID xadd(final String key, final StreamEntryID id, final Map hash) { - return xadd(key, id, hash, Long.MAX_VALUE, false); - } - - @Override - public StreamEntryID xadd(final String key, StreamEntryID id, final Map hash, - final long maxLen, final boolean approximateLength) { checkIsInMultiOrPipeline(); - client.xadd(key, id, hash, maxLen, approximateLength); - String result = client.getBulkReply(); - return new StreamEntryID(result); + return connection.executeCommand(commandObjects.xadd(key, id, hash)); } @Override - public StreamEntryID xadd(final String key, final Map hash, final XAddParams params) { + public StreamEntryID xadd_v2(final String key, final XAddParams params, final Map hash) { checkIsInMultiOrPipeline(); - client.xadd(key, hash, params); - return BuilderFactory.STREAM_ENTRY_ID.build(client.getBinaryBulkReply()); + return connection.executeCommand(commandObjects.xadd(key, params, hash)); } @Override public long xlen(final String key) { checkIsInMultiOrPipeline(); - client.xlen(key); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.xlen(key)); } @Override public List xrange(final String key, final StreamEntryID start, final StreamEntryID end) { checkIsInMultiOrPipeline(); - client.xrange(key, start, end); - return BuilderFactory.STREAM_ENTRY_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xrange(key, start, end)); } /** @@ -4398,16 +8190,14 @@ public List xrange(final String key, final StreamEntryID start, fin public List xrange(final String key, final StreamEntryID start, final StreamEntryID end, final int count) { checkIsInMultiOrPipeline(); - client.xrange(key, start, end, count); - return BuilderFactory.STREAM_ENTRY_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xrange(key, start, end, count)); } @Override public List xrevrange(final String key, final StreamEntryID end, final StreamEntryID start) { checkIsInMultiOrPipeline(); - client.xrevrange(key, end, start); - return BuilderFactory.STREAM_ENTRY_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xrevrange(key, end, start)); } /** @@ -4417,119 +8207,62 @@ public List xrevrange(final String key, final StreamEntryID end, public List xrevrange(final String key, final StreamEntryID end, final StreamEntryID start, final int count) { checkIsInMultiOrPipeline(); - client.xrevrange(key, end, start, count); - return BuilderFactory.STREAM_ENTRY_LIST.build(client.getObjectMultiBulkReply()); - } - - /** - * {@inheritDoc} - */ - @Override - public List>> xread(final int count, final long block, - final Entry... streams) { - checkIsInMultiOrPipeline(); - client.xread(count, block, streams); - client.setTimeoutInfinite(); - - try { - List streamsEntries = client.getObjectMultiBulkReply(); - if (streamsEntries == null) { // backward compatibility - return new ArrayList<>(); - } - - return BuilderFactory.STREAM_READ_RESPONSE.build(streamsEntries); - } finally { - client.rollbackTimeout(); - } + return connection.executeCommand(commandObjects.xrevrange(key, end, start, count)); } @Override public List>> xread(final XReadParams xReadParams, final Map streams) { checkIsInMultiOrPipeline(); - client.xread(xReadParams, streams); - - if (!xReadParams.hasBlock()) { - return BuilderFactory.STREAM_READ_RESPONSE.build(client.getObjectMultiBulkReply()); - } - - client.setTimeoutInfinite(); - try { - return BuilderFactory.STREAM_READ_RESPONSE.build(client.getObjectMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } + return connection.executeCommand(commandObjects.xread(xReadParams, streams)); } @Override public long xack(final String key, final String group, final StreamEntryID... ids) { checkIsInMultiOrPipeline(); - client.xack(key, group, ids); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.xack(key, group, ids)); } @Override public String xgroupCreate(final String key, final String groupname, final StreamEntryID id, final boolean makeStream) { checkIsInMultiOrPipeline(); - client.xgroupCreate(key, groupname, id, makeStream); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); } @Override public String xgroupSetID(final String key, final String groupname, final StreamEntryID id) { checkIsInMultiOrPipeline(); - client.xgroupSetID(key, groupname, id); - return client.getStatusCodeReply(); + return connection.executeCommand(commandObjects.xgroupSetID(key, groupname, id)); } @Override public long xgroupDestroy(final String key, final String groupname) { checkIsInMultiOrPipeline(); - client.xgroupDestroy(key, groupname); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.xgroupDestroy(key, groupname)); } @Override public long xgroupDelConsumer(final String key, final String groupname, final String consumerName) { checkIsInMultiOrPipeline(); - client.xgroupDelConsumer(key, groupname, consumerName); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.xgroupDelConsumer(key, groupname, consumerName)); } @Override public long xdel(final String key, final StreamEntryID... ids) { checkIsInMultiOrPipeline(); - client.xdel(key, ids); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.xdel(key, ids)); } @Override public long xtrim(final String key, final long maxLen, final boolean approximateLength) { checkIsInMultiOrPipeline(); - client.xtrim(key, maxLen, approximateLength); - return client.getIntegerReply(); + return connection.executeCommand(commandObjects.xtrim(key, maxLen, approximateLength)); } @Override public long xtrim(final String key, final XTrimParams params) { checkIsInMultiOrPipeline(); - client.xtrim(key, params); - return client.getIntegerReply(); - } - - @Override - public List>> xreadGroup(final String groupname, - final String consumer, final int count, final long block, final boolean noAck, - final Entry... streams) { - checkIsInMultiOrPipeline(); - client.xreadGroup(groupname, consumer, count, block, noAck, streams); - client.setTimeoutInfinite(); - - try { - return BuilderFactory.STREAM_READ_RESPONSE.build(client.getObjectMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } + return connection.executeCommand(commandObjects.xtrim(key, params)); } @Override @@ -4537,125 +8270,124 @@ public List>> xreadGroup(final String groupn final String consumer, final XReadGroupParams xReadGroupParams, final Map streams) { checkIsInMultiOrPipeline(); - client.xreadGroup(groupname, consumer, xReadGroupParams, streams); - - if (!xReadGroupParams.hasBlock()) { - return BuilderFactory.STREAM_READ_RESPONSE.build(client.getObjectMultiBulkReply()); - } - - client.setTimeoutInfinite(); - try { - return BuilderFactory.STREAM_READ_RESPONSE.build(client.getObjectMultiBulkReply()); - } finally { - client.rollbackTimeout(); - } + return connection.executeCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); } @Override public StreamPendingSummary xpending(final String key, final String groupname) { checkIsInMultiOrPipeline(); - client.xpending(key, groupname); - return BuilderFactory.STREAM_PENDING_SUMMARY.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xpending(key, groupname)); } @Override public List xpending(final String key, final String groupname, final StreamEntryID start, final StreamEntryID end, final int count, final String consumername) { checkIsInMultiOrPipeline(); - client.xpending(key, groupname, start, end, count, consumername); - return BuilderFactory.STREAM_PENDING_ENTRY_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); } @Override public List xpending(final String key, final String groupname, final XPendingParams params) { checkIsInMultiOrPipeline(); - client.xpending(key, groupname, params); - return BuilderFactory.STREAM_PENDING_ENTRY_LIST.build(client.getObjectMultiBulkReply()); - } - - @Override - public List xclaim(String key, String group, String consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, StreamEntryID... ids) { - checkIsInMultiOrPipeline(); - client.xclaim(key, group, consumername, minIdleTime, newIdleTime, retries, force, ids); - - return BuilderFactory.STREAM_ENTRY_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xpending(key, groupname, params)); } @Override public List xclaim(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { checkIsInMultiOrPipeline(); - client.xclaim(key, group, consumername, minIdleTime, params, ids); - - return BuilderFactory.STREAM_ENTRY_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); } @Override public List xclaimJustId(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { checkIsInMultiOrPipeline(); - client.xclaimJustId(key, group, consumername, minIdleTime, params, ids); - - return BuilderFactory.STREAM_ENTRY_ID_LIST.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); } @Override public Map.Entry> xautoclaim(String key, String group, String consumerName, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { checkIsInMultiOrPipeline(); - client.xautoclaim(key, group, consumerName, minIdleTime, start, params); - - return BuilderFactory.STREAM_AUTO_CLAIM_RESPONSE.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xautoclaim(key, group, consumerName, minIdleTime, start, params)); } @Override public Map.Entry> xautoclaimJustId(String key, String group, String consumerName, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { checkIsInMultiOrPipeline(); - client.xautoclaimJustId(key, group, consumerName, minIdleTime, start, params); - - return BuilderFactory.STREAM_AUTO_CLAIM_ID_RESPONSE.build(client.getObjectMultiBulkReply()); + return connection.executeCommand(commandObjects.xautoclaimJustId(key, group, consumerName, minIdleTime, start, params)); } @Override public StreamInfo xinfoStream(String key) { - client.xinfoStream(key); - - return BuilderFactory.STREAM_INFO.build(client.getObjectMultiBulkReply()); - + return connection.executeCommand(commandObjects.xinfoStream(key)); } @Override public List xinfoGroup(String key) { - client.xinfoGroup(key); - - return BuilderFactory.STREAM_GROUP_INFO_LIST.build(client.getObjectMultiBulkReply()); - + return connection.executeCommand(commandObjects.xinfoGroup(key)); } @Override public List xinfoConsumers(String key, String group) { - client.xinfoConsumers(key, group); - - return BuilderFactory.STREAM_CONSUMERS_INFO_LIST.build(client.getObjectMultiBulkReply()); - + return connection.executeCommand(commandObjects.xinfoConsumers(key, group)); } public Object sendCommand(ProtocolCommand cmd, String... args) { checkIsInMultiOrPipeline(); - client.sendCommand(cmd, args); - return client.getOne(); + connection.sendCommand(cmd, args); + return connection.getOne(); } public Object sendBlockingCommand(ProtocolCommand cmd, String... args) { checkIsInMultiOrPipeline(); - client.sendCommand(cmd, args); - client.setTimeoutInfinite(); + connection.sendCommand(cmd, args); + connection.setTimeoutInfinite(); try { - return client.getOne(); + return connection.getOne(); } finally { - client.rollbackTimeout(); + connection.rollbackTimeout(); } } + + private static byte[][] joinParameters(int... params) { + byte[][] result = new byte[params.length][]; + for (int i = 0; i < params.length; i++) { + result[i] = toByteArray(params[i]); + } + return result; + } + + private static byte[][] joinParameters(byte[] first, byte[][] rest) { + byte[][] result = new byte[rest.length + 1][]; + result[0] = first; + System.arraycopy(rest, 0, result, 1, rest.length); + return result; + } + + private static byte[][] joinParameters(byte[] first, byte[] second, byte[][] rest) { + byte[][] result = new byte[rest.length + 2][]; + result[0] = first; + result[1] = second; + System.arraycopy(rest, 0, result, 2, rest.length); + return result; + } + + private static String[] joinParameters(String first, String[] rest) { + String[] result = new String[rest.length + 1]; + result[0] = first; + System.arraycopy(rest, 0, result, 1, rest.length); + return result; + } + + private static String[] joinParameters(String first, String second, String[] rest) { + String[] result = new String[rest.length + 2]; + result[0] = first; + result[1] = second; + System.arraycopy(rest, 0, result, 2, rest.length); + return result; + } + } diff --git a/src/main/java/redis/clients/jedis/JedisCluster.java b/src/main/java/redis/clients/jedis/JedisCluster.java index dcf8041b73..48c9972c35 100644 --- a/src/main/java/redis/clients/jedis/JedisCluster.java +++ b/src/main/java/redis/clients/jedis/JedisCluster.java @@ -1,26 +1,19 @@ package redis.clients.jedis; -import redis.clients.jedis.args.*; -import redis.clients.jedis.commands.JedisClusterCommands; -import redis.clients.jedis.commands.JedisClusterScriptingCommands; -import redis.clients.jedis.commands.MultiKeyJedisClusterCommands; -import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.*; -import redis.clients.jedis.util.JedisClusterHashTagUtil; -import redis.clients.jedis.util.KeyMergeUtil; - import java.time.Duration; import java.util.Collections; -import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.Set; - import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import redis.clients.jedis.executors.ClusterCommandExecutor; -public class JedisCluster extends BinaryJedisCluster implements JedisClusterCommands, - MultiKeyJedisClusterCommands, JedisClusterScriptingCommands { +public class JedisCluster extends UnifiedJedis { + + /** + * Default timeout in milliseconds. + */ + public static final int DEFAULT_TIMEOUT = 2000; + public static final int DEFAULT_MAX_ATTEMPTS = 5; public JedisCluster(HostAndPort node) { this(Collections.singleton(node)); @@ -34,45 +27,45 @@ public JedisCluster(HostAndPort node, int timeout, int maxAttempts) { this(Collections.singleton(node), timeout, maxAttempts); } - public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { + public JedisCluster(HostAndPort node, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), poolConfig); } - public JedisCluster(HostAndPort node, int timeout, final GenericObjectPoolConfig poolConfig) { + public JedisCluster(HostAndPort node, int timeout, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), timeout, poolConfig); } public JedisCluster(HostAndPort node, int timeout, int maxAttempts, - final GenericObjectPoolConfig poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), timeout, maxAttempts, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - final GenericObjectPoolConfig poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - String password, final GenericObjectPoolConfig poolConfig) { + String password, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - String password, String clientName, final GenericObjectPoolConfig poolConfig) { + String password, String clientName, final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, user, password, clientName, poolConfig); } public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, - String password, String clientName, final GenericObjectPoolConfig poolConfig, + String password, String clientName, final GenericObjectPoolConfig poolConfig, boolean ssl) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, password, clientName, poolConfig, ssl); @@ -80,13 +73,13 @@ public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int public JedisCluster(HostAndPort node, int connectionTimeout, int soTimeout, int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl) { + final GenericObjectPoolConfig poolConfig, boolean ssl) { this(Collections.singleton(node), connectionTimeout, soTimeout, maxAttempts, user, password, clientName, poolConfig, ssl); } public JedisCluster(HostAndPort node, final JedisClientConfig clientConfig, int maxAttempts, - final GenericObjectPoolConfig poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(Collections.singleton(node), clientConfig, maxAttempts, poolConfig); } @@ -95,2875 +88,107 @@ public JedisCluster(Set nodes) { } public JedisCluster(Set nodes, int timeout) { - this(nodes, timeout, DEFAULT_MAX_ATTEMPTS); + this(nodes, DefaultJedisClientConfig.builder().timeoutMillis(timeout).build()); } public JedisCluster(Set nodes, int timeout, int maxAttempts) { - this(nodes, timeout, maxAttempts, new GenericObjectPoolConfig()); + this(nodes, DefaultJedisClientConfig.builder().timeoutMillis(timeout).build(), maxAttempts); + } + + public JedisCluster(Set nodes, String user, String password) { + this(nodes, DefaultJedisClientConfig.builder().user(user).password(password).build()); } - public JedisCluster(Set nodes, final GenericObjectPoolConfig poolConfig) { + public JedisCluster(Set nodes, final GenericObjectPoolConfig poolConfig) { this(nodes, DEFAULT_TIMEOUT, DEFAULT_MAX_ATTEMPTS, poolConfig); } public JedisCluster(Set nodes, int timeout, - final GenericObjectPoolConfig poolConfig) { + final GenericObjectPoolConfig poolConfig) { this(nodes, timeout, DEFAULT_MAX_ATTEMPTS, poolConfig); } public JedisCluster(Set jedisClusterNode, int timeout, int maxAttempts, - final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, timeout, maxAttempts, poolConfig); - } - - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, poolConfig); + final GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, timeout, timeout, maxAttempts, poolConfig); } - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String password, final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig); + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, final GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, poolConfig); } - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String password, String clientName, - final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, - poolConfig); + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String password, GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, null, poolConfig); } - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, user, password, clientName, + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String password, String clientName, + GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, poolConfig); } - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig) { - super(jedisClusterNode, connectionTimeout, soTimeout, infiniteSoTimeout, maxAttempts, user, - password, clientName, poolConfig); + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String user, String password, String clientName, + GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).user(user).password(password).clientName(clientName).build(), + maxAttempts, poolConfig); } - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, clientName, - poolConfig, ssl); + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int infiniteSoTimeout, int maxAttempts, String user, String password, + String clientName, GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) + .user(user).password(password).clientName(clientName).build(), maxAttempts, poolConfig); } - public JedisCluster(Set jedisClusterNode, int connectionTimeout, int soTimeout, - int maxAttempts, String user, String password, String clientName, - final GenericObjectPoolConfig poolConfig, boolean ssl) { - super(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, user, password, clientName, + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String password, String clientName, + GenericObjectPoolConfig poolConfig, boolean ssl) { + this(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, null, password, clientName, poolConfig, ssl); } - public JedisCluster(Set nodes, final JedisClientConfig clientConfig, - int maxAttempts, final GenericObjectPoolConfig poolConfig) { - super(nodes, clientConfig, maxAttempts, poolConfig); - } - - public JedisCluster(Set nodes, final JedisClientConfig clientConfig, - int maxAttempts, Duration maxTotalRetriesDuration, - final GenericObjectPoolConfig poolConfig) { - super(nodes, clientConfig, maxAttempts, maxTotalRetriesDuration, poolConfig); - } - - @Override - public boolean copy(String srcKey, String dstKey, boolean replace) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.copy(srcKey, dstKey, replace); - } - }.run(2, srcKey, dstKey); - } - - @Override - public String set(final String key, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.set(key, value); - } - }.run(key); - } - - @Override - public String set(final String key, final String value, final SetParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.set(key, value, params); - } - }.run(key); - } - - @Override - public String get(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.get(key); - } - }.run(key); - } - - @Override - public String getDel(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.getDel(key); - } - }.run(key); - } - - @Override - public String getEx(String key, GetExParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.getEx(key, params); - } - }.run(key); - } - - @Override - public boolean exists(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.exists(key); - } - }.run(key); - } - - @Override - public long exists(final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.exists(keys); - } - }.run(keys.length, keys); - } - - @Override - public long persist(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.persist(key); - } - }.run(key); - } - - @Override - public String type(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.type(key); - } - }.run(key); - } - - @Override - public byte[] dump(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public byte[] execute(Jedis connection) { - return connection.dump(key); - } - }.run(key); - } - - @Override - public String restore(final String key, final long ttl, final byte[] serializedValue) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.restore(key, ttl, serializedValue); - } - }.run(key); - } - - @Override - public String restore(final String key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.restore(key, ttl, serializedValue, params); - } - }.run(key); - } - - @Override - public long expire(final String key, final long seconds) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.expire(key, seconds); - } - }.run(key); - } - - @Override - public long pexpire(final String key, final long milliseconds) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pexpire(key, milliseconds); - } - }.run(key); - } - - @Override - public long expireAt(final String key, final long unixTime) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.expireAt(key, unixTime); - } - }.run(key); - } - - @Override - public long pexpireAt(final String key, final long millisecondsTimestamp) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pexpireAt(key, millisecondsTimestamp); - } - }.run(key); - } - - @Override - public long ttl(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.ttl(key); - } - }.run(key); - } - - @Override - public long pttl(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pttl(key); - } - }.run(key); - } - - @Override - public long touch(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.touch(key); - } - }.run(key); - } - - @Override - public long touch(final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.touch(keys); - } - }.run(keys.length, keys); - } - - @Override - public boolean setbit(final String key, final long offset, final boolean value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.setbit(key, offset, value); - } - }.run(key); - } - - @Override - public Boolean setbit(final String key, final long offset, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.setbit(key, offset, value); - } - }.run(key); - } - - @Override - public boolean getbit(final String key, final long offset) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.getbit(key, offset); - } - }.run(key); - } - - @Override - public long setrange(final String key, final long offset, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.setrange(key, offset, value); - } - }.run(key); - } - - @Override - public String getrange(final String key, final long startOffset, final long endOffset) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.getrange(key, startOffset, endOffset); - } - }.run(key); - } - - @Override - public String getSet(final String key, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.getSet(key, value); - } - }.run(key); - } - - @Override - public long setnx(final String key, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.setnx(key, value); - } - }.run(key); - } - - @Override - public String setex(final String key, final long seconds, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.setex(key, seconds, value); - } - }.run(key); - } - - @Override - public String psetex(final String key, final long milliseconds, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.psetex(key, milliseconds, value); - } - }.run(key); - } - - @Override - public long decrBy(final String key, final long decrement) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.decrBy(key, decrement); - } - }.run(key); - } - - @Override - public long decr(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.decr(key); - } - }.run(key); - } - - @Override - public long incrBy(final String key, final long increment) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.incrBy(key, increment); - } - }.run(key); - } - - @Override - public double incrByFloat(final String key, final double increment) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.incrByFloat(key, increment); - } - }.run(key); - } - - @Override - public long incr(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.incr(key); - } - }.run(key); - } - - @Override - public long append(final String key, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.append(key, value); - } - }.run(key); - } - - @Override - public String substr(final String key, final int start, final int end) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.substr(key, start, end); - } - }.run(key); - } - - @Override - public long hset(final String key, final String field, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hset(key, field, value); - } - }.run(key); - } - - @Override - public long hset(final String key, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hset(key, hash); - } - }.run(key); - } - - @Override - public String hget(final String key, final String field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.hget(key, field); - } - }.run(key); - } - - @Override - public long hsetnx(final String key, final String field, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hsetnx(key, field, value); - } - }.run(key); - } - - @Override - public String hmset(final String key, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.hmset(key, hash); - } - }.run(key); - } - - @Override - public List hmget(final String key, final String... fields) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.hmget(key, fields); - } - }.run(key); - } - - @Override - public long hincrBy(final String key, final String field, final long value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hincrBy(key, field, value); - } - }.run(key); - } - - @Override - public double hincrByFloat(final String key, final String field, final double value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.hincrByFloat(key, field, value); - } - }.run(key); - } - - @Override - public boolean hexists(final String key, final String field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.hexists(key, field); - } - }.run(key); - } - - @Override - public long hdel(final String key, final String... field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hdel(key, field); - } - }.run(key); - } - - @Override - public long hlen(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hlen(key); - } - }.run(key); - } - - @Override - public Set hkeys(final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.hkeys(key); - } - }.run(key); - } - - @Override - public List hvals(final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.hvals(key); - } - }.run(key); - } - - @Override - public Map hgetAll(final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Map execute(Jedis connection) { - return connection.hgetAll(key); - } - }.run(key); - } - - @Override - public String hrandfield(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.hrandfield(key); - } - }.run(key); - } - - @Override - public List hrandfield(final String key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.hrandfield(key, count); - } - }.run(key); - } - - @Override - public Map hrandfieldWithValues(final String key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Map execute(Jedis connection) { - return connection.hrandfieldWithValues(key, count); - } - }.run(key); - } - - @Override - public long rpush(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.rpush(key, string); - } - }.run(key); - } - - @Override - public long lpush(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpush(key, string); - } - }.run(key); - } - - @Override - public long llen(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.llen(key); - } - }.run(key); - } - - @Override - public List lrange(final String key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.lrange(key, start, stop); - } - }.run(key); - } - - @Override - public String ltrim(final String key, final long start, final long stop) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.ltrim(key, start, stop); - } - }.run(key); - } - - @Override - public String lindex(final String key, final long index) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.lindex(key, index); - } - }.run(key); - } - - @Override - public String lset(final String key, final long index, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.lset(key, index, value); - } - }.run(key); - } - - @Override - public long lrem(final String key, final long count, final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lrem(key, count, value); - } - }.run(key); - } - - @Override - public String lpop(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.lpop(key); - } - }.run(key); - } - - @Override - public List lpop(final String key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.lpop(key, count); - } - }.run(key); - } - - @Override - public Long lpos(final String key, final String element) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpos(key, element); - } - }.run(key); - } - - @Override - public Long lpos(final String key, final String element, final LPosParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpos(key, element, params); - } - }.run(key); - } - - @Override - public List lpos(final String key, final String element, final LPosParams params, - final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.lpos(key, element, params, count); - } - }.run(key); - } - - @Override - public String rpop(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.rpop(key); - } - }.run(key); - } - - @Override - public List rpop(final String key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.rpop(key, count); - } - }.run(key); - } - - @Override - public long sadd(final String key, final String... member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sadd(key, member); - } - }.run(key); - } - - @Override - public Set smembers(final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.smembers(key); - } - }.run(key); - } - - @Override - public long srem(final String key, final String... member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.srem(key, member); - } - }.run(key); - } - - @Override - public String spop(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.spop(key); - } - }.run(key); - } - - @Override - public Set spop(final String key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.spop(key, count); - } - }.run(key); - } - - @Override - public long scard(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.scard(key); - } - }.run(key); - } - - @Override - public boolean sismember(final String key, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.sismember(key, member); - } - }.run(key); - } - - @Override - public List smismember(final String key, final String... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.smismember(key, members); - } - }.run(key); - } - - @Override - public String srandmember(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.srandmember(key); - } - }.run(key); - } - - @Override - public List srandmember(final String key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.srandmember(key, count); - } - }.run(key); - } - - @Override - public long strlen(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.strlen(key); - } - }.run(key); - } - - @Override - public LCSMatchResult strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public LCSMatchResult execute(Jedis connection) { - return connection.strAlgoLCSKeys(keyA, keyB, params); - } - }.run(2, keyA, keyB); - } - - @Override - public LCSMatchResult strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public LCSMatchResult execute(Jedis connection) { - return connection.strAlgoLCSStrings(strA, strB, params); - } - }.runWithAnyNode(); - } - - @Override - public long zadd(final String key, final double score, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, score, member); - } - }.run(key); - } - - @Override - public long zadd(final String key, final double score, final String member, - final ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, score, member, params); - } - }.run(key); - } - - @Override - public long zadd(final String key, final Map scoreMembers) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, scoreMembers); - } - }.run(key); - } - - @Override - public long zadd(final String key, final Map scoreMembers, final ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zadd(key, scoreMembers, params); - } - }.run(key); - } - - @Override - public Double zaddIncr(String key, double score, String member, ZAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zaddIncr(key, score, member, params); - } - }.run(key); - } - - @Override - public Set zdiff(String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zdiff(keys); - } - }.run(keys.length, keys); - } - - @Override - public Set zdiffWithScores(String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zdiffWithScores(keys); - } - }.run(keys.length, keys); - } - - @Override - public long zdiffStore(final String dstkey, final String... keys) { - String[] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zdiffStore(dstkey, keys); - } - }.run(wholeKeys.length, wholeKeys); - } - - @Override - public Set zrange(final String key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrange(key, start, stop); - } - }.run(key); - } - - @Override - public long zrem(final String key, final String... members) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zrem(key, members); - } - }.run(key); - } - - @Override - public double zincrby(final String key, final double increment, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zincrby(key, increment, member); - } - }.run(key); - } - - @Override - public Double zincrby(final String key, final double increment, final String member, - final ZIncrByParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zincrby(key, increment, member, params); - } - }.run(key); - } - - @Override - public Long zrank(final String key, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zrank(key, member); - } - }.run(key); - } - - @Override - public Long zrevrank(final String key, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zrevrank(key, member); - } - }.run(key); - } - - @Override - public Set zrevrange(final String key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrange(key, start, stop); - } - }.run(key); - } - - @Override - public Set zrangeWithScores(final String key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeWithScores(key, start, stop); - } - }.run(key); - } - - @Override - public Set zrevrangeWithScores(final String key, final long start, final long stop) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeWithScores(key, start, stop); - } - }.run(key); - } - - @Override - public String zrandmember(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.zrandmember(key); - } - }.run(key); - } - - @Override - public Set zrandmember(final String key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrandmember(key, count); - } - }.run(key); - } - - @Override - public Set zrandmemberWithScores(final String key, final long count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrandmemberWithScores(key, count); - } - }.run(key); - } - - @Override - public long zcard(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zcard(key); - } - }.run(key); - } - - @Override - public Double zscore(final String key, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.zscore(key, member); - } - }.run(key); - } - - @Override - public List zmscore(final String key, final String... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.zmscore(key, members); - } - }.run(key); - } - - @Override - public Tuple zpopmax(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Tuple execute(Jedis connection) { - return connection.zpopmax(key); - } - }.run(key); - } - - @Override - public Set zpopmax(final String key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zpopmax(key, count); - } - }.run(key); - } - - @Override - public Tuple zpopmin(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Tuple execute(Jedis connection) { - return connection.zpopmin(key); - } - }.run(key); - } - - @Override - public Set zpopmin(final String key, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zpopmin(key, count); - } - }.run(key); - } - - @Override - public List sort(final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.sort(key); - } - }.run(key); - } - - @Override - public List sort(final String key, final SortingParams sortingParameters) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.sort(key, sortingParameters); - } - }.run(key); - } - - @Override - public long zcount(final String key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zcount(key, min, max); - } - }.run(key); - } - - @Override - public long zcount(final String key, final String min, final String max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zcount(key, min, max); - } - }.run(key); - } - - @Override - public Set zrangeByScore(final String key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max); - } - }.run(key); - } - - @Override - public Set zrangeByScore(final String key, final String min, final String max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max); - } - }.run(key); - } - - @Override - public Set zrevrangeByScore(final String key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min); - } - }.run(key); - } - - @Override - public Set zrangeByScore(final String key, final double min, final double max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max, offset, count); - } - }.run(key); - } - - @Override - public Set zrevrangeByScore(final String key, final String max, final String min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min); - } - }.run(key); - } - - @Override - public Set zrangeByScore(final String key, final String min, final String max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScore(key, min, max, offset, count); - } - }.run(key); - } - - @Override - public Set zrevrangeByScore(final String key, final double max, final double min, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min, offset, count); - } - }.run(key); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max); - } - }.run(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min); - } - }.run(key); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max, offset, count); - } - }.run(key); - } - - @Override - public Set zrevrangeByScore(final String key, final String max, final String min, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScore(key, max, min, offset, count); - } - }.run(key); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max); - } - }.run(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final String max, final String min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min); - } - }.run(key); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByScoreWithScores(key, min, max, offset, count); - } - }.run(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final double max, - final double min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - }.run(key); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final String max, - final String min, final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - }.run(key); - } - - @Override - public long zremrangeByRank(final String key, final long start, final long stop) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByRank(key, start, stop); - } - }.run(key); - } - - @Override - public long zremrangeByScore(final String key, final double min, final double max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByScore(key, min, max); - } - }.run(key); - } - - @Override - public long zremrangeByScore(final String key, final String min, final String max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByScore(key, min, max); - } - }.run(key); - } - - @Override - public long zlexcount(final String key, final String min, final String max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zlexcount(key, min, max); - } - }.run(key); - } - - @Override - public Set zrangeByLex(final String key, final String min, final String max) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByLex(key, min, max); - } - }.run(key); - } - - @Override - public Set zrangeByLex(final String key, final String min, final String max, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrangeByLex(key, min, max, offset, count); - } - }.run(key); - } - - @Override - public Set zrevrangeByLex(final String key, final String max, final String min) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByLex(key, max, min); - } - }.run(key); - } - - @Override - public Set zrevrangeByLex(final String key, final String max, final String min, - final int offset, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zrevrangeByLex(key, max, min, offset, count); - } - }.run(key); - } - - @Override - public long zremrangeByLex(final String key, final String min, final String max) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zremrangeByLex(key, min, max); - } - }.run(key); - } - - @Override - public long linsert(final String key, final ListPosition where, final String pivot, - final String value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.linsert(key, where, pivot, value); - } - }.run(key); - } - - @Override - public long lpushx(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.lpushx(key, string); - } - }.run(key); - } - - @Override - public long rpushx(final String key, final String... string) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.rpushx(key, string); - } - }.run(key); - } - - @Override - public long del(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.del(key); - } - }.run(key); - } - - @Override - public long unlink(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.unlink(key); - } - }.run(key); - } - - @Override - public long unlink(final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.unlink(keys); - } - }.run(keys.length, keys); - } - - @Override - public String echo(final String string) { - // note that it'll be run from arbitrary node - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.echo(string); - } - }.run(string); - } - - @Override - public long bitcount(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitcount(key); - } - }.run(key); - } - - @Override - public long bitcount(final String key, final long start, final long end) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitcount(key, start, end); - } - }.run(key); - } - - @Override - public long bitpos(String key, boolean value) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitpos(key, value); - } - }.run(key); - } - - @Override - public long bitpos(String key, boolean value, BitPosParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitpos(key, value, params); - } - }.run(key); - } - - @Override - public Set keys(final String pattern) { - if (pattern == null || pattern.isEmpty()) { - throw new IllegalArgumentException(this.getClass().getSimpleName() - + " only supports KEYS commands with non-empty patterns"); - } - if (!JedisClusterHashTagUtil.isClusterCompliantMatchPattern(pattern)) { - throw new IllegalArgumentException( - this.getClass().getSimpleName() - + " only supports KEYS commands with patterns containing hash-tags" - + " ( curly-brackets enclosed strings )"); - } - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.keys(pattern); - } - }.run(pattern); - } - - @Override - public ScanResult scan(final String cursor, final ScanParams params) { - return scan(cursor, params, null); - } - - @Override - public ScanResult scan(final String cursor, final ScanParams params, final String type) { - - String matchPattern = null; - - if (params == null || (matchPattern = params.match()) == null || matchPattern.isEmpty()) { - throw new IllegalArgumentException(JedisCluster.class.getSimpleName() - + " only supports SCAN commands with non-empty MATCH patterns"); - } - - if (!JedisClusterHashTagUtil.isClusterCompliantMatchPattern(matchPattern)) { - throw new IllegalArgumentException( - JedisCluster.class.getSimpleName() - + " only supports SCAN commands with MATCH patterns containing hash-tags" - + " ( curly-brackets enclosed strings )"); - } - - return new JedisClusterCommand< ScanResult>(connectionHandler, maxAttempts, - maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.scan(cursor, params, type); - } - }.run(matchPattern); - } - - @Override - public ScanResult> hscan(final String key, final String cursor, - final ScanParams scanParams) { - return new JedisClusterCommand>>(connectionHandler, maxAttempts, - maxTotalRetriesDuration) { - @Override - public ScanResult> execute(Jedis connection) { - return connection.hscan(key, cursor, scanParams); - } - }.run(key); - } - - @Override - public ScanResult sscan(final String key, final String cursor, final ScanParams scanParams) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.sscan(key, cursor, scanParams); - } - }.run(key); - } - - @Override - public ScanResult zscan(final String key, final String cursor, final ScanParams scanParams) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public ScanResult execute(Jedis connection) { - return connection.zscan(key, cursor, scanParams); - } - }.run(key); - } - - @Override - public long pfadd(final String key, final String... elements) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pfadd(key, elements); - } - }.run(key); - } - - @Override - public long pfcount(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pfcount(key); - } - }.run(key); - } - - @Override - public long del(final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.del(keys); - } - }.run(keys.length, keys); - } - - @Override - public String lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.lmove(srcKey, dstKey, from, to); - } - }.run(2, srcKey, dstKey); - } - - @Override - public String blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, - double timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.blmove(srcKey, dstKey, from, to, timeout); - } - }.run(2, srcKey, dstKey); - } - - @Override - public List blpop(final int timeout, final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.blpop(timeout, keys); - } - }.run(keys.length, keys); - - } - - @Override - public KeyedListElement blpop(final double timeout, final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public KeyedListElement execute(Jedis connection) { - return connection.blpop(timeout, keys); - } - }.run(keys.length, keys); - - } - - @Override - public List brpop(final int timeout, final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.brpop(timeout, keys); - } - }.run(keys.length, keys); - } - - @Override - public KeyedListElement brpop(final double timeout, final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public KeyedListElement execute(Jedis connection) { - return connection.brpop(timeout, keys); - } - }.run(keys.length, keys); - } - - @Override - public KeyedZSetElement bzpopmax(double timeout, String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public KeyedZSetElement execute(Jedis connection) { - return connection.bzpopmax(timeout, keys); - } - }.run(keys.length, keys); - } - - @Override - public KeyedZSetElement bzpopmin(double timeout, String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public KeyedZSetElement execute(Jedis connection) { - return connection.bzpopmin(timeout, keys); - } - }.run(keys.length, keys); - } - - @Override - public List blpop(final int timeout, final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.blpop(timeout, key); - } - }.run(key); - } - - @Override - public KeyedListElement blpop(double timeout, String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public KeyedListElement execute(Jedis connection) { - return connection.blpop(timeout, key); - } - }.run(key); - } - - @Override - public List brpop(final int timeout, final String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.brpop(timeout, key); - } - }.run(key); - } - - @Override - public KeyedListElement brpop(double timeout, String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public KeyedListElement execute(Jedis connection) { - return connection.brpop(timeout, key); - } - }.run(key); - } - - @Override - public List mget(final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.mget(keys); - } - }.run(keys.length, keys); - } - - @Override - public String mset(final String... keysvalues) { - String[] keys = new String[keysvalues.length / 2]; - - for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { - keys[keyIdx] = keysvalues[keyIdx * 2]; - } - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.mset(keysvalues); - } - }.run(keys.length, keys); - } - - @Override - public long msetnx(final String... keysvalues) { - String[] keys = new String[keysvalues.length / 2]; - - for (int keyIdx = 0; keyIdx < keys.length; keyIdx++) { - keys[keyIdx] = keysvalues[keyIdx * 2]; - } - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.msetnx(keysvalues); - } - }.run(keys.length, keys); - } - - @Override - public String rename(final String oldkey, final String newkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.rename(oldkey, newkey); - } - }.run(2, oldkey, newkey); - } - - @Override - public long renamenx(final String oldkey, final String newkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.renamenx(oldkey, newkey); - } - }.run(2, oldkey, newkey); - } - - @Override - public String rpoplpush(final String srckey, final String dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.rpoplpush(srckey, dstkey); - } - }.run(2, srckey, dstkey); - } - - @Override - public Set sdiff(final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.sdiff(keys); - } - }.run(keys.length, keys); - } - - @Override - public long sdiffstore(final String dstkey, final String... keys) { - String[] mergedKeys = KeyMergeUtil.merge(dstkey, keys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sdiffstore(dstkey, keys); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public Set sinter(final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.sinter(keys); - } - }.run(keys.length, keys); - } - - @Override - public long sinterstore(final String dstkey, final String... keys) { - String[] mergedKeys = KeyMergeUtil.merge(dstkey, keys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sinterstore(dstkey, keys); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public long smove(final String srckey, final String dstkey, final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.smove(srckey, dstkey, member); - } - }.run(2, srckey, dstkey); - } - - @Override - public long sort(final String key, final SortingParams sortingParameters, final String dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sort(key, sortingParameters, dstkey); - } - }.run(2, key, dstkey); - } - - @Override - public long sort(final String key, final String dstkey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sort(key, dstkey); - } - }.run(2, key, dstkey); - } - - @Override - public Set sunion(final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.sunion(keys); - } - }.run(keys.length, keys); - } - - @Override - public long sunionstore(final String dstkey, final String... keys) { - String[] wholeKeys = KeyMergeUtil.merge(dstkey, keys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.sunionstore(dstkey, keys); - } - }.run(wholeKeys.length, wholeKeys); - } - - @Override - public Set zinter(final ZParams params, final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zinter(params, keys); - } - }.run(keys.length, keys); - } - - @Override - public Set zinterWithScores(final ZParams params, final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zinterWithScores(params, keys); - } - }.run(keys.length, keys); - } - - @Override - public long zinterstore(final String dstkey, final String... sets) { - String[] wholeKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zinterstore(dstkey, sets); - } - }.run(wholeKeys.length, wholeKeys); - } - - @Override - public long zinterstore(final String dstkey, final ZParams params, final String... sets) { - String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zinterstore(dstkey, params, sets); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public Set zunion(final ZParams params, final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zunion(params, keys); - } - }.run(keys.length, keys); - } - - @Override - public Set zunionWithScores(final ZParams params, final String... keys) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Set execute(Jedis connection) { - return connection.zunionWithScores(params, keys); - } - }.run(keys.length, keys); - } - - @Override - public long zunionstore(final String dstkey, final String... sets) { - String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zunionstore(dstkey, sets); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public long zunionstore(final String dstkey, final ZParams params, final String... sets) { - String[] mergedKeys = KeyMergeUtil.merge(dstkey, sets); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.zunionstore(dstkey, params, sets); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public String brpoplpush(final String source, final String destination, final int timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.brpoplpush(source, destination, timeout); - } - }.run(2, source, destination); - } - - @Override - public Long publish(final String channel, final String message) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.publish(channel, message); - } - }.runWithAnyNode(); - } - - @Override - public void subscribe(final JedisPubSub jedisPubSub, final String... channels) { - new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Integer execute(Jedis connection) { - connection.subscribe(jedisPubSub, channels); - return 0; - } - }.runWithAnyNode(); - } - - @Override - public void psubscribe(final JedisPubSub jedisPubSub, final String... patterns) { - new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Integer execute(Jedis connection) { - connection.psubscribe(jedisPubSub, patterns); - return 0; - } - }.runWithAnyNode(); - } - - @Override - public long bitop(final BitOP op, final String destKey, final String... srcKeys) { - String[] mergedKeys = KeyMergeUtil.merge(destKey, srcKeys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.bitop(op, destKey, srcKeys); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public String pfmerge(final String destkey, final String... sourcekeys) { - String[] mergedKeys = KeyMergeUtil.merge(destkey, sourcekeys); - - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.pfmerge(destkey, sourcekeys); - } - }.run(mergedKeys.length, mergedKeys); - } - - @Override - public long pfcount(final String... keys) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.pfcount(keys); - } - }.run(keys.length, keys); - } - - @Override - public Object eval(final String script, final int keyCount, final String... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script, keyCount, params); - } - }.run(keyCount, params); - } - - @Override - public Object eval(final String script, final String sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script); - } - }.run(sampleKey); - } - - @Override - public Object eval(final String script, final List keys, final List args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.eval(script, keys, args); - } - }.run(keys.size(), keys.toArray(new String[keys.size()])); - } - - @Override - public Object evalsha(final String sha1, final int keyCount, final String... params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.evalsha(sha1, keyCount, params); - } - }.run(keyCount, params); - } - - @Override - public Object evalsha(final String sha1, final List keys, final List args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.evalsha(sha1, keys, args); - } - }.run(keys.size(), keys.toArray(new String[keys.size()])); - } - - @Override - public Object evalsha(final String sha1, final String sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.evalsha(sha1); - } - }.run(sampleKey); - } - - @Override - public Boolean scriptExists(final String sha1, final String sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Boolean execute(Jedis connection) { - return connection.scriptExists(sha1); - } - }.run(sampleKey); - } - - @Override - public List scriptExists(final String sampleKey, final String... sha1) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.scriptExists(sha1); - } - }.run(sampleKey); - } - - @Override - public String scriptLoad(final String script, final String sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.scriptLoad(script); - } - }.run(sampleKey); - } - - @Override - public String scriptFlush(final String sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.scriptFlush(); - } - }.run(sampleKey); - } - - @Override - public String scriptKill(final String sampleKey) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.scriptKill(); - } - }.run(sampleKey); - } - - @Override - public long geoadd(final String key, final double longitude, final double latitude, - final String member) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.geoadd(key, longitude, latitude, member); - } - }.run(key); - } - - @Override - public long geoadd(final String key, final Map memberCoordinateMap) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.geoadd(key, memberCoordinateMap); - } - }.run(key); - } - - @Override - public long geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.geoadd(key, params, memberCoordinateMap); - } - }.run(key); - } - - @Override - public Double geodist(final String key, final String member1, final String member2) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.geodist(key, member1, member2); - } - }.run(key); - } - - @Override - public Double geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Double execute(Jedis connection) { - return connection.geodist(key, member1, member2, unit); - } - }.run(key); - } - - @Override - public List geohash(final String key, final String... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.geohash(key, members); - } - }.run(key); - } - - @Override - public List geopos(final String key, final String... members) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.geopos(key, members); - } - }.run(key); - } - - @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadius(key, longitude, latitude, radius, unit); - } - }.run(key); - } - - @Override - public List georadiusReadonly(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusReadonly(key, longitude, latitude, radius, unit); - } - }.run(key); - } - - @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadius(key, longitude, latitude, radius, unit, param); - } - }.run(key); - } - - @Override - public long georadiusStore(final String key, final double longitude, final double latitude, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - String[] keys = storeParam.getStringKeys(key); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam); - } - }.run(keys.length, keys); - } - - @Override - public List georadiusReadonly(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusReadonly(key, longitude, latitude, radius, unit, param); - } - }.run(key); - } - - @Override - public List georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMember(key, member, radius, unit); - } - }.run(key); - } - - @Override - public List georadiusByMemberReadonly(final String key, final String member, - final double radius, final GeoUnit unit) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMemberReadonly(key, member, radius, unit); - } - }.run(key); - } - - @Override - public List georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMember(key, member, radius, unit, param); - } - }.run(key); - } - - @Override - public long georadiusByMemberStore(final String key, final String member, final double radius, - final GeoUnit unit, final GeoRadiusParam param, final GeoRadiusStoreParam storeParam) { - String[] keys = storeParam.getStringKeys(key); - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.georadiusByMemberStore(key, member, radius, unit, param, storeParam); - } - }.run(keys.length, keys); - } - - @Override - public List georadiusByMemberReadonly(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.georadiusByMemberReadonly(key, member, radius, unit, param); - } - }.run(key); - } - - @Override - public List bitfield(final String key, final String... arguments) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.bitfield(key, arguments); - } - }.run(key); - } - - @Override - public List bitfieldReadonly(final String key, final String... arguments) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.bitfieldReadonly(key, arguments); - } - }.run(key); - } - - @Override - public long hstrlen(final String key, final String field) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.hstrlen(key, field); - } - }.run(key); - } - - @Override - public Long memoryUsage(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.memoryUsage(key); - } - }.run(key); - } - - @Override - public Long memoryUsage(final String key, final int samples) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.memoryUsage(key, samples); - } - }.run(key); - } - - @Override - public StreamEntryID xadd(final String key, final StreamEntryID id, final Map hash) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public StreamEntryID execute(Jedis connection) { - return connection.xadd(key, id, hash); - } - }.run(key); - } - - @Override - public StreamEntryID xadd(final String key, final StreamEntryID id, - final Map hash, final long maxLen, final boolean approximateLength) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public StreamEntryID execute(Jedis connection) { - return connection.xadd(key, id, hash, maxLen, approximateLength); - } - }.run(key); - } - - @Override - public StreamEntryID xadd(final String key, final Map hash, final XAddParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public StreamEntryID execute(Jedis connection) { - return connection.xadd(key, hash, params); - } - }.run(key); - } - - @Override - public long xlen(final String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xlen(key); - } - }.run(key); - } - - @Override - public List xrange(final String key, final StreamEntryID start, - final StreamEntryID end) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrange(key, start, end); - } - }.run(key); - } - - @Override - public List xrange(final String key, final StreamEntryID start, - final StreamEntryID end, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrange(key, start, end, count); - } - }.run(key); - } - - @Override - public List xrevrange(final String key, final StreamEntryID end, - final StreamEntryID start) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrevrange(key, end, start); - } - }.run(key); - } - - @Override - public List xrevrange(final String key, final StreamEntryID end, - final StreamEntryID start, final int count) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xrevrange(key, end, start, count); - } - }.run(key); - } - - @Override - public List>> xread(final int count, final long block, - final Entry... streams) { - String[] keys = new String[streams.length]; - for (int i = 0; i < streams.length; ++i) { - keys[i] = streams[i].getKey(); - } - - return new JedisClusterCommand>>>(connectionHandler, - maxAttempts, this.maxTotalRetriesDuration) { - @Override - public List>> execute(Jedis connection) { - return connection.xread(count, block, streams); - } - }.run(keys.length, keys); - } - - @Override - public List>> xread(final XReadParams xReadParams, final Map streams) { - return new JedisClusterCommand>>>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List>> execute(Jedis connection) { - return connection.xread(xReadParams, streams); - } - }.run(streams.size(), getKeys(streams)); - } - - @Override - public long xack(final String key, final String group, final StreamEntryID... ids) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xack(key, group, ids); - } - }.run(key); - } - - @Override - public String xgroupCreate(final String key, final String groupname, final StreamEntryID id, - final boolean makeStream) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.xgroupCreate(key, groupname, id, makeStream); - } - }.run(key); - } - - @Override - public String xgroupSetID(final String key, final String groupname, final StreamEntryID id) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public String execute(Jedis connection) { - return connection.xgroupSetID(key, groupname, id); - } - }.run(key); - } - - @Override - public long xgroupDestroy(final String key, final String groupname) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xgroupDestroy(key, groupname); - } - }.run(key); - } - - @Override - public long xgroupDelConsumer(final String key, final String groupname, final String consumername) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xgroupDelConsumer(key, groupname, consumername); - } - }.run(key); - } - - @Override - public List>> xreadGroup(final String groupname, - final String consumer, final int count, final long block, final boolean noAck, - final Entry... streams) { - - String[] keys = new String[streams.length]; - for (int i = 0; i < streams.length; ++i) { - keys[i] = streams[i].getKey(); - } - - return new JedisClusterCommand>>>(connectionHandler, - maxAttempts, this.maxTotalRetriesDuration) { - @Override - public List>> execute(Jedis connection) { - return connection.xreadGroup(groupname, consumer, count, block, noAck, streams); - } - }.run(keys.length, keys); - } - - @Override - public List>> xreadGroup(final String groupname, - final String consumer, final XReadGroupParams xReadGroupParams, - final Map streams) { - return new JedisClusterCommand>>>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List>> execute(Jedis connection) { - return connection.xreadGroup(groupname, consumer, xReadGroupParams, streams); - } - }.run(streams.size(), getKeys(streams)); - } - - @Override - public StreamPendingSummary xpending(final String key, final String groupname) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public StreamPendingSummary execute(Jedis connection) { - return connection.xpending(key, groupname); - } - }.run(key); - } - - @Override - public List xpending(final String key, final String groupname, - final StreamEntryID start, final StreamEntryID end, final int count, final String consumername) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xpending(key, groupname, start, end, count, consumername); - } - }.run(key); - } - - @Override - public List xpending(final String key, final String groupname, final XPendingParams params) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xpending(key, groupname, params); - } - }.run(key); - } - - @Override - public long xdel(final String key, final StreamEntryID... ids) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xdel(key, ids); - } - }.run(key); - } - - @Override - public long xtrim(final String key, final long maxLen, final boolean approximateLength) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xtrim(key, maxLen, approximateLength); - } - }.run(key); - } - - @Override - public long xtrim(final String key, final XTrimParams params) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.xtrim(key, params); - } - }.run(key); - } - - @Override - public List xclaim(final String key, final String group, final String consumername, - final long minIdleTime, final long newIdleTime, final int retries, final boolean force, - final StreamEntryID... ids) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xclaim(key, group, consumername, minIdleTime, newIdleTime, retries, - force, ids); - } - }.run(key); - } - - @Override - public List xclaim(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xclaim(key, group, consumername, minIdleTime, params, ids); - } - }.run(key); - } - - @Override - public List xclaimJustId(String key, String group, String consumername, - long minIdleTime, XClaimParams params, StreamEntryID... ids) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xclaimJustId(key, group, consumername, minIdleTime, params, ids); - } - }.run(key); - } - - @Override - public Map.Entry> xautoclaim(final String key, final String group, final String consumerName, - final long minIdleTime, final StreamEntryID start, XAutoClaimParams params) { - return new JedisClusterCommand>>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Map.Entry> execute(Jedis connection) { - return connection.xautoclaim(key, group, consumerName, minIdleTime, start, params); - } - }.run(key); - } - - @Override - public Map.Entry> xautoclaimJustId(final String key, final String group, final String consumerName, - final long minIdleTime, final StreamEntryID start, XAutoClaimParams params) { - return new JedisClusterCommand>>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Map.Entry> execute(Jedis connection) { - return connection.xautoclaimJustId(key, group, consumerName, minIdleTime, start, params); - } - }.run(key); + public JedisCluster(Set jedisClusterNode, int connectionTimeout, + int soTimeout, int maxAttempts, String user, String password, String clientName, + GenericObjectPoolConfig poolConfig, boolean ssl) { + this(jedisClusterNode, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).user(user).password(password).clientName(clientName).ssl(ssl).build(), + maxAttempts, poolConfig); } - @Override - public StreamInfo xinfoStream(String key) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public StreamInfo execute(Jedis connection) { - return connection.xinfoStream(key); - } - }.run(key); + public JedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, + int maxAttempts, GenericObjectPoolConfig poolConfig) { + this(jedisClusterNode, clientConfig, maxAttempts, + Duration.ofMillis((long) clientConfig.getSocketTimeoutMillis() * maxAttempts), poolConfig); } - @Override - public List xinfoGroup(String key) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xinfoGroup(key); - } - }.run(key); + public JedisCluster(Set jedisClusterNode, JedisClientConfig clientConfig, + int maxAttempts, Duration maxTotalRetriesDuration, GenericObjectPoolConfig poolConfig) { + super(jedisClusterNode, clientConfig, poolConfig, maxAttempts, maxTotalRetriesDuration); } - @Override - public List xinfoConsumers(String key, String group) { - return new JedisClusterCommand>(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public List execute(Jedis connection) { - return connection.xinfoConsumers(key, group); - } - }.run(key); + public JedisCluster(Set jedisClusterNodes, JedisClientConfig clientConfig) { + this(jedisClusterNodes, clientConfig, DEFAULT_MAX_ATTEMPTS); } - @Override - public long waitReplicas(final String key, final int replicas, final long timeout) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Long execute(Jedis connection) { - return connection.waitReplicas(replicas, timeout); - } - }.run(key); + public JedisCluster(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts) { + super(jedisClusterNodes, clientConfig, maxAttempts); } - public Object sendCommand(final String sampleKey, final ProtocolCommand cmd, final String... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.sendCommand(cmd, args); - } - }.run(sampleKey); + public JedisCluster(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts, Duration maxTotalRetriesDuration) { + super(jedisClusterNodes, clientConfig, maxAttempts, maxTotalRetriesDuration); } - public Object sendBlockingCommand(final String sampleKey, final ProtocolCommand cmd, - final String... args) { - return new JedisClusterCommand(connectionHandler, maxAttempts, maxTotalRetriesDuration) { - @Override - public Object execute(Jedis connection) { - return connection.sendBlockingCommand(cmd, args); - } - }.run(sampleKey); + public Map getClusterNodes() { + return ((ClusterCommandExecutor) executor).provider.getNodes(); } - private static String[] getKeys(final Map map) { - return map.keySet().toArray(new String[map.size()]); + public Connection getConnectionFromSlot(int slot) { + return ((ClusterCommandExecutor) executor).provider.getConnectionFromSlot(slot); } } diff --git a/src/main/java/redis/clients/jedis/JedisClusterCommand.java b/src/main/java/redis/clients/jedis/JedisClusterCommand.java deleted file mode 100644 index d626f33984..0000000000 --- a/src/main/java/redis/clients/jedis/JedisClusterCommand.java +++ /dev/null @@ -1,222 +0,0 @@ -package redis.clients.jedis; - -import java.time.Duration; -import java.time.Instant; -import java.util.concurrent.TimeUnit; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.exceptions.JedisAskDataException; -import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; -import redis.clients.jedis.exceptions.JedisClusterOperationException; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisMovedDataException; -import redis.clients.jedis.exceptions.JedisRedirectionException; -import redis.clients.jedis.util.JedisClusterCRC16; - -public abstract class JedisClusterCommand { - - private static final Logger LOG = LoggerFactory.getLogger(JedisClusterCommand.class); - - private final JedisClusterConnectionHandler connectionHandler; - private final int maxAttempts; - private final Duration maxTotalRetriesDuration; - - public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int maxAttempts) { - this(connectionHandler, maxAttempts, Duration.ofMillis((long) BinaryJedisCluster.DEFAULT_TIMEOUT * maxAttempts)); - } - - /** - * @param connectionHandler - * @param maxAttempts - * @param maxTotalRetriesDuration No more attempts after we have been trying for this long. - */ - public JedisClusterCommand(JedisClusterConnectionHandler connectionHandler, int maxAttempts, - Duration maxTotalRetriesDuration) { - this.connectionHandler = connectionHandler; - this.maxAttempts = maxAttempts; - this.maxTotalRetriesDuration = maxTotalRetriesDuration; - } - - public abstract T execute(Jedis connection); - - public T run(String key) { - return runWithRetries(JedisClusterCRC16.getSlot(key)); - } - - public T run(int keyCount, String... keys) { - if (keys == null || keys.length == 0) { - throw new JedisClusterOperationException("No way to dispatch this command to Redis Cluster."); - } - - // For multiple keys, only execute if they all share the same connection slot. - int slot = JedisClusterCRC16.getSlot(keys[0]); - if (keys.length > 1) { - for (int i = 1; i < keyCount; i++) { - int nextSlot = JedisClusterCRC16.getSlot(keys[i]); - if (slot != nextSlot) { - throw new JedisClusterOperationException("No way to dispatch this command to Redis " - + "Cluster because keys have different slots."); - } - } - } - - return runWithRetries(slot); - } - - public T runBinary(byte[] key) { - return runWithRetries(JedisClusterCRC16.getSlot(key)); - } - - public T runBinary(int keyCount, byte[]... keys) { - if (keys == null || keys.length == 0) { - throw new JedisClusterOperationException("No way to dispatch this command to Redis Cluster."); - } - - // For multiple keys, only execute if they all share the same connection slot. - int slot = JedisClusterCRC16.getSlot(keys[0]); - if (keys.length > 1) { - for (int i = 1; i < keyCount; i++) { - int nextSlot = JedisClusterCRC16.getSlot(keys[i]); - if (slot != nextSlot) { - throw new JedisClusterOperationException("No way to dispatch this command to Redis " - + "Cluster because keys have different slots."); - } - } - } - - return runWithRetries(slot); - } - - public T runWithAnyNode() { - Jedis connection = null; - try { - connection = connectionHandler.getConnection(); - return execute(connection); - } finally { - releaseConnection(connection); - } - } - - private T runWithRetries(final int slot) { - Instant deadline = Instant.now().plus(maxTotalRetriesDuration); - - JedisRedirectionException redirect = null; - int consecutiveConnectionFailures = 0; - Exception lastException = null; - for (int attemptsLeft = this.maxAttempts; attemptsLeft > 0; attemptsLeft--) { - Jedis connection = null; - try { - if (redirect != null) { - connection = connectionHandler.getConnectionFromNode(redirect.getTargetNode()); - if (redirect instanceof JedisAskDataException) { - // TODO: Pipeline asking with the original command to make it faster.... - connection.asking(); - } - } else { - connection = connectionHandler.getConnectionFromSlot(slot); - } - - return execute(connection); - - } catch (JedisConnectionException jce) { - lastException = jce; - ++consecutiveConnectionFailures; - LOG.debug("Failed connecting to Redis: {}", connection, jce); - // "- 1" because we just did one, but the attemptsLeft counter hasn't been decremented yet - boolean reset = handleConnectionProblem(attemptsLeft - 1, consecutiveConnectionFailures, deadline); - if (reset) { - consecutiveConnectionFailures = 0; - redirect = null; - } - } catch (JedisRedirectionException jre) { - // avoid updating lastException if it is a connection exception - if (lastException == null || lastException instanceof JedisRedirectionException) { - lastException = jre; - } - LOG.debug("Redirected by server to {}", jre.getTargetNode()); - consecutiveConnectionFailures = 0; - redirect = jre; - // if MOVED redirection occurred, - if (jre instanceof JedisMovedDataException) { - // it rebuilds cluster's slot cache recommended by Redis cluster specification - this.connectionHandler.renewSlotCache(connection); - } - } finally { - releaseConnection(connection); - } - if (Instant.now().isAfter(deadline)) { - throw new JedisClusterOperationException("Cluster retry deadline exceeded."); - } - } - - JedisClusterMaxAttemptsException maxAttemptsException - = new JedisClusterMaxAttemptsException("No more cluster attempts left."); - maxAttemptsException.addSuppressed(lastException); - throw maxAttemptsException; - } - - /** - * Related values should be reset if TRUE is returned. - * - * @param attemptsLeft - * @param consecutiveConnectionFailures - * @param doneDeadline - * @return true - if some actions are taken - *
false - if no actions are taken - */ - private boolean handleConnectionProblem(int attemptsLeft, int consecutiveConnectionFailures, Instant doneDeadline) { - if (this.maxAttempts < 3) { - // Since we only renew the slots cache after two consecutive connection - // failures (see consecutiveConnectionFailures above), we need to special - // case the situation where we max out after two or fewer attempts. - // Otherwise, on two or fewer max attempts, the slots cache would never be - // renewed. - if (attemptsLeft == 0) { - this.connectionHandler.renewSlotCache(); - return true; - } - return false; - } - - if (consecutiveConnectionFailures < 2) { - return false; - } - - sleep(getBackoffSleepMillis(attemptsLeft, doneDeadline)); - //We need this because if node is not reachable anymore - we need to finally initiate slots - //renewing, or we can stuck with cluster state without one node in opposite case. - //TODO make tracking of successful/unsuccessful operations for node - do renewing only - //if there were no successful responses from this node last few seconds - this.connectionHandler.renewSlotCache(); - return true; - } - - private static long getBackoffSleepMillis(int attemptsLeft, Instant deadline) { - if (attemptsLeft <= 0) { - return 0; - } - - long millisLeft = Duration.between(Instant.now(), deadline).toMillis(); - if (millisLeft < 0) { - throw new JedisClusterOperationException("Cluster retry deadline exceeded."); - } - - return millisLeft / (attemptsLeft * (attemptsLeft + 1)); - } - - protected void sleep(long sleepMillis) { - try { - TimeUnit.MILLISECONDS.sleep(sleepMillis); - } catch (InterruptedException e) { - throw new JedisClusterOperationException(e); - } - } - - private void releaseConnection(Jedis connection) { - if (connection != null) { - connection.close(); - } - } - -} diff --git a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java deleted file mode 100644 index 89f42ee88f..0000000000 --- a/src/main/java/redis/clients/jedis/JedisClusterConnectionHandler.java +++ /dev/null @@ -1,87 +0,0 @@ -package redis.clients.jedis; - -import java.io.Closeable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Map; -import java.util.Set; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - -import redis.clients.jedis.exceptions.JedisConnectionException; - -public abstract class JedisClusterConnectionHandler implements Closeable { - protected final JedisClusterInfoCache cache; - - public JedisClusterConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password) { - this(nodes, poolConfig, connectionTimeout, soTimeout, password, null); - } - - public JedisClusterConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password, String clientName) { - this(nodes, poolConfig, connectionTimeout, soTimeout, null, password, clientName); - } - - public JedisClusterConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String user, String password, String clientName) { - this(nodes, poolConfig, connectionTimeout, soTimeout, 0, user, password, clientName); - } - - public JedisClusterConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, String user, String password, String clientName) { - this(nodes, poolConfig, - DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) - .user(user).password(password).clientName(clientName).build()); - } - - public JedisClusterConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, final JedisClientConfig clientConfig) { - this.cache = new JedisClusterInfoCache(poolConfig, clientConfig); - initializeSlotsCache(nodes, clientConfig); - } - - protected abstract Jedis getConnection(); - - protected abstract Jedis getConnectionFromSlot(int slot); - - public Jedis getConnectionFromNode(HostAndPort node) { - return cache.setupNodeIfNotExist(node).getResource(); - } - - public Map getNodes() { - return cache.getNodes(); - } - - private void initializeSlotsCache(Set startNodes, JedisClientConfig clientConfig) { - ArrayList startNodeList = new ArrayList<>(startNodes); - Collections.shuffle(startNodeList); - - for (HostAndPort hostAndPort : startNodeList) { - try (Jedis jedis = new Jedis(hostAndPort, clientConfig)) { - cache.discoverClusterNodesAndSlots(jedis); - return; - } catch (JedisConnectionException e) { - // try next nodes - } - } - } - - public void renewSlotCache() { - cache.renewClusterSlots(null); - } - - public void renewSlotCache(Jedis jedis) { - cache.renewClusterSlots(jedis); - } - - @Override - public void close() { - cache.reset(); - } -} diff --git a/src/main/java/redis/clients/jedis/JedisClusterInfoCache.java b/src/main/java/redis/clients/jedis/JedisClusterInfoCache.java index 5506204721..52f77e44b4 100644 --- a/src/main/java/redis/clients/jedis/JedisClusterInfoCache.java +++ b/src/main/java/redis/clients/jedis/JedisClusterInfoCache.java @@ -12,103 +12,44 @@ import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.util.Pool; import redis.clients.jedis.util.SafeEncoder; public class JedisClusterInfoCache { - private final Map nodes = new HashMap<>(); - private final Map slots = new HashMap<>(); + + private final Map nodes = new HashMap<>(); + private final Map slots = new HashMap<>(); + private final Map slotNodes = new HashMap<>(); private final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock(); private final Lock r = rwl.readLock(); private final Lock w = rwl.writeLock(); private final Lock rediscoverLock = new ReentrantLock(); - private final GenericObjectPoolConfig poolConfig; + private final GenericObjectPoolConfig poolConfig; private final JedisClientConfig clientConfig; private static final int MASTER_NODE_INDEX = 2; - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, int timeout) { - this(poolConfig, timeout, timeout, null, null); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final String password, - final String clientName) { - this(poolConfig, connectionTimeout, soTimeout, null, password, clientName); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, - final String password, final String clientName) { - this(poolConfig, connectionTimeout, soTimeout, infiniteSoTimeout, null, password, clientName); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final String user, final String password, - final String clientName) { - this(poolConfig, connectionTimeout, soTimeout, user, password, clientName, false, null, null, - null, (HostAndPortMapper) null); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, - final String user, final String password, final String clientName) { - this(poolConfig, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, clientName, - false, null, null, null, (HostAndPortMapper) null); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final String password, - final String clientName, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - HostAndPortMapper hostAndPortMap) { - this(poolConfig, connectionTimeout, soTimeout, null, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMap); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final String user, final String password, - final String clientName, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier, - HostAndPortMapper hostAndPortMap) { - this(poolConfig, connectionTimeout, soTimeout, 0, user, password, clientName, ssl, - sslSocketFactory, sslParameters, hostnameVerifier, hostAndPortMap); - } - - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, - final String user, final String password, final String clientName, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier, HostAndPortMapper hostAndPortMap) { - this(poolConfig, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) - .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout).user(user) - .password(password).clientName(clientName).ssl(ssl).sslSocketFactory(sslSocketFactory) - .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier) - .hostAndPortMapper(hostAndPortMap).build()); + public JedisClusterInfoCache(final JedisClientConfig clientConfig) { + this(clientConfig, new GenericObjectPoolConfig()); } - public JedisClusterInfoCache(final GenericObjectPoolConfig poolConfig, - final JedisClientConfig clientConfig) { + public JedisClusterInfoCache(final JedisClientConfig clientConfig, + final GenericObjectPoolConfig poolConfig) { this.poolConfig = poolConfig; this.clientConfig = clientConfig; } - public void discoverClusterNodesAndSlots(Jedis jedis) { - List slots = jedis.clusterSlots(); + public void discoverClusterNodesAndSlots(Connection jedis) { + List slotsInfo = executeClusterSlots(jedis); w.lock(); try { reset(); - for (Object slotInfoObj : slots) { + for (Object slotInfoObj : slotsInfo) { List slotInfo = (List) slotInfoObj; if (slotInfo.size() <= MASTER_NODE_INDEX) { @@ -137,7 +78,7 @@ public void discoverClusterNodesAndSlots(Jedis jedis) { } } - public void renewClusterSlots(Jedis jedis) { + public void renewClusterSlots(Connection jedis) { // If rediscovering is already in process - no need to start one more same rediscovering, just return if (rediscoverLock.tryLock()) { try { @@ -150,8 +91,8 @@ public void renewClusterSlots(Jedis jedis) { } } - for (JedisPool jp : getShuffledNodesPool()) { - Jedis j = null; + for (ConnectionPool jp : getShuffledNodesPool()) { + Connection j = null; try { j = jp.getResource(); discoverClusterSlots(j); @@ -170,14 +111,15 @@ public void renewClusterSlots(Jedis jedis) { } } - private void discoverClusterSlots(Jedis jedis) { - List slots = jedis.clusterSlots(); + private void discoverClusterSlots(Connection jedis) { + List slotsInfo = executeClusterSlots(jedis); w.lock(); try { this.slots.clear(); + this.slotNodes.clear(); Set hostAndPortKeys = new HashSet<>(); - for (Object slotInfoObj : slots) { + for (Object slotInfoObj : slotsInfo) { List slotInfo = (List) slotInfoObj; if (slotInfo.size() <= MASTER_NODE_INDEX) { @@ -203,11 +145,11 @@ private void discoverClusterSlots(Jedis jedis) { } // Remove dead nodes according to the latest query - Iterator> entryIt = nodes.entrySet().iterator(); + Iterator> entryIt = nodes.entrySet().iterator(); while (entryIt.hasNext()) { - Entry entry = entryIt.next(); + Entry entry = entryIt.next(); if (!hostAndPortKeys.contains(entry.getKey())) { - JedisPool pool = entry.getValue(); + ConnectionPool pool = entry.getValue(); try { if (pool != null) { pool.destroy(); @@ -229,14 +171,14 @@ private HostAndPort generateHostAndPort(List hostInfos) { return new HostAndPort(host, port); } - public JedisPool setupNodeIfNotExist(final HostAndPort node) { + public ConnectionPool setupNodeIfNotExist(final HostAndPort node) { w.lock(); try { String nodeKey = getNodeKey(node); - JedisPool existingPool = nodes.get(nodeKey); + ConnectionPool existingPool = nodes.get(nodeKey); if (existingPool != null) return existingPool; - JedisPool nodePool = new JedisPool(poolConfig, node, clientConfig); + ConnectionPool nodePool = new ConnectionPool(node, clientConfig, poolConfig); nodes.put(nodeKey, nodePool); return nodePool; } finally { @@ -247,8 +189,9 @@ public JedisPool setupNodeIfNotExist(final HostAndPort node) { public void assignSlotToNode(int slot, HostAndPort targetNode) { w.lock(); try { - JedisPool targetPool = setupNodeIfNotExist(targetNode); + ConnectionPool targetPool = setupNodeIfNotExist(targetNode); slots.put(slot, targetPool); + slotNodes.put(slot, targetNode); } finally { w.unlock(); } @@ -257,16 +200,17 @@ public void assignSlotToNode(int slot, HostAndPort targetNode) { public void assignSlotsToNode(List targetSlots, HostAndPort targetNode) { w.lock(); try { - JedisPool targetPool = setupNodeIfNotExist(targetNode); + ConnectionPool targetPool = setupNodeIfNotExist(targetNode); for (Integer slot : targetSlots) { slots.put(slot, targetPool); + slotNodes.put(slot, targetNode); } } finally { w.unlock(); } } - public JedisPool getNode(String nodeKey) { + public ConnectionPool getNode(String nodeKey) { r.lock(); try { return nodes.get(nodeKey); @@ -275,7 +219,11 @@ public JedisPool getNode(String nodeKey) { } } - public JedisPool getSlotPool(int slot) { + public ConnectionPool getNode(HostAndPort node) { + return getNode(getNodeKey(node)); + } + + public ConnectionPool getSlotPool(int slot) { r.lock(); try { return slots.get(slot); @@ -284,7 +232,16 @@ public JedisPool getSlotPool(int slot) { } } - public Map getNodes() { + public HostAndPort getSlotNode(int slot) { + r.lock(); + try { + return slotNodes.get(slot); + } finally { + r.unlock(); + } + } + + public Map getNodes() { r.lock(); try { return new HashMap<>(nodes); @@ -293,10 +250,10 @@ public Map getNodes() { } } - public List getShuffledNodesPool() { + public List getShuffledNodesPool() { r.lock(); try { - List pools = new ArrayList<>(nodes.values()); + List pools = new ArrayList<>(nodes.values()); Collections.shuffle(pools); return pools; } finally { @@ -310,7 +267,7 @@ public List getShuffledNodesPool() { public void reset() { w.lock(); try { - for (JedisPool pool : nodes.values()) { + for (ConnectionPool pool : nodes.values()) { try { if (pool != null) { pool.destroy(); @@ -321,29 +278,20 @@ public void reset() { } nodes.clear(); slots.clear(); + slotNodes.clear(); } finally { w.unlock(); } } public static String getNodeKey(HostAndPort hnp) { - return hnp.getHost() + ":" + hnp.getPort(); + //return hnp.getHost() + ":" + hnp.getPort(); + return hnp.toString(); } - /** - * @deprecated This method will be removed in future. - */ - @Deprecated - public static String getNodeKey(Client client) { - return client.getHost() + ":" + client.getPort(); - } - - /** - * @deprecated This method will be removed in future. - */ - @Deprecated - public static String getNodeKey(Jedis jedis) { - return getNodeKey(jedis.getClient()); + private List executeClusterSlots(Connection jedis) { + jedis.sendCommand(Protocol.Command.CLUSTER, "SLOTS"); + return jedis.getObjectMultiBulkReply(); } private List getAssignedSlotArray(List slotInfo) { diff --git a/src/main/java/redis/clients/jedis/JedisFactory.java b/src/main/java/redis/clients/jedis/JedisFactory.java index e81eabb358..fcce26025c 100644 --- a/src/main/java/redis/clients/jedis/JedisFactory.java +++ b/src/main/java/redis/clients/jedis/JedisFactory.java @@ -19,6 +19,7 @@ /** * PoolableObjectFactory custom impl. */ +// Legacy public class JedisFactory implements PooledObjectFactory { private static final Logger logger = LoggerFactory.getLogger(JedisFactory.class); @@ -45,7 +46,7 @@ protected JedisFactory(final String host, final int port, final int connectionTi /** * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. */ - protected JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, final String user, final String password, final int database, final String clientName) { this(connectionTimeout, soTimeout, infiniteSoTimeout, user, password, database, clientName, false, null, null, null); } @@ -89,7 +90,7 @@ protected JedisFactory(final JedisSocketFactory jedisSocketFactory, final JedisC /** * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. */ - protected JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + JedisFactory(final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, final String user, final String password, final int database, final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { this(DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) @@ -102,7 +103,7 @@ protected JedisFactory(final int connectionTimeout, final int soTimeout, final i /** * {@link #setHostAndPort(redis.clients.jedis.HostAndPort) setHostAndPort} must be called later. */ - protected JedisFactory(final JedisClientConfig clientConfig) { + JedisFactory(final JedisClientConfig clientConfig) { this.clientConfig = clientConfig; this.jedisSocketFactory = new DefaultJedisSocketFactory(clientConfig); } @@ -134,8 +135,11 @@ protected JedisFactory(final URI uri, final int connectionTimeout, final int soT this.jedisSocketFactory = new DefaultJedisSocketFactory(new HostAndPort(uri.getHost(), uri.getPort()), this.clientConfig); } - public void setHostAndPort(final HostAndPort hostAndPort) { - jedisSocketFactory.updateHostAndPort(hostAndPort); + void setHostAndPort(final HostAndPort hostAndPort) { + if (!(jedisSocketFactory instanceof DefaultJedisSocketFactory)) { + throw new IllegalStateException("setHostAndPort method has limited capability."); + } + ((DefaultJedisSocketFactory) jedisSocketFactory).updateHostAndPort(hostAndPort); } public void setPassword(final String password) { @@ -144,7 +148,7 @@ public void setPassword(final String password) { @Override public void activateObject(PooledObject pooledJedis) throws Exception { - final BinaryJedis jedis = pooledJedis.getObject(); + final Jedis jedis = pooledJedis.getObject(); if (jedis.getDB() != clientConfig.getDatabase()) { jedis.select(clientConfig.getDatabase()); } @@ -152,7 +156,7 @@ public void activateObject(PooledObject pooledJedis) throws Exception { @Override public void destroyObject(PooledObject pooledJedis) throws Exception { - final BinaryJedis jedis = pooledJedis.getObject(); + final Jedis jedis = pooledJedis.getObject(); if (jedis.isConnected()) { try { // need a proper test, probably with mock @@ -201,17 +205,10 @@ public void passivateObject(PooledObject pooledJedis) throws Exception { @Override public boolean validateObject(PooledObject pooledJedis) { - final BinaryJedis jedis = pooledJedis.getObject(); + final Jedis jedis = pooledJedis.getObject(); try { - String host = jedisSocketFactory.getHost(); - int port = jedisSocketFactory.getPort(); - - String connectionHost = jedis.getClient().getHost(); - int connectionPort = jedis.getClient().getPort(); - - return host.equals(connectionHost) - && port == connectionPort && jedis.isConnected() - && jedis.ping().equals("PONG"); + // check HostAndPort ?? + return jedis.getConnection().isConnected() && jedis.ping().equals("PONG"); } catch (final Exception e) { logger.error("Error while validating pooled Jedis object.", e); return false; diff --git a/src/main/java/redis/clients/jedis/JedisMonitor.java b/src/main/java/redis/clients/jedis/JedisMonitor.java index 6e372f98f3..821af4858a 100644 --- a/src/main/java/redis/clients/jedis/JedisMonitor.java +++ b/src/main/java/redis/clients/jedis/JedisMonitor.java @@ -1,9 +1,10 @@ package redis.clients.jedis; public abstract class JedisMonitor { - protected Client client; - public void proceed(Client client) { + protected Connection client; + + public void proceed(Connection client) { this.client = client; this.client.setTimeoutInfinite(); do { @@ -13,4 +14,4 @@ public void proceed(Client client) { } public abstract void onCommand(String command); -} \ No newline at end of file +} diff --git a/src/main/java/redis/clients/jedis/JedisPool.java b/src/main/java/redis/clients/jedis/JedisPool.java index ae23596084..913e46a4be 100644 --- a/src/main/java/redis/clients/jedis/JedisPool.java +++ b/src/main/java/redis/clients/jedis/JedisPool.java @@ -13,6 +13,7 @@ import redis.clients.jedis.util.JedisURIHelper; import redis.clients.jedis.util.Pool; +// Legacy public class JedisPool extends Pool { private static final Logger log = LoggerFactory.getLogger(JedisPool.class); @@ -21,8 +22,8 @@ public JedisPool() { this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); } - public JedisPool(final GenericObjectPoolConfig poolConfig, final String host) { - this(poolConfig, host, Protocol.DEFAULT_PORT); + public JedisPool(final GenericObjectPoolConfig poolConfig, final String url) { + this(poolConfig, URI.create(url)); } public JedisPool(String host, int port) { @@ -39,8 +40,7 @@ public JedisPool(String host, int port) { * @param url */ public JedisPool(final String url) { - this(new GenericObjectPoolConfig(), new JedisFactory(URI.create(url), Protocol.DEFAULT_TIMEOUT, - Protocol.DEFAULT_TIMEOUT, null)); + this(URI.create(url)); } /** @@ -355,7 +355,7 @@ public JedisPool(final GenericObjectPoolConfig poolConfig, final URI uri, sslSocketFactory, sslParameters, hostnameVerifier)); } - public JedisPool(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + public JedisPool(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { super(poolConfig, factory); } @@ -373,7 +373,7 @@ public void returnResource(final Jedis resource) { resource.resetState(); super.returnResource(resource); } catch (RuntimeException e) { - returnBrokenResource(resource); + super.returnBrokenResource(resource); log.warn("Resource is returned to the pool as broken", e); } } diff --git a/src/main/java/redis/clients/jedis/JedisPoolConfig.java b/src/main/java/redis/clients/jedis/JedisPoolConfig.java index f9ddceca90..c88364bf4f 100644 --- a/src/main/java/redis/clients/jedis/JedisPoolConfig.java +++ b/src/main/java/redis/clients/jedis/JedisPoolConfig.java @@ -3,6 +3,7 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig; public class JedisPoolConfig extends GenericObjectPoolConfig { + public JedisPoolConfig() { // defaults to make your life with connection pool easier :) setTestWhileIdle(true); diff --git a/src/main/java/redis/clients/jedis/JedisPooled.java b/src/main/java/redis/clients/jedis/JedisPooled.java new file mode 100644 index 0000000000..a014c9dd3f --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisPooled.java @@ -0,0 +1,380 @@ +package redis.clients.jedis; + +import java.net.URI; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocketFactory; + +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +import redis.clients.jedis.providers.PooledConnectionProvider; +import redis.clients.jedis.util.JedisURIHelper; +import redis.clients.jedis.util.Pool; + +public class JedisPooled extends UnifiedJedis { + + public JedisPooled() { + this(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host) { + this(poolConfig, host, Protocol.DEFAULT_PORT); + } + + public JedisPooled(String host, int port) { + this(new GenericObjectPoolConfig(), host, port); + } + + /** + * WARNING: This constructor only accepts a uri string as {@code url}. + * {@link JedisURIHelper#isValid(java.net.URI)} can be used before this. + *

+ * To use a host string, {@link #JedisPooled(java.lang.String, int)} can be used with + * {@link Protocol#DEFAULT_PORT}. + * + * @param url + */ + public JedisPooled(final String url) { + super(url); + } + + /** + * WARNING: This constructor only accepts a uri string as {@code url}. + * {@link JedisURIHelper#isValid(java.net.URI)} can be used before this. + *

+ * To use a host string, + * {@link #JedisPooled(java.lang.String, int, boolean, javax.net.ssl.SSLSocketFactory, javax.net.ssl.SSLParameters, javax.net.ssl.HostnameVerifier)} + * can be used with {@link Protocol#DEFAULT_PORT} and {@code ssl=true}. + * + * @param url + * @param sslSocketFactory + * @param sslParameters + * @param hostnameVerifier + */ + public JedisPooled(final String url, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(URI.create(url), sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final URI uri) { + super(uri); + } + + public JedisPooled(final URI uri, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), uri, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPooled(final URI uri, final int timeout) { + this(new GenericObjectPoolConfig(), uri, timeout); + } + + public JedisPooled(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), uri, timeout, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password) { + this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE); + } + + public JedisPooled(final String host, int port, String user, final String password) { + this(new GenericObjectPoolConfig(), host, port, user, password); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + String user, final String password) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, user, password, + Protocol.DEFAULT_DATABASE); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password) { + this(poolConfig, host, port, timeout, user, password, Protocol.DEFAULT_DATABASE); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final boolean ssl) { + this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final boolean ssl) { + this(poolConfig, host, port, timeout, user, password, Protocol.DEFAULT_DATABASE, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, password, Protocol.DEFAULT_DATABASE, ssl, + sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final boolean ssl) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, Protocol.DEFAULT_TIMEOUT, ssl, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int timeout) { + this(poolConfig, host, port, timeout, null); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int timeout, final boolean ssl) { + this(poolConfig, host, port, timeout, null, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int timeout, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, null, ssl, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database) { + this(poolConfig, host, port, timeout, password, database, null); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database) { + this(poolConfig, host, port, timeout, user, password, database, null); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final boolean ssl) { + this(poolConfig, host, port, timeout, password, database, null, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database, final boolean ssl) { + this(poolConfig, host, port, timeout, user, password, database, null, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, password, database, null, ssl, sslSocketFactory, + sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final String clientName) { + this(poolConfig, host, port, timeout, timeout, password, database, clientName); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database, + final String clientName) { + this(poolConfig, host, port, timeout, timeout, user, password, database, clientName); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final String clientName, + final boolean ssl) { + this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String user, final String password, final int database, + final String clientName, final boolean ssl) { + this(poolConfig, host, port, timeout, timeout, user, password, database, clientName, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + int timeout, final String password, final int database, final String clientName, + final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, timeout, timeout, password, database, clientName, ssl, + sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String password, final int database, + final String clientName, final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, connectionTimeout, soTimeout, 0, password, database, clientName, + ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final String password, final int database, final String clientName, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, connectionTimeout, soTimeout, infiniteSoTimeout, null, password, + database, clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String user, final String password, + final int database, final String clientName, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, host, port, connectionTimeout, soTimeout, 0, user, password, database, + clientName, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final String user, final String password, final int database, final String clientName, + final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(new HostAndPort(host, port), DefaultJedisClientConfig.create(connectionTimeout, soTimeout, + infiniteSoTimeout, user, password, database, clientName, ssl, sslSocketFactory, sslParameters, + hostnameVerifier, null)); + } + + public JedisPooled(final HostAndPort hostAndPort, final JedisClientConfig clientConfig) { + this(new GenericObjectPoolConfig(), hostAndPort, clientConfig); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final HostAndPort hostAndPort, + final JedisClientConfig clientConfig) { + this(hostAndPort, clientConfig, poolConfig); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final JedisSocketFactory jedisSocketFactory, + final JedisClientConfig clientConfig) { + this(new ConnectionFactory(jedisSocketFactory, clientConfig), poolConfig); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig) { + this(poolConfig, Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT); + } + + public JedisPooled(final String host, final int port, final boolean ssl) { + this(new GenericObjectPoolConfig(), host, port, ssl); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String password, final int database, + final String clientName) { + this(poolConfig, host, port, connectionTimeout, soTimeout, null, password, database, clientName); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final String user, final String password, + final int database, final String clientName) { + this(poolConfig, host, port, connectionTimeout, soTimeout, 0, user, password, database, clientName); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, int port, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final String user, final String password, final int database, final String clientName) { + this(new HostAndPort(host, port), DefaultJedisClientConfig.create(connectionTimeout, soTimeout, + infiniteSoTimeout, user, password, database, clientName, false, null, null, null, null), + poolConfig); + } + + public JedisPooled(final String host, final int port, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(new GenericObjectPoolConfig(), host, port, ssl, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int connectionTimeout, final int soTimeout, final String password, + final int database, final String clientName, final boolean ssl) { + this(poolConfig, host, port, connectionTimeout, soTimeout, password, database, clientName, ssl, + null, null, null); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final String host, + final int port, final int connectionTimeout, final int soTimeout, final String user, + final String password, final int database, final String clientName, final boolean ssl) { + this(poolConfig, host, port, connectionTimeout, soTimeout, user, password, database, + clientName, ssl, null, null, null); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri) { + this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(poolConfig, uri, Protocol.DEFAULT_TIMEOUT, sslSocketFactory, sslParameters, + hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri, final int timeout) { + this(poolConfig, uri, timeout, timeout); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri, + final int timeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri, + final int connectionTimeout, final int soTimeout) { + this(poolConfig, uri, connectionTimeout, soTimeout, null, null, null); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri, + final int connectionTimeout, final int soTimeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(poolConfig, uri, connectionTimeout, soTimeout, 0, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public JedisPooled(final GenericObjectPoolConfig poolConfig, final URI uri, + final int connectionTimeout, final int soTimeout, final int infiniteSoTimeout, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(new HostAndPort(uri.getHost(), uri.getPort()), DefaultJedisClientConfig.create( + connectionTimeout, soTimeout, infiniteSoTimeout, JedisURIHelper.getUser(uri), + JedisURIHelper.getPassword(uri), JedisURIHelper.getDBIndex(uri), null, + JedisURIHelper.isRedisSSLScheme(uri), sslSocketFactory, sslParameters, hostnameVerifier, null)); + } + + public JedisPooled(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + this(factory, poolConfig); + } + + public JedisPooled(HostAndPort hostAndPort) { + this(new ConnectionFactory(hostAndPort), new GenericObjectPoolConfig()); + } + + public JedisPooled(HostAndPort hostAndPort, GenericObjectPoolConfig poolConfig) { + this(new ConnectionFactory(hostAndPort), poolConfig); + } + + public JedisPooled(HostAndPort hostAndPort, JedisClientConfig clientConfig, GenericObjectPoolConfig poolConfig) { + this(new ConnectionFactory(hostAndPort, clientConfig), poolConfig); + } + + public JedisPooled(PooledObjectFactory factory, GenericObjectPoolConfig poolConfig) { + this(new PooledConnectionProvider(factory, poolConfig)); + } + + public JedisPooled(PooledConnectionProvider provider) { + super(provider); + } + + public final Pool getPool() { + return ((PooledConnectionProvider) provider).getPool(); + } +} diff --git a/src/main/java/redis/clients/jedis/JedisPubSub.java b/src/main/java/redis/clients/jedis/JedisPubSub.java index c09563931a..2bedb1d738 100644 --- a/src/main/java/redis/clients/jedis/JedisPubSub.java +++ b/src/main/java/redis/clients/jedis/JedisPubSub.java @@ -1,16 +1,11 @@ package redis.clients.jedis; -import static redis.clients.jedis.Protocol.Keyword.MESSAGE; -import static redis.clients.jedis.Protocol.Keyword.PMESSAGE; -import static redis.clients.jedis.Protocol.Keyword.PSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.PUNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.SUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.UNSUBSCRIBE; -import static redis.clients.jedis.Protocol.Keyword.PONG; +import static redis.clients.jedis.Protocol.ResponseKeyword.*; import java.util.Arrays; import java.util.List; +import redis.clients.jedis.Protocol.Command; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; import redis.clients.jedis.util.SafeEncoder; @@ -19,7 +14,7 @@ public abstract class JedisPubSub { private static final String JEDIS_SUBSCRIPTION_MESSAGE = "JedisPubSub is not subscribed to a Jedis instance."; private int subscribedChannels = 0; - private volatile Client client; + private volatile Connection client; public void onMessage(String channel, String message) { } @@ -47,7 +42,7 @@ public void unsubscribe() { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.unsubscribe(); + client.sendCommand(Command.UNSUBSCRIBE); client.flush(); } @@ -55,7 +50,7 @@ public void unsubscribe(String... channels) { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.unsubscribe(channels); + client.sendCommand(Command.UNSUBSCRIBE, channels); client.flush(); } @@ -63,7 +58,7 @@ public void subscribe(String... channels) { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.subscribe(channels); + client.sendCommand(Command.SUBSCRIBE, channels); client.flush(); } @@ -71,7 +66,7 @@ public void psubscribe(String... patterns) { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.psubscribe(patterns); + client.sendCommand(Command.PSUBSCRIBE, patterns); client.flush(); } @@ -79,7 +74,7 @@ public void punsubscribe() { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.punsubscribe(); + client.sendCommand(Command.PUNSUBSCRIBE); client.flush(); } @@ -87,7 +82,7 @@ public void punsubscribe(String... patterns) { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.punsubscribe(patterns); + client.sendCommand(Command.PUNSUBSCRIBE, patterns); client.flush(); } @@ -95,7 +90,7 @@ public void ping() { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.ping(); + client.sendCommand(Command.PING); client.flush(); } @@ -103,7 +98,7 @@ public void ping(String argument) { if (client == null) { throw new JedisConnectionException(JEDIS_SUBSCRIPTION_MESSAGE); } - client.ping(argument); + client.sendCommand(Command.PING, argument); client.flush(); } @@ -111,21 +106,26 @@ public boolean isSubscribed() { return subscribedChannels > 0; } - public void proceedWithPatterns(Client client, String... patterns) { + public void proceedWithPatterns(Connection client, String... patterns) { this.client = client; - client.psubscribe(patterns); - client.flush(); - process(client); +// client.psubscribe(patterns); +// client.flush(); + psubscribe(patterns); +// process(client); + process(); } - public void proceed(Client client, String... channels) { + public void proceed(Connection client, String... channels) { this.client = client; - client.subscribe(channels); - client.flush(); - process(client); +// client.subscribe(channels); +// client.flush(); + subscribe(channels); +// process(client); + process(); } - private void process(Client client) { +// private void process(Client client) { + private void process() { do { List reply = client.getUnflushedObjectMultiBulkReply(); diff --git a/src/main/java/redis/clients/jedis/JedisSentinelPool.java b/src/main/java/redis/clients/jedis/JedisSentinelPool.java index 18db671ac3..85de79adf6 100644 --- a/src/main/java/redis/clients/jedis/JedisSentinelPool.java +++ b/src/main/java/redis/clients/jedis/JedisSentinelPool.java @@ -185,7 +185,7 @@ public JedisSentinelPool(String masterName, Set sentinels, } private static Set parseHostAndPorts(Set strings) { - return strings.stream().map(HostAndPort::parseString).collect(Collectors.toSet()); + return strings.stream().map(HostAndPort::from).collect(Collectors.toSet()); } @Override @@ -226,7 +226,7 @@ private HostAndPort initSentinels(Set sentinels, final String maste LOG.debug("Connecting to Sentinel {}", sentinel); - try (Jedis jedis = new Jedis(sentinel, sentinelClientConfig)) { + try (Sentinel jedis = new Sentinel(sentinel, sentinelClientConfig)) { List masterAddr = jedis.sentinelGetMasterAddrByName(masterName); @@ -289,8 +289,7 @@ public Jedis getResource() { // get a reference because it can change concurrently final HostAndPort master = currentHostMaster; - final HostAndPort connection = new HostAndPort(jedis.getClient().getHost(), jedis.getClient() - .getPort()); + final HostAndPort connection = jedis.getClient().getHostAndPort(); if (master.equals(connection)) { // connected to the correct master @@ -320,7 +319,7 @@ protected class MasterListener extends Thread { protected String host; protected int port; protected long subscribeRetryWaitTimeMillis = 5000; - protected volatile Jedis j; + protected volatile Sentinel j; protected AtomicBoolean running = new AtomicBoolean(false); protected MasterListener() { @@ -353,7 +352,7 @@ public void run() { } final HostAndPort hostPort = new HostAndPort(host, port); - j = new Jedis(hostPort, sentinelClientConfig); + j = new Sentinel(hostPort, sentinelClientConfig); // code for active refresh List masterAddr = j.sentinelGetMasterAddrByName(masterName); diff --git a/src/main/java/redis/clients/jedis/JedisShardInfo.java b/src/main/java/redis/clients/jedis/JedisShardInfo.java deleted file mode 100644 index 625a6a1342..0000000000 --- a/src/main/java/redis/clients/jedis/JedisShardInfo.java +++ /dev/null @@ -1,266 +0,0 @@ -package redis.clients.jedis; - -import java.net.URI; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLSocketFactory; - -import redis.clients.jedis.exceptions.InvalidURIException; -import redis.clients.jedis.util.JedisURIHelper; -import redis.clients.jedis.util.ShardInfo; -import redis.clients.jedis.util.Sharded; - -public class JedisShardInfo extends ShardInfo { - - private int connectionTimeout; - private int soTimeout; - private String host; - private int port; - private String user = null; - private String password = null; - private String name = null; - // Default Redis DB - private int db = 0; - private boolean ssl; - private SSLSocketFactory sslSocketFactory; - private SSLParameters sslParameters; - private HostnameVerifier hostnameVerifier; - - public JedisShardInfo(String host) { - super(Sharded.DEFAULT_WEIGHT); - URI uri = URI.create(host); - if (JedisURIHelper.isValid(uri)) { - this.host = uri.getHost(); - this.port = uri.getPort(); - this.user = JedisURIHelper.getUser(uri); - this.password = JedisURIHelper.getPassword(uri); - this.db = JedisURIHelper.getDBIndex(uri); - this.ssl = JedisURIHelper.isRedisSSLScheme(uri); - } else { - this.host = host; - this.port = Protocol.DEFAULT_PORT; - } - } - - public JedisShardInfo(String host, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier) { - this(host); - this.sslSocketFactory = sslSocketFactory; - this.sslParameters = sslParameters; - this.hostnameVerifier = hostnameVerifier; - } - - public JedisShardInfo(String host, String name) { - this(host, Protocol.DEFAULT_PORT, name); - } - - public JedisShardInfo(HostAndPort hp) { - this(hp.getHost(), hp.getPort()); - } - - public JedisShardInfo(String host, int port) { - this(host, port, Protocol.DEFAULT_TIMEOUT); - } - - public JedisShardInfo(String host, int port, boolean ssl) { - this(host, port, Protocol.DEFAULT_TIMEOUT, ssl); - } - - public JedisShardInfo(String host, int port, boolean ssl, SSLSocketFactory sslSocketFactory, - SSLParameters sslParameters, HostnameVerifier hostnameVerifier) { - this(host, port, Protocol.DEFAULT_TIMEOUT, ssl, sslSocketFactory, sslParameters, - hostnameVerifier); - } - - public JedisShardInfo(String host, int port, String name) { - this(host, port, Protocol.DEFAULT_TIMEOUT, name); - } - - public JedisShardInfo(String host, int port, String name, boolean ssl) { - this(host, port, Protocol.DEFAULT_TIMEOUT, name, ssl); - } - - public JedisShardInfo(String host, int port, String name, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(host, port, Protocol.DEFAULT_TIMEOUT, name, ssl, sslSocketFactory, sslParameters, - hostnameVerifier); - } - - public JedisShardInfo(String host, int port, int timeout) { - this(host, port, timeout, timeout, Sharded.DEFAULT_WEIGHT); - } - - public JedisShardInfo(String host, int port, int timeout, boolean ssl) { - this(host, port, timeout, timeout, Sharded.DEFAULT_WEIGHT, ssl); - } - - public JedisShardInfo(String host, int port, int timeout, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(host, port, timeout, timeout, Sharded.DEFAULT_WEIGHT, ssl, sslSocketFactory, - sslParameters, hostnameVerifier); - } - - public JedisShardInfo(String host, int port, int timeout, String name) { - this(host, port, timeout, timeout, Sharded.DEFAULT_WEIGHT); - this.name = name; - } - - public JedisShardInfo(String host, int port, int timeout, String name, boolean ssl) { - this(host, port, timeout, timeout, Sharded.DEFAULT_WEIGHT, ssl); - this.name = name; - } - - public JedisShardInfo(String host, int port, int timeout, String name, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(host, port, timeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier); - this.name = name; - } - - public JedisShardInfo(String host, int port, int connectionTimeout, int soTimeout, int weight) { - super(weight); - this.host = host; - this.port = port; - this.connectionTimeout = connectionTimeout; - this.soTimeout = soTimeout; - } - - public JedisShardInfo(String host, int port, int connectionTimeout, int soTimeout, int weight, - boolean ssl) { - super(weight); - this.host = host; - this.port = port; - this.connectionTimeout = connectionTimeout; - this.soTimeout = soTimeout; - this.ssl = ssl; - } - - public JedisShardInfo(String host, int port, int connectionTimeout, int soTimeout, int weight, - boolean ssl, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(host, port, connectionTimeout, soTimeout, weight, ssl); - this.sslSocketFactory = sslSocketFactory; - this.sslParameters = sslParameters; - this.hostnameVerifier = hostnameVerifier; - } - - public JedisShardInfo(String host, String name, int port, int timeout, int weight) { - this(host, port, timeout, timeout, weight); - this.name = name; - } - - public JedisShardInfo(String host, String name, int port, int timeout, int weight, boolean ssl) { - this(host, port, timeout, timeout, weight, ssl); - this.name = name; - } - - public JedisShardInfo(String host, String name, int port, int timeout, int weight, boolean ssl, - SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(host, port, timeout, timeout, weight, ssl, sslSocketFactory, sslParameters, - hostnameVerifier); - this.name = name; - } - - public JedisShardInfo(URI uri) { - super(Sharded.DEFAULT_WEIGHT); - if (!JedisURIHelper.isValid(uri)) { - throw new InvalidURIException(String.format( - "Cannot open Redis connection due invalid URI. %s", uri.toString())); - } - - this.host = uri.getHost(); - this.port = uri.getPort(); - this.user = JedisURIHelper.getUser(uri); - this.password = JedisURIHelper.getPassword(uri); - this.db = JedisURIHelper.getDBIndex(uri); - this.ssl = JedisURIHelper.isRedisSSLScheme(uri); - } - - public JedisShardInfo(URI uri, SSLSocketFactory sslSocketFactory, SSLParameters sslParameters, - HostnameVerifier hostnameVerifier) { - this(uri); - this.sslSocketFactory = sslSocketFactory; - this.sslParameters = sslParameters; - this.hostnameVerifier = hostnameVerifier; - } - - @Override - public String toString() { - return host + ":" + port + "*" + getWeight(); - } - - public String getHost() { - return host; - } - - public int getPort() { - return port; - } - - public String getPassword() { - return password; - } - - public void setPassword(String auth) { - this.password = auth; - } - - public String getUser() { - return user; - } - - public void setUser(String user) { - this.user = user; - } - - public int getConnectionTimeout() { - return connectionTimeout; - } - - public void setConnectionTimeout(int connectionTimeout) { - this.connectionTimeout = connectionTimeout; - } - - public int getSoTimeout() { - return soTimeout; - } - - public void setSoTimeout(int soTimeout) { - this.soTimeout = soTimeout; - } - - @Override - public String getName() { - return name; - } - - public int getDb() { - return db; - } - - public boolean getSsl() { - return ssl; - } - - public SSLSocketFactory getSslSocketFactory() { - return sslSocketFactory; - } - - public SSLParameters getSslParameters() { - return sslParameters; - } - - public HostnameVerifier getHostnameVerifier() { - return hostnameVerifier; - } - - @Override - public Jedis createResource() { - return new Jedis(this); - } - -} diff --git a/src/main/java/redis/clients/jedis/JedisSharding.java b/src/main/java/redis/clients/jedis/JedisSharding.java new file mode 100644 index 0000000000..a1cb7371e4 --- /dev/null +++ b/src/main/java/redis/clients/jedis/JedisSharding.java @@ -0,0 +1,42 @@ +package redis.clients.jedis; + +import java.util.List; +import java.util.regex.Pattern; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import redis.clients.jedis.providers.ShardedConnectionProvider; +import redis.clients.jedis.util.Hashing; + +public class JedisSharding extends UnifiedJedis { + + public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern.compile("\\{(.+?)\\}"); + + public JedisSharding(List shards) { + this(new ShardedConnectionProvider(shards)); + } + + public JedisSharding(List shards, JedisClientConfig clientConfig) { + this(new ShardedConnectionProvider(shards, clientConfig)); + } + + public JedisSharding(List shards, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig) { + this(new ShardedConnectionProvider(shards, clientConfig, poolConfig)); + } + + public JedisSharding(List shards, JedisClientConfig clientConfig, Hashing algo) { + this(new ShardedConnectionProvider(shards, clientConfig, algo)); + } + + public JedisSharding(List shards, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig, Hashing algo) { + this(new ShardedConnectionProvider(shards, clientConfig, poolConfig, algo)); + } + + public JedisSharding(ShardedConnectionProvider provider) { + super(provider); + } + + public JedisSharding(ShardedConnectionProvider provider, Pattern tagPattern) { + super(provider, tagPattern); + } +} diff --git a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java b/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java deleted file mode 100644 index 418e4aa51d..0000000000 --- a/src/main/java/redis/clients/jedis/JedisSlotBasedConnectionHandler.java +++ /dev/null @@ -1,112 +0,0 @@ -package redis.clients.jedis; - -import java.util.List; -import java.util.Set; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - -import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; - -public class JedisSlotBasedConnectionHandler extends JedisClusterConnectionHandler { - - public JedisSlotBasedConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, int timeout) { - this(nodes, poolConfig, timeout, timeout); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - final GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout) { - this(nodes, poolConfig, connectionTimeout, soTimeout, null); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password) { - super(nodes, poolConfig, connectionTimeout, soTimeout, password); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - String password, String clientName) { - super(nodes, poolConfig, connectionTimeout, soTimeout, password, clientName); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, String user, - String password, String clientName) { - super(nodes, poolConfig, connectionTimeout, soTimeout, user, password, clientName); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, int connectionTimeout, int soTimeout, - int infiniteSoTimeout, String user, String password, String clientName) { - super(nodes, poolConfig, connectionTimeout, soTimeout, infiniteSoTimeout, user, password, - clientName); - } - - public JedisSlotBasedConnectionHandler(Set nodes, - GenericObjectPoolConfig poolConfig, JedisClientConfig clientConfig) { - super(nodes, poolConfig, clientConfig); - } - - @Override - public Jedis getConnection() { - // In antirez's redis-rb-cluster implementation, getRandomConnection always - // return valid connection (able to ping-pong) or exception if all - // connections are invalid - - List pools = cache.getShuffledNodesPool(); - - JedisException suppressed = null; - for (JedisPool pool : pools) { - Jedis jedis = null; - try { - jedis = pool.getResource(); - - if (jedis == null) { - continue; - } - - if (jedis.ping().equalsIgnoreCase("pong")) { - return jedis; - } - - jedis.close(); - } catch (JedisException ex) { - if (suppressed == null) { // remembering first suppressed exception - suppressed = ex; - } - if (jedis != null) { - jedis.close(); - } - } - } - - JedisNoReachableClusterNodeException noReachableNode = new JedisNoReachableClusterNodeException("No reachable node in cluster."); - if (suppressed != null) { - noReachableNode.addSuppressed(suppressed); - } - throw noReachableNode; - } - - @Override - public Jedis getConnectionFromSlot(int slot) { - JedisPool connectionPool = cache.getSlotPool(slot); - if (connectionPool != null) { - // It can't guaranteed to get valid connection because of node assignment - return connectionPool.getResource(); - } else { - // It's abnormal situation for cluster mode that we have just nothing for slot. - // Try to rediscover state - renewSlotCache(); - connectionPool = cache.getSlotPool(slot); - if (connectionPool != null) { - return connectionPool.getResource(); - } else { - // no choice, fallback to new connection to random node - return getConnection(); - } - } - } -} diff --git a/src/main/java/redis/clients/jedis/JedisSocketFactory.java b/src/main/java/redis/clients/jedis/JedisSocketFactory.java index 297519bf17..7fc3ebc5f3 100644 --- a/src/main/java/redis/clients/jedis/JedisSocketFactory.java +++ b/src/main/java/redis/clients/jedis/JedisSocketFactory.java @@ -15,38 +15,5 @@ */ public interface JedisSocketFactory { - /** - * @return Socket - * @throws JedisConnectionException - */ Socket createSocket() throws JedisConnectionException; - - void updateHostAndPort(HostAndPort hostAndPort); - - @Deprecated - String getDescription(); - - @Deprecated - String getHost(); - - @Deprecated - void setHost(String host); - - @Deprecated - int getPort(); - - @Deprecated - void setPort(int port); - - @Deprecated - int getConnectionTimeout(); - - @Deprecated - void setConnectionTimeout(int connectionTimeout); - - @Deprecated - int getSoTimeout(); - - @Deprecated - void setSoTimeout(int soTimeout); } diff --git a/src/main/java/redis/clients/jedis/ListPosition.java b/src/main/java/redis/clients/jedis/ListPosition.java deleted file mode 100644 index e82deabf09..0000000000 --- a/src/main/java/redis/clients/jedis/ListPosition.java +++ /dev/null @@ -1,12 +0,0 @@ -package redis.clients.jedis; - -import redis.clients.jedis.util.SafeEncoder; - -public enum ListPosition { - BEFORE, AFTER; - public final byte[] raw; - - private ListPosition() { - raw = SafeEncoder.encode(name()); - } -} diff --git a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java b/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java deleted file mode 100644 index bff7095ce4..0000000000 --- a/src/main/java/redis/clients/jedis/MultiKeyPipelineBase.java +++ /dev/null @@ -1,1022 +0,0 @@ -package redis.clients.jedis; - -import redis.clients.jedis.args.*; -import redis.clients.jedis.commands.*; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.*; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -public abstract class MultiKeyPipelineBase extends PipelineBase implements - MultiKeyBinaryRedisPipeline, MultiKeyCommandsPipeline, ClusterPipeline, - BinaryScriptingCommandsPipeline, ScriptingCommandsPipeline, BasicRedisPipeline { - - protected Client client = null; - - @Override - public Response copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) { - client.copy(srcKey, dstKey, db, replace); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response copy(byte[] srcKey, byte[] dstKey, boolean replace) { - client.copy(srcKey, dstKey, replace); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response copy(String srcKey, String dstKey, int db, boolean replace) { - client.copy(srcKey, dstKey, db, replace); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response copy(String srcKey, String dstKey, boolean replace) { - client.copy(srcKey, dstKey, replace); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response lmove(String srcKey, String dstKey, ListDirection from, - ListDirection to) { - client.lmove(srcKey, dstKey, from, to); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response lmove(byte[] srcKey, byte[] dstKey, ListDirection from, - ListDirection to) { - client.lmove(srcKey, dstKey, from, to); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, - double timeout) { - client.blmove(srcKey, dstKey, from, to, timeout); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, - double timeout) { - client.blmove(srcKey, dstKey, from, to, timeout); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> blpop(String... args) { - client.blpop(args); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> blpop(byte[]... args) { - client.blpop(args); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> blpop(int timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); - } - - /** - * @deprecated Use {@link #blpop(double, java.lang.String...)} or - * {@link #blpop(int, java.lang.String...)}. - */ - @Deprecated - public Response> blpopMap(int timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_MAP); - } - - @Deprecated - public Response> blpop(int timeout, byte[]... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response blpop(double timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.KEYED_LIST_ELEMENT); - } - - @Override - public Response> blpop(double timeout, byte[]... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> brpop(String... args) { - client.brpop(args); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> brpop(byte[]... args) { - client.brpop(args); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> brpop(int timeout, String... keys) { - client.brpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); - } - - /** - * @deprecated Use {@link #brpop(double, java.lang.String...)} or - * {@link #brpop(int, java.lang.String...)}. - */ - @Deprecated - public Response> brpopMap(int timeout, String... keys) { - client.blpop(timeout, keys); - return getResponse(BuilderFactory.STRING_MAP); - } - - @Deprecated - public Response> brpop(int timeout, byte[]... keys) { - client.brpop(timeout, keys); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response brpop(double timeout, String... keys) { - client.brpop(timeout, keys); - return getResponse(BuilderFactory.KEYED_LIST_ELEMENT); - } - - @Override - public Response> brpop(double timeout, byte[]... keys) { - client.brpop(timeout, keys); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response bzpopmax(double timeout, String... keys) { - client.bzpopmax(timeout, keys); - return getResponse(BuilderFactory.KEYED_ZSET_ELEMENT); - } - - @Override - public Response> bzpopmax(double timeout, byte[]... keys) { - client.bzpopmax(timeout, keys); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response bzpopmin(double timeout, String... keys) { - client.bzpopmin(timeout, keys); - return getResponse(BuilderFactory.KEYED_ZSET_ELEMENT); - } - - @Override - public Response> bzpopmin(double timeout, byte[]... keys) { - client.bzpopmin(timeout, keys); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response del(String... keys) { - client.del(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response del(byte[]... keys) { - client.del(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response unlink(String... keys) { - client.unlink(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response unlink(byte[]... keys) { - client.unlink(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response exists(String... keys) { - client.exists(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response exists(byte[]... keys) { - client.exists(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> keys(String pattern) { - getClient(pattern).keys(pattern); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response> keys(byte[] pattern) { - getClient(pattern).keys(pattern); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> mget(String... keys) { - client.mget(keys); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> mget(byte[]... keys) { - client.mget(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response mset(String... keysvalues) { - client.mset(keysvalues); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response mset(byte[]... keysvalues) { - client.mset(keysvalues); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response msetnx(String... keysvalues) { - client.msetnx(keysvalues); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response msetnx(byte[]... keysvalues) { - client.msetnx(keysvalues); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response rename(String oldkey, String newkey) { - client.rename(oldkey, newkey); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response rename(byte[] oldkey, byte[] newkey) { - client.rename(oldkey, newkey); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response renamenx(String oldkey, String newkey) { - client.renamenx(oldkey, newkey); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response renamenx(byte[] oldkey, byte[] newkey) { - client.renamenx(oldkey, newkey); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response rpoplpush(String srckey, String dstkey) { - client.rpoplpush(srckey, dstkey); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response rpoplpush(byte[] srckey, byte[] dstkey) { - client.rpoplpush(srckey, dstkey); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> sdiff(String... keys) { - client.sdiff(keys); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response> sdiff(byte[]... keys) { - client.sdiff(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response sdiffstore(String dstkey, String... keys) { - client.sdiffstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sdiffstore(byte[] dstkey, byte[]... keys) { - client.sdiffstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> sinter(String... keys) { - client.sinter(keys); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response> sinter(byte[]... keys) { - client.sinter(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response sinterstore(String dstkey, String... keys) { - client.sinterstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sinterstore(byte[] dstkey, byte[]... keys) { - client.sinterstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response smove(String srckey, String dstkey, String member) { - client.smove(srckey, dstkey, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response smove(byte[] srckey, byte[] dstkey, byte[] member) { - client.smove(srckey, dstkey, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sort(String key, SortingParams sortingParameters, String dstkey) { - client.sort(key, sortingParameters, dstkey); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey) { - client.sort(key, sortingParameters, dstkey); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sort(String key, String dstkey) { - client.sort(key, dstkey); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sort(byte[] key, byte[] dstkey) { - client.sort(key, dstkey); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> sunion(String... keys) { - client.sunion(keys); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response> sunion(byte[]... keys) { - client.sunion(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response sunionstore(String dstkey, String... keys) { - client.sunionstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sunionstore(byte[] dstkey, byte[]... keys) { - client.sunionstore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response unwatch() { - client.unwatch(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> zdiff(byte[]... keys) { - client.zdiff(keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zdiffWithScores(byte[]... keys) { - client.zdiffWithScores(keys); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zdiff(String... keys) { - client.zdiff(keys); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zdiffWithScores(String... keys) { - client.zdiffWithScores(keys); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zdiffStore(final byte[] dstkey, final byte[]... keys) { - client.zdiffStore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zdiffStore(final String dstkey, final String... keys) { - client.zdiffStore(dstkey, keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> zinter(final ZParams params, final byte[]... keys) { - client.zinter(params, keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zinterWithScores(final ZParams params, final byte[]... keys) { - client.zinterWithScores(params, keys); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zinter(final ZParams params, final String... keys) { - client.zinter(params, keys); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zinterWithScores(final ZParams params, final String... keys) { - client.zinterWithScores(params, keys); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zinterstore(String dstkey, String... sets) { - client.zinterstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zinterstore(byte[] dstkey, byte[]... sets) { - client.zinterstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zinterstore(String dstkey, ZParams params, String... sets) { - client.zinterstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zinterstore(byte[] dstkey, ZParams params, byte[]... sets) { - client.zinterstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> zunion(ZParams params, byte[]... keys) { - client.zunion(params, keys); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zunionWithScores(ZParams params, byte[]... keys) { - client.zunionWithScores(params, keys); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zunion(ZParams params, String... keys) { - client.zunion(params, keys); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zunionWithScores(ZParams params, String... keys) { - client.zunionWithScores(params, keys); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zunionstore(String dstkey, String... sets) { - client.zunionstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zunionstore(byte[] dstkey, byte[]... sets) { - client.zunionstore(dstkey, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zunionstore(String dstkey, ZParams params, String... sets) { - client.zunionstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zunionstore(byte[] dstkey, ZParams params, byte[]... sets) { - client.zunionstore(dstkey, params, sets); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bgrewriteaof() { - client.bgrewriteaof(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response bgsave() { - client.bgsave(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> configGet(String pattern) { - client.configGet(pattern); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response configSet(String parameter, String value) { - client.configSet(parameter, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response brpoplpush(String source, String destination, int timeout) { - client.brpoplpush(source, destination, timeout); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response brpoplpush(byte[] source, byte[] destination, int timeout) { - client.brpoplpush(source, destination, timeout); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response configResetStat() { - client.configResetStat(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response save() { - client.save(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response lastsave() { - client.lastsave(); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response publish(String channel, String message) { - client.publish(channel, message); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response publish(byte[] channel, byte[] message) { - client.publish(channel, message); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response randomKey() { - client.randomKey(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response randomKeyBinary() { - client.randomKey(); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response flushDB() { - client.flushDB(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response flushAll() { - client.flushAll(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response flushDB(FlushMode flushMode) { - client.flushDB(flushMode); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response flushAll(FlushMode flushMode) { - client.flushAll(flushMode); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response info() { - client.info(); - return getResponse(BuilderFactory.STRING); - } - - public Response info(final String section) { - client.info(section); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response dbSize() { - client.dbSize(); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response shutdown() { - client.shutdown(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response ping() { - client.ping(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response select(int index) { - client.select(index); - Response response = getResponse(BuilderFactory.STRING); - client.setDb(index); - - return response; - } - - @Override - public Response swapDB(int index1, int index2) { - client.swapDB(index1, index2); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { - client.bitop(op, destKey, srcKeys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bitop(BitOP op, String destKey, String... srcKeys) { - client.bitop(op, destKey, srcKeys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response clusterNodes() { - client.clusterNodes(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response clusterMeet(final String ip, final int port) { - client.clusterMeet(ip, port); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response clusterAddSlots(final int... slots) { - client.clusterAddSlots(slots); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response clusterDelSlots(final int... slots) { - client.clusterDelSlots(slots); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response clusterInfo() { - client.clusterInfo(); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> clusterGetKeysInSlot(final int slot, final int count) { - client.clusterGetKeysInSlot(slot, count); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response clusterSetSlotNode(final int slot, final String nodeId) { - client.clusterSetSlotNode(slot, nodeId); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response clusterSetSlotMigrating(final int slot, final String nodeId) { - client.clusterSetSlotMigrating(slot, nodeId); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response clusterSetSlotImporting(final int slot, final String nodeId) { - client.clusterSetSlotImporting(slot, nodeId); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response eval(String script) { - return this.eval(script, 0, new String[0]); - } - - @Override - public Response eval(String script, List keys, List args) { - String[] argv = Jedis.getParams(keys, args); - return this.eval(script, keys.size(), argv); - } - - @Override - public Response eval(String script, int keyCount, String... params) { - getClient(script).eval(script, keyCount, params); - return getResponse(BuilderFactory.ENCODED_OBJECT); - } - - @Override - public Response evalsha(String sha1) { - return this.evalsha(sha1, 0, new String[0]); - } - - @Override - public Response evalsha(String sha1, List keys, List args) { - String[] argv = Jedis.getParams(keys, args); - return this.evalsha(sha1, keys.size(), argv); - } - - @Override - public Response evalsha(String sha1, int keyCount, String... params) { - getClient(sha1).evalsha(sha1, keyCount, params); - return getResponse(BuilderFactory.ENCODED_OBJECT); - } - - @Override - public Response eval(byte[] script) { - return this.eval(script, 0); - } - - @Override - @Deprecated - public Response eval(byte[] script, byte[] keyCount, byte[]... params) { - getClient(script).eval(script, keyCount, params); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - @Override - public Response eval(byte[] script, List keys, List args) { - byte[][] argv = BinaryJedis.getParamsWithBinary(keys, args); - return this.eval(script, keys.size(), argv); - } - - @Override - public Response eval(byte[] script, int keyCount, byte[]... params) { - getClient(script).eval(script, keyCount, params); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - @Override - public Response evalsha(byte[] sha1) { - return this.evalsha(sha1, 0); - } - - @Override - public Response evalsha(byte[] sha1, List keys, List args) { - byte[][] argv = BinaryJedis.getParamsWithBinary(keys, args); - return this.evalsha(sha1, keys.size(), argv); - } - - @Override - public Response evalsha(byte[] sha1, int keyCount, byte[]... params) { - getClient(sha1).evalsha(sha1, keyCount, params); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - @Override - public Response pfcount(String... keys) { - client.pfcount(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pfcount(final byte[]... keys) { - client.pfcount(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pfmerge(byte[] destkey, byte[]... sourcekeys) { - client.pfmerge(destkey, sourcekeys); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response pfmerge(String destkey, String... sourcekeys) { - client.pfmerge(destkey, sourcekeys); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> time() { - client.time(); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response touch(String... keys) { - client.touch(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response touch(byte[]... keys) { - client.touch(keys); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response moduleUnload(String name) { - client.moduleUnload(name); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> moduleList() { - client.moduleList(); - return getResponse(BuilderFactory.MODULE_LIST); - } - - @Override - public Response moduleLoad(String path) { - client.moduleLoad(path); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response migrate(final String host, final int port, final int destinationDB, - final int timeout, final MigrateParams params, final String... keys) { - client.migrate(host, port, destinationDB, timeout, params, keys); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response migrate(final String host, final int port, final int destinationDB, - final int timeout, final MigrateParams params, final byte[]... keys) { - client.migrate(host, port, destinationDB, timeout, params, keys); - return getResponse(BuilderFactory.STRING); - } - - public Response sendCommand(final ProtocolCommand cmd, final String... args) { - client.sendCommand(cmd, args); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - public Response sendCommand(final ProtocolCommand cmd, final byte[]... args) { - client.sendCommand(cmd, args); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - @Override - public Response georadiusStore(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - client.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response georadiusStore(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - client.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response georadiusByMemberStore(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - client.georadiusByMemberStore(key, member, radius, unit, param, storeParam); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response georadiusByMemberStore(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param, - final GeoRadiusStoreParam storeParam) { - client.georadiusByMemberStore(key, member, radius, unit, param, storeParam); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> xread(int count, long block, Map streams) { - client.xread(count, block, streams); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xread(XReadParams xReadParams, Map.Entry... streams) { - client.xread(xReadParams, streams); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xreadGroup(byte[] groupname, byte[] consumer, int count, long block, - boolean noAck, Map streams) { - client.xreadGroup(groupname, consumer, count, block, noAck, streams); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xreadGroup(final byte[] groupname, final byte[] consumer, - final XReadGroupParams xReadGroupParams, final Map.Entry... streams) { - client.xreadGroup(groupname, consumer, xReadGroupParams, streams); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response>>> xread(int count, long block, - Map.Entry... streams) { - client.xread(count, block, streams); - return getResponse(BuilderFactory.STREAM_READ_RESPONSE); - } - - @Override - public Response>>> xread(final XReadParams xReadParams, - final Map streams) { - client.xread(xReadParams, streams); - return getResponse(BuilderFactory.STREAM_READ_RESPONSE); - } - - @Override - public Response>>> xreadGroup(String groupname, - String consumer, int count, long block, boolean noAck, - Map.Entry... streams) { - client.xreadGroup(groupname, consumer, count, block, noAck, streams); - return getResponse(BuilderFactory.STREAM_READ_RESPONSE); - } - - @Override - public Response>>> xreadGroup(final String groupname, - final String consumer, final XReadGroupParams xReadGroupParams, - final Map streams) { - client.xreadGroup(groupname, consumer, xReadGroupParams, streams); - return getResponse(BuilderFactory.STREAM_READ_RESPONSE); - } - - @Override - public Response strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params) { - client.strAlgoLCSKeys(keyA, keyB, params); - return getResponse(BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); - } - - @Override - public Response strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params) { - client.strAlgoLCSKeys(keyA, keyB, params); - return getResponse(BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); - } -} diff --git a/src/main/java/redis/clients/jedis/MultiNodePipelineBase.java b/src/main/java/redis/clients/jedis/MultiNodePipelineBase.java new file mode 100644 index 0000000000..8992a14f89 --- /dev/null +++ b/src/main/java/redis/clients/jedis/MultiNodePipelineBase.java @@ -0,0 +1,3008 @@ +package redis.clients.jedis; + +import java.io.Closeable; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Queue; +import java.util.Set; + +import org.json.JSONArray; + +import redis.clients.jedis.args.*; +import redis.clients.jedis.commands.PipelineBinaryCommands; +import redis.clients.jedis.commands.PipelineCommands; +import redis.clients.jedis.commands.RedisModulePipelineCommands; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; +import redis.clients.jedis.search.*; + +public abstract class MultiNodePipelineBase implements PipelineCommands, PipelineBinaryCommands, + RedisModulePipelineCommands, Closeable { + + private final Map>> pipelinedResponses; + private final Map connections; + private volatile boolean synced; + + private final CommandObjects commandObjects; + + public MultiNodePipelineBase(CommandObjects commandObjects) { + pipelinedResponses = new LinkedHashMap<>(); + connections = new LinkedHashMap<>(); + synced = false; + this.commandObjects = commandObjects; + } + + protected abstract HostAndPort getNodeKey(CommandArguments args); + + protected abstract Connection getConnection(HostAndPort nodeKey); + + protected final Response appendCommand(CommandObject commandObject) { + HostAndPort nodeKey = getNodeKey(commandObject.getArguments()); + + Queue> queue; + Connection connection; + if (pipelinedResponses.containsKey(nodeKey)) { + queue = pipelinedResponses.get(nodeKey); + connection = connections.get(nodeKey); + } else { + queue = new LinkedList<>(); + connection = getConnection(nodeKey); + pipelinedResponses.put(nodeKey, queue); + connections.put(nodeKey, connection); + } + + connection.sendCommand(commandObject.getArguments()); + Response response = new Response<>(commandObject.getBuilder()); + queue.add(response); + return response; + } + + @Override + public final void close() { + sync(); + for (Connection connection : connections.values()) { + connection.close(); + } + } + + public final void sync() { + if (synced) { + return; + } + for (Map.Entry>> entry : pipelinedResponses.entrySet()) { + HostAndPort nodeKey = entry.getKey(); + Queue> queue = entry.getValue(); + List unformatted = connections.get(nodeKey).getMany(queue.size()); + for (Object o : unformatted) { + queue.poll().set(o); + } + } + synced = true; + } + + @Override + public Response exists(String key) { + return appendCommand(commandObjects.exists(key)); + } + + @Override + public Response exists(String... keys) { + return appendCommand(commandObjects.exists(keys)); + } + + @Override + public Response persist(String key) { + return appendCommand(commandObjects.persist(key)); + } + + @Override + public Response type(String key) { + return appendCommand(commandObjects.type(key)); + } + + @Override + public Response dump(String key) { + return appendCommand(commandObjects.dump(key)); + } + + @Override + public Response restore(String key, long ttl, byte[] serializedValue) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public Response restore(String key, long ttl, byte[] serializedValue, RestoreParams params) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public Response expire(String key, long seconds) { + return appendCommand(commandObjects.expire(key, seconds)); + } + + @Override + public Response pexpire(String key, long milliseconds) { + return appendCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public Response expireAt(String key, long unixTime) { + return appendCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public Response pexpireAt(String key, long millisecondsTimestamp) { + return appendCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public Response ttl(String key) { + return appendCommand(commandObjects.ttl(key)); + } + + @Override + public Response pttl(String key) { + return appendCommand(commandObjects.pttl(key)); + } + + @Override + public Response touch(String key) { + return appendCommand(commandObjects.touch(key)); + } + + @Override + public Response touch(String... keys) { + return appendCommand(commandObjects.touch(keys)); + } + + @Override + public Response> sort(String key) { + return appendCommand(commandObjects.sort(key)); + } + + @Override + public Response sort(String key, String dstKey) { + return appendCommand(commandObjects.sort(key, dstKey)); + } + + @Override + public Response> sort(String key, SortingParams sortingParameters) { + return appendCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public Response sort(String key, SortingParams sortingParameters, String dstKey) { + return appendCommand(commandObjects.sort(key, sortingParameters, dstKey)); + } + + @Override + public Response del(String key) { + return appendCommand(commandObjects.del(key)); + } + + @Override + public Response del(String... keys) { + return appendCommand(commandObjects.del(keys)); + } + + @Override + public Response unlink(String key) { + return appendCommand(commandObjects.unlink(key)); + } + + @Override + public Response unlink(String... keys) { + return appendCommand(commandObjects.unlink(keys)); + } + + @Override + public Response copy(String srcKey, String dstKey, boolean replace) { + return appendCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public Response rename(String oldKey, String newKey) { + return appendCommand(commandObjects.rename(oldKey, newKey)); + } + + @Override + public Response renamenx(String oldKey, String newKey) { + return appendCommand(commandObjects.renamenx(oldKey, newKey)); + } + + @Override + public Response memoryUsage(String key) { + return appendCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Response memoryUsage(String key, int samples) { + return appendCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Response objectRefcount(String key) { + return appendCommand(commandObjects.objectRefcount(key)); + } + + @Override + public Response objectEncoding(String key) { + return appendCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Response objectIdletime(String key) { + return appendCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Response objectFreq(String key) { + return appendCommand(commandObjects.objectFreq(key)); + } + + @Override + public Response migrate(String host, int port, String key, int timeout) { + return appendCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public Response migrate(String host, int port, int timeout, MigrateParams params, String... keys) { + return appendCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public Response> keys(String pattern) { + return appendCommand(commandObjects.keys(pattern)); + } + + @Override + public Response> scan(String cursor) { + return appendCommand(commandObjects.scan(cursor)); + } + + @Override + public Response> scan(String cursor, ScanParams params) { + return appendCommand(commandObjects.scan(cursor, params)); + } + + @Override + public Response> scan(String cursor, ScanParams params, String type) { + return appendCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Response randomKey() { + return appendCommand(commandObjects.randomKey()); + } + + @Override + public Response get(String key) { + return appendCommand(commandObjects.get(key)); + } + + @Override + public Response getDel(String key) { + return appendCommand(commandObjects.getDel(key)); + } + + @Override + public Response getEx(String key, GetExParams params) { + return appendCommand(commandObjects.getEx(key, params)); + } + + @Override + public Response setbit(String key, long offset, boolean value) { + return appendCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public Response getbit(String key, long offset) { + return appendCommand(commandObjects.getbit(key, offset)); + } + + @Override + public Response setrange(String key, long offset, String value) { + return appendCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public Response getrange(String key, long startOffset, long endOffset) { + return appendCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public Response getSet(String key, String value) { + return appendCommand(commandObjects.getSet(key, value)); + } + + @Override + public Response setnx(String key, String value) { + return appendCommand(commandObjects.setnx(key, value)); + } + + @Override + public Response setex(String key, long seconds, String value) { + return appendCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public Response psetex(String key, long milliseconds, String value) { + return appendCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public Response> mget(String... keys) { + return appendCommand(commandObjects.mget(keys)); + } + + @Override + public Response mset(String... keysvalues) { + return appendCommand(commandObjects.mset(keysvalues)); + } + + @Override + public Response msetnx(String... keysvalues) { + return appendCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public Response incr(String key) { + return appendCommand(commandObjects.incr(key)); + } + + @Override + public Response incrBy(String key, long increment) { + return appendCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public Response incrByFloat(String key, double increment) { + return appendCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public Response decr(String key) { + return appendCommand(commandObjects.decr(key)); + } + + @Override + public Response decrBy(String key, long decrement) { + return appendCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public Response append(String key, String value) { + return appendCommand(commandObjects.append(key, value)); + } + + @Override + public Response substr(String key, int start, int end) { + return appendCommand(commandObjects.substr(key, start, end)); + } + + @Override + public Response strlen(String key) { + return appendCommand(commandObjects.strlen(key)); + } + + @Override + public Response bitcount(String key) { + return appendCommand(commandObjects.bitcount(key)); + } + + @Override + public Response bitcount(String key, long start, long end) { + return appendCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public Response bitpos(String key, boolean value) { + return appendCommand(commandObjects.bitpos(key, value)); + } + + @Override + public Response bitpos(String key, boolean value, BitPosParams params) { + return appendCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public Response> bitfield(String key, String... arguments) { + return appendCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public Response> bitfieldReadonly(String key, String... arguments) { + return appendCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public Response bitop(BitOP op, String destKey, String... srcKeys) { + return appendCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public Response strAlgoLCSKeys(String keyA, String keyB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); + } + + @Override + public Response set(String key, String value) { + return appendCommand(commandObjects.set(key, value)); + } + + @Override + public Response set(String key, String value, SetParams params) { + return appendCommand(commandObjects.set(key, value, params)); + } + + @Override + public Response rpush(String key, String... string) { + return appendCommand(commandObjects.rpush(key, string)); + } + + @Override + public Response lpush(String key, String... string) { + return appendCommand(commandObjects.lpush(key, string)); + } + + @Override + public Response llen(String key) { + return appendCommand(commandObjects.llen(key)); + } + + @Override + public Response> lrange(String key, long start, long stop) { + return appendCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public Response ltrim(String key, long start, long stop) { + return appendCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public Response lindex(String key, long index) { + return appendCommand(commandObjects.lindex(key, index)); + } + + @Override + public Response lset(String key, long index, String value) { + return appendCommand(commandObjects.lset(key, index, value)); + } + + @Override + public Response lrem(String key, long count, String value) { + return appendCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public Response lpop(String key) { + return appendCommand(commandObjects.lpop(key)); + } + + @Override + public Response> lpop(String key, int count) { + return appendCommand(commandObjects.lpop(key, count)); + } + + @Override + public Response lpos(String key, String element) { + return appendCommand(commandObjects.lpos(key, element)); + } + + @Override + public Response lpos(String key, String element, LPosParams params) { + return appendCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public Response> lpos(String key, String element, LPosParams params, long count) { + return appendCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Response rpop(String key) { + return appendCommand(commandObjects.rpop(key)); + } + + @Override + public Response> rpop(String key, int count) { + return appendCommand(commandObjects.rpop(key, count)); + } + + @Override + public Response linsert(String key, ListPosition where, String pivot, String value) { + return appendCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public Response lpushx(String key, String... string) { + return appendCommand(commandObjects.lpushx(key, string)); + } + + @Override + public Response rpushx(String key, String... string) { + return appendCommand(commandObjects.rpushx(key, string)); + } + + @Override + public Response> blpop(int timeout, String key) { + return appendCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public Response blpop(double timeout, String key) { + return appendCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public Response> brpop(int timeout, String key) { + return appendCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public Response brpop(double timeout, String key) { + return appendCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public Response> blpop(int timeout, String... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response blpop(double timeout, String... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> brpop(int timeout, String... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response brpop(double timeout, String... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response rpoplpush(String srcKey, String dstKey) { + return appendCommand(commandObjects.rpoplpush(srcKey, dstKey)); + } + + @Override + public Response brpoplpush(String source, String destination, int timeout) { + return appendCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public Response lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { + return appendCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public Response blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout) { + return appendCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + @Override + public Response hset(String key, String field, String value) { + return appendCommand(commandObjects.hset(key, field, value)); + } + + @Override + public Response hset(String key, Map hash) { + return appendCommand(commandObjects.hset(key, hash)); + } + + @Override + public Response hget(String key, String field) { + return appendCommand(commandObjects.hget(key, field)); + } + + @Override + public Response hsetnx(String key, String field, String value) { + return appendCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public Response hmset(String key, Map hash) { + return appendCommand(commandObjects.hmset(key, hash)); + } + + @Override + public Response> hmget(String key, String... fields) { + return appendCommand(commandObjects.hmget(key, fields)); + } + + @Override + public Response hincrBy(String key, String field, long value) { + return appendCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public Response hincrByFloat(String key, String field, double value) { + return appendCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public Response hexists(String key, String field) { + return appendCommand(commandObjects.hexists(key, field)); + } + + @Override + public Response hdel(String key, String... field) { + return appendCommand(commandObjects.hdel(key, field)); + } + + @Override + public Response hlen(String key) { + return appendCommand(commandObjects.hlen(key)); + } + + @Override + public Response> hkeys(String key) { + return appendCommand(commandObjects.hkeys(key)); + } + + @Override + public Response> hvals(String key) { + return appendCommand(commandObjects.hvals(key)); + } + + @Override + public Response> hgetAll(String key) { + return appendCommand(commandObjects.hgetAll(key)); + } + + @Override + public Response hrandfield(String key) { + return appendCommand(commandObjects.hrandfield(key)); + } + + @Override + public Response> hrandfield(String key, long count) { + return appendCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Response> hrandfieldWithValues(String key, long count) { + return appendCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public Response>> hscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public Response hstrlen(String key, String field) { + return appendCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public Response sadd(String key, String... member) { + return appendCommand(commandObjects.sadd(key, member)); + } + + @Override + public Response> smembers(String key) { + return appendCommand(commandObjects.smembers(key)); + } + + @Override + public Response srem(String key, String... member) { + return appendCommand(commandObjects.srem(key, member)); + } + + @Override + public Response spop(String key) { + return appendCommand(commandObjects.spop(key)); + } + + @Override + public Response> spop(String key, long count) { + return appendCommand(commandObjects.spop(key, count)); + } + + @Override + public Response scard(String key) { + return appendCommand(commandObjects.scard(key)); + } + + @Override + public Response sismember(String key, String member) { + return appendCommand(commandObjects.sismember(key, member)); + } + + @Override + public Response> smismember(String key, String... members) { + return appendCommand(commandObjects.smismember(key, members)); + } + + @Override + public Response srandmember(String key) { + return appendCommand(commandObjects.srandmember(key)); + } + + @Override + public Response> srandmember(String key, int count) { + return appendCommand(commandObjects.srandmember(key, count)); + } + + @Override + public Response> sscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Response> sdiff(String... keys) { + return appendCommand(commandObjects.sdiff(keys)); + } + + @Override + public Response sdiffstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sdiffstore(dstKey, keys)); + } + + @Override + public Response> sinter(String... keys) { + return appendCommand(commandObjects.sinter(keys)); + } + + @Override + public Response sinterstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sinterstore(dstKey, keys)); + } + + @Override + public Response> sunion(String... keys) { + return appendCommand(commandObjects.sunion(keys)); + } + + @Override + public Response sunionstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sunionstore(dstKey, keys)); + } + + @Override + public Response smove(String srcKey, String dstKey, String member) { + return appendCommand(commandObjects.smove(srcKey, dstKey, member)); + } + + @Override + public Response zadd(String key, double score, String member) { + return appendCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public Response zadd(String key, double score, String member, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public Response zadd(String key, Map scoreMembers) { + return appendCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public Response zadd(String key, Map scoreMembers, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Response zaddIncr(String key, double score, String member, ZAddParams params) { + return appendCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Response zrem(String key, String... members) { + return appendCommand(commandObjects.zrem(key, members)); + } + + @Override + public Response zincrby(String key, double increment, String member) { + return appendCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Response zincrby(String key, double increment, String member, ZIncrByParams params) { + return appendCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Response zrank(String key, String member) { + return appendCommand(commandObjects.zrank(key, member)); + } + + @Override + public Response zrevrank(String key, String member) { + return appendCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public Response> zrange(String key, long start, long stop) { + return appendCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public Response> zrevrange(String key, long start, long stop) { + return appendCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public Response> zrangeWithScores(String key, long start, long stop) { + return appendCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public Response> zrevrangeWithScores(String key, long start, long stop) { + return appendCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public Response zrandmember(String key) { + return appendCommand(commandObjects.zrandmember(key)); + } + + @Override + public Response> zrandmember(String key, long count) { + return appendCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public Response> zrandmemberWithScores(String key, long count) { + return appendCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public Response zcard(String key) { + return appendCommand(commandObjects.zcard(key)); + } + + @Override + public Response zscore(String key, String member) { + return appendCommand(commandObjects.zscore(key, member)); + } + + @Override + public Response> zmscore(String key, String... members) { + return appendCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Response zpopmax(String key) { + return appendCommand(commandObjects.zpopmax(key)); + } + + @Override + public Response> zpopmax(String key, int count) { + return appendCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Response zpopmin(String key) { + return appendCommand(commandObjects.zpopmin(key)); + } + + @Override + public Response> zpopmin(String key, int count) { + return appendCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public Response zcount(String key, double min, double max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response zcount(String key, String min, String max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response> zrangeByScore(String key, double min, double max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrevrangeByScore(String key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + + } + + @Override + public Response> zrangeByScore(String key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public Response> zrangeByScore(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, double min, double max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByRank(String key, long start, long stop) { + return appendCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public Response zremrangeByScore(String key, double min, double max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zremrangeByScore(String key, String min, String max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zlexcount(String key, String min, String max) { + return appendCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public Response> zrangeByLex(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public Response> zrangeByLex(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByLex(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public Response> zrevrangeByLex(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByLex(String key, String min, String max) { + return appendCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public Response> zscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public Response bzpopmax(double timeout, String... keys) { + return appendCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public Response bzpopmin(double timeout, String... keys) { + return appendCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Response> zdiff(String... keys) { + return appendCommand(commandObjects.zdiff(keys)); + } + + @Override + public Response> zdiffWithScores(String... keys) { + return appendCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public Response zdiffStore(String dstKey, String... keys) { + return appendCommand(commandObjects.zdiffStore(dstKey, keys)); + } + + @Override + public Response zinterstore(String dstKey, String... sets) { + return appendCommand(commandObjects.zinterstore(dstKey, sets)); + } + + @Override + public Response zinterstore(String dstKey, ZParams params, String... sets) { + return appendCommand(commandObjects.zinterstore(dstKey, params, sets)); + } + + @Override + public Response> zinter(ZParams params, String... keys) { + return appendCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Response> zinterWithScores(ZParams params, String... keys) { + return appendCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Response> zunion(ZParams params, String... keys) { + return appendCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Response> zunionWithScores(ZParams params, String... keys) { + return appendCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public Response zunionstore(String dstKey, String... sets) { + return appendCommand(commandObjects.zunionstore(dstKey, sets)); + } + + @Override + public Response zunionstore(String dstKey, ZParams params, String... sets) { + return appendCommand(commandObjects.zunionstore(dstKey, params, sets)); + } + + @Override + public Response geoadd(String key, double longitude, double latitude, String member) { + return appendCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public Response geoadd(String key, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public Response geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Response geodist(String key, String member1, String member2) { + return appendCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Response geodist(String key, String member1, String member2, GeoUnit unit) { + return appendCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public Response> geohash(String key, String... members) { + return appendCommand(commandObjects.geohash(key, members)); + } + + @Override + public Response> geopos(String key, String... members) { + return appendCommand(commandObjects.geopos(key, members)); + } + + @Override + public Response> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusByMember(String key, String member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMember(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public Response georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public Response georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public Response pfadd(String key, String... elements) { + return appendCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public Response pfmerge(String destkey, String... sourcekeys) { + return appendCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public Response pfcount(String key) { + return appendCommand(commandObjects.pfcount(key)); + } + + @Override + public Response pfcount(String... keys) { + return appendCommand(commandObjects.pfcount(keys)); + } + + @Override + public Response xadd(String key, StreamEntryID id, Map hash) { + return appendCommand(commandObjects.xadd(key, id, hash)); + } + + @Override + public Response xadd_v2(String key, XAddParams params, Map hash) { + return appendCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public Response xlen(String key) { + return appendCommand(commandObjects.xlen(key)); + } + + @Override + public Response> xrange(String key, StreamEntryID start, StreamEntryID end) { + return appendCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public Response> xrange(String key, StreamEntryID start, StreamEntryID end, int count) { + return appendCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start) { + return appendCommand(commandObjects.xrevrange(key, start, end)); + } + + @Override + public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { + return appendCommand(commandObjects.xrevrange(key, start, end, count)); + } + + @Override + public Response xack(String key, String group, StreamEntryID... ids) { + return appendCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public Response xgroupCreate(String key, String groupname, StreamEntryID id, boolean makeStream) { + return appendCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public Response xgroupSetID(String key, String groupname, StreamEntryID id) { + return appendCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public Response xgroupDestroy(String key, String groupname) { + return appendCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public Response xgroupDelConsumer(String key, String groupname, String consumername) { + return appendCommand(commandObjects.xgroupDelConsumer(key, groupname, consumername)); + } + + @Override + public Response xpending(String key, String groupname) { + return appendCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public Response> xpending(String key, String groupname, StreamEntryID start, StreamEntryID end, int count, String consumername) { + return appendCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Response> xpending(String key, String groupname, XPendingParams params) { + return appendCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public Response xdel(String key, StreamEntryID... ids) { + return appendCommand(commandObjects.xdel(key, ids)); + } + + @Override + public Response xtrim(String key, long maxLen, boolean approximate) { + return appendCommand(commandObjects.xtrim(key, maxLen, approximate)); + } + + @Override + public Response xtrim(String key, XTrimParams params) { + return appendCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Response> xclaim(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return appendCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xclaimJustId(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return appendCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response>> xautoclaim(String key, String group, String consumername, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaim(key, group, consumername, minIdleTime, start, params)); + } + + @Override + public Response>> xautoclaimJustId(String key, String group, String consumername, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaimJustId(key, group, consumername, minIdleTime, start, params)); + } + + @Override + public Response xinfoStream(String key) { + return appendCommand(commandObjects.xinfoStream(key)); + } + + @Override + public Response> xinfoGroup(String key) { + return appendCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public Response> xinfoConsumers(String key, String group) { + return appendCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public Response>>> xread(XReadParams xReadParams, Map streams) { + return appendCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public Response>>> xreadGroup(String groupname, String consumer, XReadGroupParams xReadGroupParams, Map streams) { + return appendCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public Response eval(String script) { + return appendCommand(commandObjects.eval(script)); + } + + @Override + public Response eval(String script, int keyCount, String... params) { + return appendCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Response eval(String script, List keys, List args) { + return appendCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Response evalsha(String sha1) { + return appendCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Response evalsha(String sha1, int keyCount, String... params) { + return appendCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Response evalsha(String sha1, List keys, List args) { + return appendCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Response waitReplicas(String sampleKey, int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Response eval(String script, String sampleKey) { + return appendCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Response evalsha(String sha1, String sampleKey) { + return appendCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Response> scriptExists(String sampleKey, String... sha1) { + return appendCommand(commandObjects.scriptExists(sampleKey, sha1)); + } + + @Override + public Response scriptLoad(String script, String sampleKey) { + return appendCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public Response scriptFlush(String sampleKey) { + return appendCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public Response scriptFlush(String sampleKey, FlushMode flushMode) { + return appendCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public Response scriptKill(String sampleKey) { + return appendCommand(commandObjects.scriptKill(sampleKey)); + } + + public Response publish(String channel, String message) { + return appendCommand(commandObjects.publish(channel, message)); + } + + public Response strAlgoLCSStrings(String strA, String strB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public Response geoadd(byte[] key, double longitude, double latitude, byte[] member) { + return appendCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public Response geoadd(byte[] key, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public Response geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Response geodist(byte[] key, byte[] member1, byte[] member2) { + return appendCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Response geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit) { + return appendCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public Response> geohash(byte[] key, byte[]... members) { + return appendCommand(commandObjects.geohash(key, members)); + } + + @Override + public Response> geopos(byte[] key, byte[]... members) { + return appendCommand(commandObjects.geopos(key, members)); + } + + @Override + public Response> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public Response georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public Response georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public Response hset(byte[] key, byte[] field, byte[] value) { + return appendCommand(commandObjects.hset(key, field, value)); + } + + @Override + public Response hset(byte[] key, Map hash) { + return appendCommand(commandObjects.hset(key, hash)); + } + + @Override + public Response hget(byte[] key, byte[] field) { + return appendCommand(commandObjects.hget(key, field)); + } + + @Override + public Response hsetnx(byte[] key, byte[] field, byte[] value) { + return appendCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public Response hmset(byte[] key, Map hash) { + return appendCommand(commandObjects.hmset(key, hash)); + } + + @Override + public Response> hmget(byte[] key, byte[]... fields) { + return appendCommand(commandObjects.hmget(key, fields)); + } + + @Override + public Response hincrBy(byte[] key, byte[] field, long value) { + return appendCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public Response hincrByFloat(byte[] key, byte[] field, double value) { + return appendCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public Response hexists(byte[] key, byte[] field) { + return appendCommand(commandObjects.hexists(key, field)); + } + + @Override + public Response hdel(byte[] key, byte[]... field) { + return appendCommand(commandObjects.hdel(key, field)); + } + + @Override + public Response hlen(byte[] key) { + return appendCommand(commandObjects.hlen(key)); + } + + @Override + public Response> hkeys(byte[] key) { + return appendCommand(commandObjects.hkeys(key)); + } + + @Override + public Response> hvals(byte[] key) { + return appendCommand(commandObjects.hvals(key)); + } + + @Override + public Response> hgetAll(byte[] key) { + return appendCommand(commandObjects.hgetAll(key)); + } + + @Override + public Response hrandfield(byte[] key) { + return appendCommand(commandObjects.hrandfield(key)); + } + + @Override + public Response> hrandfield(byte[] key, long count) { + return appendCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Response> hrandfieldWithValues(byte[] key, long count) { + return appendCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public Response>> hscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public Response hstrlen(byte[] key, byte[] field) { + return appendCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public Response pfadd(byte[] key, byte[]... elements) { + return appendCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public Response pfmerge(byte[] destkey, byte[]... sourcekeys) { + return appendCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public Response pfcount(byte[] key) { + return appendCommand(commandObjects.pfcount(key)); + } + + @Override + public Response pfcount(byte[]... keys) { + return appendCommand(commandObjects.pfcount(keys)); + } + + @Override + public Response exists(byte[] key) { + return appendCommand(commandObjects.exists(key)); + } + + @Override + public Response exists(byte[]... keys) { + return appendCommand(commandObjects.exists(keys)); + } + + @Override + public Response persist(byte[] key) { + return appendCommand(commandObjects.persist(key)); + } + + @Override + public Response type(byte[] key) { + return appendCommand(commandObjects.type(key)); + } + + @Override + public Response dump(byte[] key) { + return appendCommand(commandObjects.dump(key)); + } + + @Override + public Response restore(byte[] key, long ttl, byte[] serializedValue) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public Response restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public Response expire(byte[] key, long seconds) { + return appendCommand(commandObjects.expire(key, seconds)); + } + + @Override + public Response pexpire(byte[] key, long milliseconds) { + return appendCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public Response expireAt(byte[] key, long unixTime) { + return appendCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public Response pexpireAt(byte[] key, long millisecondsTimestamp) { + return appendCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public Response ttl(byte[] key) { + return appendCommand(commandObjects.ttl(key)); + } + + @Override + public Response pttl(byte[] key) { + return appendCommand(commandObjects.pttl(key)); + } + + @Override + public Response touch(byte[] key) { + return appendCommand(commandObjects.touch(key)); + } + + @Override + public Response touch(byte[]... keys) { + return appendCommand(commandObjects.touch(keys)); + } + + @Override + public Response> sort(byte[] key) { + return appendCommand(commandObjects.sort(key)); + } + + @Override + public Response> sort(byte[] key, SortingParams sortingParameters) { + return appendCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public Response del(byte[] key) { + return appendCommand(commandObjects.del(key)); + } + + @Override + public Response del(byte[]... keys) { + return appendCommand(commandObjects.del(keys)); + } + + @Override + public Response unlink(byte[] key) { + return appendCommand(commandObjects.unlink(key)); + } + + @Override + public Response unlink(byte[]... keys) { + return appendCommand(commandObjects.unlink(keys)); + } + + @Override + public Response copy(byte[] srcKey, byte[] dstKey, boolean replace) { + return appendCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public Response rename(byte[] oldkey, byte[] newkey) { + return appendCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public Response renamenx(byte[] oldkey, byte[] newkey) { + return appendCommand(commandObjects.renamenx(oldkey, newkey)); + } + + @Override + public Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey) { + return appendCommand(commandObjects.sort(key, sortingParameters, dstkey)); + } + + @Override + public Response sort(byte[] key, byte[] dstkey) { + return appendCommand(commandObjects.sort(key, dstkey)); + } + + @Override + public Response memoryUsage(byte[] key) { + return appendCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Response memoryUsage(byte[] key, int samples) { + return appendCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Response objectRefcount(byte[] key) { + return appendCommand(commandObjects.objectRefcount(key)); + } + + @Override + public Response objectEncoding(byte[] key) { + return appendCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Response objectIdletime(byte[] key) { + return appendCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Response objectFreq(byte[] key) { + return appendCommand(commandObjects.objectFreq(key)); + } + + @Override + public Response migrate(String host, int port, byte[] key, int timeout) { + return appendCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public Response migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { + return appendCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public Response> keys(byte[] pattern) { + return appendCommand(commandObjects.keys(pattern)); + } + + @Override + public Response> scan(byte[] cursor) { + return appendCommand(commandObjects.scan(cursor)); + } + + @Override + public Response> scan(byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.scan(cursor, params)); + } + + @Override + public Response> scan(byte[] cursor, ScanParams params, byte[] type) { + return appendCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Response randomBinaryKey() { + return appendCommand(commandObjects.randomBinaryKey()); + } + + @Override + public Response rpush(byte[] key, byte[]... args) { + return appendCommand(commandObjects.rpush(key, args)); + } + + @Override + public Response lpush(byte[] key, byte[]... args) { + return appendCommand(commandObjects.lpush(key, args)); + } + + @Override + public Response llen(byte[] key) { + return appendCommand(commandObjects.llen(key)); + } + + @Override + public Response> lrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public Response ltrim(byte[] key, long start, long stop) { + return appendCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public Response lindex(byte[] key, long index) { + return appendCommand(commandObjects.lindex(key, index)); + } + + @Override + public Response lset(byte[] key, long index, byte[] value) { + return appendCommand(commandObjects.lset(key, index, value)); + } + + @Override + public Response lrem(byte[] key, long count, byte[] value) { + return appendCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public Response lpop(byte[] key) { + return appendCommand(commandObjects.lpop(key)); + } + + @Override + public Response> lpop(byte[] key, int count) { + return appendCommand(commandObjects.lpop(key, count)); + } + + @Override + public Response lpos(byte[] key, byte[] element) { + return appendCommand(commandObjects.lpos(key, element)); + } + + @Override + public Response lpos(byte[] key, byte[] element, LPosParams params) { + return appendCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public Response> lpos(byte[] key, byte[] element, LPosParams params, long count) { + return appendCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Response rpop(byte[] key) { + return appendCommand(commandObjects.rpop(key)); + } + + @Override + public Response> rpop(byte[] key, int count) { + return appendCommand(commandObjects.rpop(key, count)); + } + + @Override + public Response linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value) { + return appendCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public Response lpushx(byte[] key, byte[]... arg) { + return appendCommand(commandObjects.lpushx(key, arg)); + } + + @Override + public Response rpushx(byte[] key, byte[]... arg) { + return appendCommand(commandObjects.rpushx(key, arg)); + } + + @Override + public Response> blpop(int timeout, byte[]... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> blpop(double timeout, byte[]... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> brpop(int timeout, byte[]... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response> brpop(double timeout, byte[]... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response rpoplpush(byte[] srckey, byte[] dstkey) { + return appendCommand(commandObjects.rpoplpush(srckey, dstkey)); + } + + @Override + public Response brpoplpush(byte[] source, byte[] destination, int timeout) { + return appendCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public Response lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { + return appendCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public Response blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { + return appendCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + public Response publish(byte[] channel, byte[] message) { + return appendCommand(commandObjects.publish(channel, message)); + } + + public Response strAlgoLCSStrings(byte[] strA, byte[] strB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public Response waitReplicas(byte[] sampleKey, int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Response eval(byte[] script, byte[] sampleKey) { + return appendCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Response evalsha(byte[] sha1, byte[] sampleKey) { + return appendCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Response> scriptExists(byte[] sampleKey, byte[]... sha1s) { + return appendCommand(commandObjects.scriptExists(sampleKey, sha1s)); + } + + @Override + public Response scriptLoad(byte[] script, byte[] sampleKey) { + return appendCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public Response scriptFlush(byte[] sampleKey) { + return appendCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public Response scriptFlush(byte[] sampleKey, FlushMode flushMode) { + return appendCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public Response scriptKill(byte[] sampleKey) { + return appendCommand(commandObjects.scriptKill(sampleKey)); + } + + @Override + public Response eval(byte[] script) { + return appendCommand(commandObjects.eval(script)); + } + + @Override + public Response eval(byte[] script, int keyCount, byte[]... params) { + return appendCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Response eval(byte[] script, List keys, List args) { + return appendCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Response evalsha(byte[] sha1) { + return appendCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Response evalsha(byte[] sha1, int keyCount, byte[]... params) { + return appendCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Response evalsha(byte[] sha1, List keys, List args) { + return appendCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Response sadd(byte[] key, byte[]... member) { + return appendCommand(commandObjects.sadd(key, member)); + } + + @Override + public Response> smembers(byte[] key) { + return appendCommand(commandObjects.smembers(key)); + } + + @Override + public Response srem(byte[] key, byte[]... member) { + return appendCommand(commandObjects.srem(key, member)); + } + + @Override + public Response spop(byte[] key) { + return appendCommand(commandObjects.spop(key)); + } + + @Override + public Response> spop(byte[] key, long count) { + return appendCommand(commandObjects.spop(key, count)); + } + + @Override + public Response scard(byte[] key) { + return appendCommand(commandObjects.scard(key)); + } + + @Override + public Response sismember(byte[] key, byte[] member) { + return appendCommand(commandObjects.sismember(key, member)); + } + + @Override + public Response> smismember(byte[] key, byte[]... members) { + return appendCommand(commandObjects.smismember(key, members)); + } + + @Override + public Response srandmember(byte[] key) { + return appendCommand(commandObjects.srandmember(key)); + } + + @Override + public Response> srandmember(byte[] key, int count) { + return appendCommand(commandObjects.srandmember(key, count)); + } + + @Override + public Response> sscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Response> sdiff(byte[]... keys) { + return appendCommand(commandObjects.sdiff(keys)); + } + + @Override + public Response sdiffstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sdiffstore(dstkey, keys)); + } + + @Override + public Response> sinter(byte[]... keys) { + return appendCommand(commandObjects.sinter(keys)); + } + + @Override + public Response sinterstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sinterstore(dstkey, keys)); + } + + @Override + public Response> sunion(byte[]... keys) { + return appendCommand(commandObjects.sunion(keys)); + } + + @Override + public Response sunionstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sunionstore(dstkey, keys)); + } + + @Override + public Response smove(byte[] srckey, byte[] dstkey, byte[] member) { + return appendCommand(commandObjects.smove(srckey, dstkey, member)); + } + + @Override + public Response zadd(byte[] key, double score, byte[] member) { + return appendCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public Response zadd(byte[] key, double score, byte[] member, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public Response zadd(byte[] key, Map scoreMembers) { + return appendCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public Response zadd(byte[] key, Map scoreMembers, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Response zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { + return appendCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Response zrem(byte[] key, byte[]... members) { + return appendCommand(commandObjects.zrem(key, members)); + } + + @Override + public Response zincrby(byte[] key, double increment, byte[] member) { + return appendCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Response zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params) { + return appendCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Response zrank(byte[] key, byte[] member) { + return appendCommand(commandObjects.zrank(key, member)); + } + + @Override + public Response zrevrank(byte[] key, byte[] member) { + return appendCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public Response> zrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public Response> zrevrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public Response> zrangeWithScores(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public Response> zrevrangeWithScores(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public Response zrandmember(byte[] key) { + return appendCommand(commandObjects.zrandmember(key)); + } + + @Override + public Response> zrandmember(byte[] key, long count) { + return appendCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public Response> zrandmemberWithScores(byte[] key, long count) { + return appendCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public Response zcard(byte[] key) { + return appendCommand(commandObjects.zcard(key)); + } + + @Override + public Response zscore(byte[] key, byte[] member) { + return appendCommand(commandObjects.zscore(key, member)); + } + + @Override + public Response> zmscore(byte[] key, byte[]... members) { + return appendCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Response zpopmax(byte[] key) { + return appendCommand(commandObjects.zpopmax(key)); + } + + @Override + public Response> zpopmax(byte[] key, int count) { + return appendCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Response zpopmin(byte[] key) { + return appendCommand(commandObjects.zpopmin(key)); + } + + @Override + public Response> zpopmin(byte[] key, int count) { + return appendCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public Response zcount(byte[] key, double min, double max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response zcount(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, double min, double max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, double min, double max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response zremrangeByRank(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public Response zremrangeByScore(byte[] key, double min, double max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zremrangeByScore(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zlexcount(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public Response> zrangeByLex(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public Response> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByLex(key, min, max)); + } + + @Override + public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response zremrangeByLex(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public Response> zscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public Response> bzpopmax(double timeout, byte[]... keys) { + return appendCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public Response> bzpopmin(double timeout, byte[]... keys) { + return appendCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Response> zdiff(byte[]... keys) { + return appendCommand(commandObjects.zdiff(keys)); + } + + @Override + public Response> zdiffWithScores(byte[]... keys) { + return appendCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public Response zdiffStore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.zdiffStore(dstkey, keys)); + } + + @Override + public Response> zinter(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Response> zinterWithScores(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Response zinterstore(byte[] dstkey, byte[]... sets) { + return appendCommand(commandObjects.zinterstore(dstkey, sets)); + } + + @Override + public Response zinterstore(byte[] dstkey, ZParams params, byte[]... sets) { + return appendCommand(commandObjects.zinterstore(dstkey, params, sets)); + } + + @Override + public Response> zunion(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Response> zunionWithScores(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public Response zunionstore(byte[] dstkey, byte[]... sets) { + return appendCommand(commandObjects.zunionstore(dstkey, sets)); + } + + @Override + public Response zunionstore(byte[] dstkey, ZParams params, byte[]... sets) { + return appendCommand(commandObjects.zunionstore(dstkey, params, sets)); + } + + @Override + public Response xadd(byte[] key, XAddParams params, Map hash) { + return appendCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public Response xlen(byte[] key) { + return appendCommand(commandObjects.xlen(key)); + } + + @Override + public Response> xrange(byte[] key, byte[] start, byte[] end) { + return appendCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public Response> xrange(byte[] key, byte[] start, byte[] end, int count) { + return appendCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public Response> xrevrange(byte[] key, byte[] end, byte[] start) { + return appendCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public Response> xrevrange(byte[] key, byte[] end, byte[] start, int count) { + return appendCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public Response xack(byte[] key, byte[] group, byte[]... ids) { + return appendCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public Response xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream) { + return appendCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public Response xgroupSetID(byte[] key, byte[] groupname, byte[] id) { + return appendCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public Response xgroupDestroy(byte[] key, byte[] groupname) { + return appendCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public Response xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName) { + return appendCommand(commandObjects.xgroupDelConsumer(key, groupname, consumerName)); + } + + @Override + public Response xdel(byte[] key, byte[]... ids) { + return appendCommand(commandObjects.xdel(key, ids)); + } + + @Override + public Response xtrim(byte[] key, long maxLen, boolean approximateLength) { + return appendCommand(commandObjects.xtrim(key, maxLen, approximateLength)); + } + + @Override + public Response xtrim(byte[] key, XTrimParams params) { + return appendCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Response xpending(byte[] key, byte[] groupname) { + return appendCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public Response> xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername) { + return appendCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Response> xpending(byte[] key, byte[] groupname, XPendingParams params) { + return appendCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public Response> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return appendCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return appendCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaim(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Response> xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Response xinfoStream(byte[] key) { + return appendCommand(commandObjects.xinfoStream(key)); + } + + @Override + public Response> xinfoGroup(byte[] key) { + return appendCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public Response> xinfoConsumers(byte[] key, byte[] group) { + return appendCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public Response> xread(XReadParams xReadParams, Map.Entry... streams) { + return appendCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public Response> xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, Map.Entry... streams) { + return appendCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public Response set(byte[] key, byte[] value) { + return appendCommand(commandObjects.set(key, value)); + } + + @Override + public Response set(byte[] key, byte[] value, SetParams params) { + return appendCommand(commandObjects.set(key, value, params)); + } + + @Override + public Response get(byte[] key) { + return appendCommand(commandObjects.get(key)); + } + + @Override + public Response getDel(byte[] key) { + return appendCommand(commandObjects.getDel(key)); + } + + @Override + public Response getEx(byte[] key, GetExParams params) { + return appendCommand(commandObjects.getEx(key, params)); + } + + @Override + public Response setbit(byte[] key, long offset, boolean value) { + return appendCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public Response getbit(byte[] key, long offset) { + return appendCommand(commandObjects.getbit(key, offset)); + } + + @Override + public Response setrange(byte[] key, long offset, byte[] value) { + return appendCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public Response getrange(byte[] key, long startOffset, long endOffset) { + return appendCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public Response getSet(byte[] key, byte[] value) { + return appendCommand(commandObjects.getSet(key, value)); + } + + @Override + public Response setnx(byte[] key, byte[] value) { + return appendCommand(commandObjects.setnx(key, value)); + } + + @Override + public Response setex(byte[] key, long seconds, byte[] value) { + return appendCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public Response psetex(byte[] key, long milliseconds, byte[] value) { + return appendCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public Response> mget(byte[]... keys) { + return appendCommand(commandObjects.mget(keys)); + } + + @Override + public Response mset(byte[]... keysvalues) { + return appendCommand(commandObjects.mset(keysvalues)); + } + + @Override + public Response msetnx(byte[]... keysvalues) { + return appendCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public Response incr(byte[] key) { + return appendCommand(commandObjects.incr(key)); + } + + @Override + public Response incrBy(byte[] key, long increment) { + return appendCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public Response incrByFloat(byte[] key, double increment) { + return appendCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public Response decr(byte[] key) { + return appendCommand(commandObjects.decr(key)); + } + + @Override + public Response decrBy(byte[] key, long decrement) { + return appendCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public Response append(byte[] key, byte[] value) { + return appendCommand(commandObjects.append(key, value)); + } + + @Override + public Response substr(byte[] key, int start, int end) { + return appendCommand(commandObjects.substr(key, start, end)); + } + + @Override + public Response strlen(byte[] key) { + return appendCommand(commandObjects.strlen(key)); + } + + @Override + public Response bitcount(byte[] key) { + return appendCommand(commandObjects.bitcount(key)); + } + + @Override + public Response bitcount(byte[] key, long start, long end) { + return appendCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public Response bitpos(byte[] key, boolean value) { + return appendCommand(commandObjects.bitpos(key, value)); + } + + @Override + public Response bitpos(byte[] key, boolean value, BitPosParams params) { + return appendCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public Response> bitfield(byte[] key, byte[]... arguments) { + return appendCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public Response> bitfieldReadonly(byte[] key, byte[]... arguments) { + return appendCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { + return appendCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public Response strAlgoLCSKeys(byte[] keyA, byte[] keyB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(keyA, keyB, params)); + } + + @Override + public Response jsonSet(String key, Path2 path, Object object) { + return appendCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public Response jsonSetWithEscape(String key, Path2 path, Object object) { + return appendCommand(commandObjects.jsonSetWithEscape(key, path, object)); + } + + @Override + public Response jsonSet(String key, Path path, Object object) { + return appendCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public Response jsonSet(String key, Path2 path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSet(key, path, object, params)); + } + + @Override + public Response jsonSetWithEscape(String key, Path2 path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSetWithEscape(key, path, object, params)); + } + + @Override + public Response jsonSet(String key, Path path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSet(key, path, object, params)); + } + + @Override + public Response jsonGet(String key) { + return appendCommand(commandObjects.jsonGet(key)); + } + + @Override + public Response jsonGet(String key, Class clazz) { + return appendCommand(commandObjects.jsonGet(key, clazz)); + } + + @Override + public Response jsonGet(String key, Path2... paths) { + return appendCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Response jsonGet(String key, Path... paths) { + return appendCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Response jsonGet(String key, Class clazz, Path... paths) { + return appendCommand(commandObjects.jsonGet(key, clazz, paths)); + } + + @Override + public Response> jsonMGet(Path2 path, String... keys) { + return appendCommand(commandObjects.jsonMGet(path, keys)); + } + + @Override + public Response> jsonMGet(Path path, Class clazz, String... keys) { + return appendCommand(commandObjects.jsonMGet(path, clazz, keys)); + } + + @Override + public Response jsonDel(String key) { + return appendCommand(commandObjects.jsonDel(key)); + } + + @Override + public Response jsonDel(String key, Path2 path) { + return appendCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public Response jsonDel(String key, Path path) { + return appendCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public Response jsonClear(String key) { + return appendCommand(commandObjects.jsonClear(key)); + } + + @Override + public Response jsonClear(String key, Path2 path) { + return appendCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public Response jsonClear(String key, Path path) { + return appendCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public Response> jsonToggle(String key, Path2 path) { + return appendCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Response jsonToggle(String key, Path path) { + return appendCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Response> jsonType(String key) { + return appendCommand(commandObjects.jsonType(key)); + } + + @Override + public Response>> jsonType(String key, Path2 path) { + return appendCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Response> jsonType(String key, Path path) { + return appendCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Response jsonStrAppend(String key, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, string)); + } + + @Override + public Response> jsonStrAppend(String key, Path2 path, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Response jsonStrAppend(String key, Path path, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Response jsonStrLen(String key) { + return appendCommand(commandObjects.jsonStrLen(key)); + } + + @Override + public Response> jsonStrLen(String key, Path2 path) { + return appendCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Response jsonStrLen(String key, Path path) { + return appendCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Response> jsonArrAppend(String key, Path2 path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public Response> jsonArrAppendWithEscape(String key, Path2 path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppendWithEscape(key, path, objects)); + } + + @Override + public Response jsonArrAppend(String key, Path path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public Response> jsonArrIndex(String key, Path2 path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public Response> jsonArrIndexWithEscape(String key, Path2 path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndexWithEscape(key, path, scalar)); + } + + @Override + public Response jsonArrIndex(String key, Path path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public Response> jsonArrInsert(String key, Path2 path, int index, Object... objects) { + return appendCommand(commandObjects.jsonArrInsert(key, path, index, objects)); + } + + @Override + public Response> jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects) { + return appendCommand(commandObjects.jsonArrInsertWithEscape(key, path, index, objects)); + } + + @Override + public Response jsonArrInsert(String key, Path path, int index, Object... pojos) { + return appendCommand(commandObjects.jsonArrInsert(key, path, index, pojos)); + } + + @Override + public Response jsonArrPop(String key) { + return appendCommand(commandObjects.jsonArrPop(key)); + } + + @Override + public Response jsonArrLen(String key, Path path) { + return appendCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Response> jsonArrTrim(String key, Path2 path, int start, int stop) { + return appendCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Response jsonArrTrim(String key, Path path, int start, int stop) { + return appendCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Response jsonArrPop(String key, Class clazz, Path path) { + return appendCommand(commandObjects.jsonArrPop(key, clazz, path)); + } + + @Override + public Response> jsonArrPop(String key, Path2 path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Response jsonArrPop(String key, Path path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Response jsonArrPop(String key, Class clazz, Path path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, clazz, path, index)); + } + + @Override + public Response jsonArrLen(String key) { + return appendCommand(commandObjects.jsonArrLen(key)); + } + + @Override + public Response> jsonArrLen(String key, Path2 path) { + return appendCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Response jsonArrPop(String key, Class clazz) { + return appendCommand(commandObjects.jsonArrPop(key, clazz)); + } + + @Override + public Response> jsonArrPop(String key, Path2 path) { + return appendCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Response jsonArrPop(String key, Path path) { + return appendCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Response ftCreate(String indexName, IndexOptions indexOptions, Schema schema) { + return appendCommand(commandObjects.ftCreate(indexName, indexOptions, schema)); + } + + @Override + public Response ftSearch(String indexName, Query query) { + return appendCommand(commandObjects.ftSearch(indexName, query)); + } + + @Override + public Response ftSearch(byte[] indexName, Query query) { + return appendCommand(commandObjects.ftSearch(indexName, query)); + } + + public Response waitReplicas(int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(replicas, timeout)); + } +} diff --git a/src/main/java/redis/clients/jedis/Pipeline.java b/src/main/java/redis/clients/jedis/Pipeline.java index 3234728eac..03b11fc927 100644 --- a/src/main/java/redis/clients/jedis/Pipeline.java +++ b/src/main/java/redis/clients/jedis/Pipeline.java @@ -3,102 +3,67 @@ import java.io.Closeable; import java.util.ArrayList; import java.util.List; +import java.util.Map; +import java.util.Set; +import org.json.JSONArray; +import redis.clients.jedis.args.*; +import redis.clients.jedis.commands.PipelineBinaryCommands; +import redis.clients.jedis.commands.PipelineCommands; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.commands.RedisModulePipelineCommands; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; +import redis.clients.jedis.search.IndexOptions; +import redis.clients.jedis.search.Query; +import redis.clients.jedis.search.Schema; +import redis.clients.jedis.search.SearchResult; -public class Pipeline extends MultiKeyPipelineBase implements Closeable { +public class Pipeline extends Queable implements PipelineCommands, PipelineBinaryCommands, + RedisModulePipelineCommands, Closeable { - private MultiResponseBuilder currentMulti; + protected final Connection connection; +// private final Jedis jedis; + private final CommandObjects commandObjects; - private class MultiResponseBuilder extends Builder> { - private List> responses = new ArrayList<>(); - - @Override - public List build(Object data) { - @SuppressWarnings("unchecked") - List list = (List) data; - List values = new ArrayList<>(); - - if (list.size() != responses.size()) { - throw new IllegalStateException( - "Expected data size " + responses.size() + " but was " + list.size()); - } - - for (int i = 0; i < list.size(); i++) { - Response response = responses.get(i); - response.set(list.get(i)); - Object builtResponse; - try { - builtResponse = response.get(); - } catch (JedisDataException e) { - builtResponse = e; - } - values.add(builtResponse); - } - return values; - } - - public void setResponseDependency(Response dependency) { - for (Response response : responses) { - response.setDependency(dependency); - } - } - - public void addResponse(Response response) { - responses.add(response); - } - } - - @Override - protected Response getResponse(Builder builder) { - if (currentMulti != null) { - super.getResponse(BuilderFactory.STRING); // Expected QUEUED - - Response lr = new Response<>(builder); - currentMulti.addResponse(lr); - return lr; - } else { - return super.getResponse(builder); - } + public Pipeline(Connection connection) { +// super(connection); + this.connection = connection; +// this.jedis = null; + this.commandObjects = new CommandObjects(); } - public void setClient(Client client) { - this.client = client; + public Pipeline(Jedis jedis) { +// super(jedis.getConnection()); + this.connection = jedis.getConnection(); +// this.jedis = jedis; + this.commandObjects = new CommandObjects(); } - @Override - protected Client getClient(byte[] key) { - return client; + public final Response appendCommand(CommandObject commandObject) { + connection.sendCommand(commandObject.getArguments()); + return enqueResponse(commandObject.getBuilder()); } @Override - protected Client getClient(String key) { - return client; - } - - public void clear() { - if (isInMulti()) { - discard(); - } - + public void close() { sync(); } - public boolean isInMulti() { - return currentMulti != null; - } - /** * Synchronize pipeline by reading all responses. This operation close the pipeline. In order to * get return values from pipelined commands, capture the different Response<?> of the * commands you execute. */ public void sync() { - if (getPipelinedResponseLength() > 0) { - List unformatted = client.getMany(getPipelinedResponseLength()); - for (Object o : unformatted) { - generateResponse(o); - } + if (!hasPipelinedResponse()) return; + List unformatted = connection.getMany(getPipelinedResponseLength()); + for (Object o : unformatted) { + generateResponse(o); } } @@ -109,8 +74,8 @@ public void sync() { * @return A list of all the responses in the order you executed them. */ public List syncAndReturnAll() { - if (getPipelinedResponseLength() > 0) { - List unformatted = client.getMany(getPipelinedResponseLength()); + if (hasPipelinedResponse()) { + List unformatted = connection.getMany(getPipelinedResponseLength()); List formatted = new ArrayList<>(); for (Object o : unformatted) { try { @@ -125,50 +90,2946 @@ public List syncAndReturnAll() { } } - public Response discard() { - if (currentMulti == null) throw new IllegalStateException("DISCARD without MULTI"); - client.discard(); - currentMulti = null; - return getResponse(BuilderFactory.STRING); + @Deprecated + public final boolean hasPipelinedResponse() { + return getPipelinedResponseLength() > 0; + } + + @Override + public Response exists(String key) { + return appendCommand(commandObjects.exists(key)); } - public Response> exec() { - if (currentMulti == null) throw new IllegalStateException("EXEC without MULTI"); + @Override + public Response exists(String... keys) { + return appendCommand(commandObjects.exists(keys)); + } - client.exec(); - Response> response = super.getResponse(currentMulti); - currentMulti.setResponseDependency(response); - currentMulti = null; - return response; + @Override + public Response persist(String key) { + return appendCommand(commandObjects.persist(key)); } - public Response multi() { - if (currentMulti != null) throw new IllegalStateException("MULTI calls can not be nested"); + @Override + public Response type(String key) { + return appendCommand(commandObjects.type(key)); + } - client.multi(); - Response response = getResponse(BuilderFactory.STRING); // Expecting OK - currentMulti = new MultiResponseBuilder(); - return response; + @Override + public Response dump(String key) { + return appendCommand(commandObjects.dump(key)); } @Override - public void close() { - clear(); + public Response restore(String key, long ttl, byte[] serializedValue) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue)); } - public Response watch(String... keys) { - client.watch(keys); - return getResponse(BuilderFactory.STRING); + @Override + public Response restore(String key, long ttl, byte[] serializedValue, RestoreParams params) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue, params)); } - public Response watch(byte[]... keys) { - client.watch(keys); - return getResponse(BuilderFactory.STRING); + @Override + public Response expire(String key, long seconds) { + return appendCommand(commandObjects.expire(key, seconds)); } - public Response waitReplicas(int replicas, long timeout) { - client.waitReplicas(replicas, timeout); - return getResponse(BuilderFactory.LONG); + @Override + public Response pexpire(String key, long milliseconds) { + return appendCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public Response expireAt(String key, long unixTime) { + return appendCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public Response pexpireAt(String key, long millisecondsTimestamp) { + return appendCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public Response ttl(String key) { + return appendCommand(commandObjects.ttl(key)); + } + + @Override + public Response pttl(String key) { + return appendCommand(commandObjects.pttl(key)); + } + + @Override + public Response touch(String key) { + return appendCommand(commandObjects.touch(key)); + } + + @Override + public Response touch(String... keys) { + return appendCommand(commandObjects.touch(keys)); + } + + @Override + public Response> sort(String key) { + return appendCommand(commandObjects.sort(key)); + } + + @Override + public Response sort(String key, String dstKey) { + return appendCommand(commandObjects.sort(key, dstKey)); + } + + @Override + public Response> sort(String key, SortingParams sortingParameters) { + return appendCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public Response sort(String key, SortingParams sortingParameters, String dstKey) { + return appendCommand(commandObjects.sort(key, sortingParameters, dstKey)); + } + + @Override + public Response del(String key) { + return appendCommand(commandObjects.del(key)); + } + + @Override + public Response del(String... keys) { + return appendCommand(commandObjects.del(keys)); + } + + @Override + public Response unlink(String key) { + return appendCommand(commandObjects.unlink(key)); + } + + @Override + public Response unlink(String... keys) { + return appendCommand(commandObjects.unlink(keys)); + } + + @Override + public Response copy(String srcKey, String dstKey, boolean replace) { + return appendCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public Response rename(String oldkey, String newkey) { + return appendCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public Response renamenx(String oldkey, String newkey) { + return appendCommand(commandObjects.renamenx(oldkey, newkey)); + } + + @Override + public Response memoryUsage(String key) { + return appendCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Response memoryUsage(String key, int samples) { + return appendCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Response objectRefcount(String key) { + return appendCommand(commandObjects.objectRefcount(key)); + } + + @Override + public Response objectEncoding(String key) { + return appendCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Response objectIdletime(String key) { + return appendCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Response objectFreq(String key) { + return appendCommand(commandObjects.objectFreq(key)); + } + + @Override + public Response migrate(String host, int port, String key, int timeout) { + return appendCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public Response migrate(String host, int port, int timeout, MigrateParams params, String... keys) { + return appendCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public Response> keys(String pattern) { + return appendCommand(commandObjects.keys(pattern)); + } + + @Override + public Response> scan(String cursor) { + return appendCommand(commandObjects.scan(cursor)); + } + + @Override + public Response> scan(String cursor, ScanParams params) { + return appendCommand(commandObjects.scan(cursor, params)); } + @Override + public Response> scan(String cursor, ScanParams params, String type) { + return appendCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Response randomKey() { + return appendCommand(commandObjects.randomKey()); + } + + @Override + public Response get(String key) { + return appendCommand(commandObjects.get(key)); + } + + @Override + public Response getDel(String key) { + return appendCommand(commandObjects.getDel(key)); + } + + @Override + public Response getEx(String key, GetExParams params) { + return appendCommand(commandObjects.getEx(key, params)); + } + + @Override + public Response setbit(String key, long offset, boolean value) { + return appendCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public Response getbit(String key, long offset) { + return appendCommand(commandObjects.getbit(key, offset)); + } + + @Override + public Response setrange(String key, long offset, String value) { + return appendCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public Response getrange(String key, long startOffset, long endOffset) { + return appendCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public Response getSet(String key, String value) { + return appendCommand(commandObjects.getSet(key, value)); + } + + @Override + public Response setnx(String key, String value) { + return appendCommand(commandObjects.setnx(key, value)); + } + + @Override + public Response setex(String key, long seconds, String value) { + return appendCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public Response psetex(String key, long milliseconds, String value) { + return appendCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public Response> mget(String... keys) { + return appendCommand(commandObjects.mget(keys)); + } + + @Override + public Response mset(String... keysvalues) { + return appendCommand(commandObjects.mset(keysvalues)); + } + + @Override + public Response msetnx(String... keysvalues) { + return appendCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public Response incr(String key) { + return appendCommand(commandObjects.incr(key)); + } + + @Override + public Response incrBy(String key, long increment) { + return appendCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public Response incrByFloat(String key, double increment) { + return appendCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public Response decr(String key) { + return appendCommand(commandObjects.decr(key)); + } + + @Override + public Response decrBy(String key, long decrement) { + return appendCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public Response append(String key, String value) { + return appendCommand(commandObjects.append(key, value)); + } + + @Override + public Response substr(String key, int start, int end) { + return appendCommand(commandObjects.substr(key, start, end)); + } + + @Override + public Response strlen(String key) { + return appendCommand(commandObjects.strlen(key)); + } + + @Override + public Response bitcount(String key) { + return appendCommand(commandObjects.bitcount(key)); + } + + @Override + public Response bitcount(String key, long start, long end) { + return appendCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public Response bitpos(String key, boolean value) { + return appendCommand(commandObjects.bitpos(key, value)); + } + + @Override + public Response bitpos(String key, boolean value, BitPosParams params) { + return appendCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public Response> bitfield(String key, String... arguments) { + return appendCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public Response> bitfieldReadonly(String key, String... arguments) { + return appendCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public Response bitop(BitOP op, String destKey, String... srcKeys) { + return appendCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public Response strAlgoLCSKeys(String keyA, String keyB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); + } + + @Override + public Response set(String key, String value) { + return appendCommand(commandObjects.set(key, value)); + } + + @Override + public Response set(String key, String value, SetParams params) { + return appendCommand(commandObjects.set(key, value, params)); + } + + @Override + public Response rpush(String key, String... string) { + return appendCommand(commandObjects.rpush(key, string)); + + } + + @Override + public Response lpush(String key, String... string) { + return appendCommand(commandObjects.lpush(key, string)); + } + + @Override + public Response llen(String key) { + return appendCommand(commandObjects.llen(key)); + } + + @Override + public Response> lrange(String key, long start, long stop) { + return appendCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public Response ltrim(String key, long start, long stop) { + return appendCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public Response lindex(String key, long index) { + return appendCommand(commandObjects.lindex(key, index)); + } + + @Override + public Response lset(String key, long index, String value) { + return appendCommand(commandObjects.lset(key, index, value)); + } + + @Override + public Response lrem(String key, long count, String value) { + return appendCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public Response lpop(String key) { + return appendCommand(commandObjects.lpop(key)); + } + + @Override + public Response> lpop(String key, int count) { + return appendCommand(commandObjects.lpop(key, count)); + } + + @Override + public Response lpos(String key, String element) { + return appendCommand(commandObjects.lpos(key, element)); + } + + @Override + public Response lpos(String key, String element, LPosParams params) { + return appendCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public Response> lpos(String key, String element, LPosParams params, long count) { + return appendCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Response rpop(String key) { + return appendCommand(commandObjects.rpop(key)); + } + + @Override + public Response> rpop(String key, int count) { + return appendCommand(commandObjects.rpop(key, count)); + } + + @Override + public Response linsert(String key, ListPosition where, String pivot, String value) { + return appendCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public Response lpushx(String key, String... string) { + return appendCommand(commandObjects.lpushx(key, string)); + } + + @Override + public Response rpushx(String key, String... string) { + return appendCommand(commandObjects.rpushx(key, string)); + } + + @Override + public Response> blpop(int timeout, String key) { + return appendCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public Response blpop(double timeout, String key) { + return appendCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public Response> brpop(int timeout, String key) { + return appendCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public Response brpop(double timeout, String key) { + return appendCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public Response> blpop(int timeout, String... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response blpop(double timeout, String... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> brpop(int timeout, String... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response brpop(double timeout, String... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response rpoplpush(String srcKey, String dstKey) { + return appendCommand(commandObjects.rpoplpush(srcKey, dstKey)); + } + + @Override + public Response brpoplpush(String source, String destination, int timeout) { + return appendCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public Response lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { + return appendCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public Response blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout) { + return appendCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + @Override + public Response hset(String key, String field, String value) { + return appendCommand(commandObjects.hset(key, field, value)); + } + + @Override + public Response hset(String key, Map hash) { + return appendCommand(commandObjects.hset(key, hash)); + } + + @Override + public Response hget(String key, String field) { + return appendCommand(commandObjects.hget(key, field)); + } + + @Override + public Response hsetnx(String key, String field, String value) { + return appendCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public Response hmset(String key, Map hash) { + return appendCommand(commandObjects.hmset(key, hash)); + } + + @Override + public Response> hmget(String key, String... fields) { + return appendCommand(commandObjects.hmget(key, fields)); + } + + @Override + public Response hincrBy(String key, String field, long value) { + return appendCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public Response hincrByFloat(String key, String field, double value) { + return appendCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public Response hexists(String key, String field) { + return appendCommand(commandObjects.hexists(key, field)); + } + + @Override + public Response hdel(String key, String... field) { + return appendCommand(commandObjects.hdel(key, field)); + } + + @Override + public Response hlen(String key) { + return appendCommand(commandObjects.hlen(key)); + } + + @Override + public Response> hkeys(String key) { + return appendCommand(commandObjects.hkeys(key)); + } + + @Override + public Response> hvals(String key) { + return appendCommand(commandObjects.hvals(key)); + } + + @Override + public Response> hgetAll(String key) { + return appendCommand(commandObjects.hgetAll(key)); + } + + @Override + public Response hrandfield(String key) { + return appendCommand(commandObjects.hrandfield(key)); + } + + @Override + public Response> hrandfield(String key, long count) { + return appendCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Response> hrandfieldWithValues(String key, long count) { + return appendCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public Response>> hscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public Response hstrlen(String key, String field) { + return appendCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public Response sadd(String key, String... member) { + return appendCommand(commandObjects.sadd(key, member)); + } + + @Override + public Response> smembers(String key) { + return appendCommand(commandObjects.smembers(key)); + } + + @Override + public Response srem(String key, String... member) { + return appendCommand(commandObjects.srem(key, member)); + } + + @Override + public Response spop(String key) { + return appendCommand(commandObjects.spop(key)); + } + + @Override + public Response> spop(String key, long count) { + return appendCommand(commandObjects.spop(key, count)); + } + + @Override + public Response scard(String key) { + return appendCommand(commandObjects.scard(key)); + } + + @Override + public Response sismember(String key, String member) { + return appendCommand(commandObjects.sismember(key, member)); + } + + @Override + public Response> smismember(String key, String... members) { + return appendCommand(commandObjects.smismember(key, members)); + } + + @Override + public Response srandmember(String key) { + return appendCommand(commandObjects.srandmember(key)); + } + + @Override + public Response> srandmember(String key, int count) { + return appendCommand(commandObjects.srandmember(key, count)); + } + + @Override + public Response> sscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Response> sdiff(String... keys) { + return appendCommand(commandObjects.sdiff(keys)); + } + + @Override + public Response sdiffstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sdiffstore(dstKey, keys)); + } + + @Override + public Response> sinter(String... keys) { + return appendCommand(commandObjects.sinter(keys)); + } + + @Override + public Response sinterstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sinterstore(dstKey, keys)); + } + + @Override + public Response> sunion(String... keys) { + return appendCommand(commandObjects.sunion(keys)); + } + + @Override + public Response sunionstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sunionstore(dstKey, keys)); + } + + @Override + public Response smove(String srcKey, String dstKey, String member) { + return appendCommand(commandObjects.smove(srcKey, dstKey, member)); + } + + @Override + public Response zadd(String key, double score, String member) { + return appendCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public Response zadd(String key, double score, String member, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public Response zadd(String key, Map scoreMembers) { + return appendCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public Response zadd(String key, Map scoreMembers, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Response zaddIncr(String key, double score, String member, ZAddParams params) { + return appendCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Response zrem(String key, String... members) { + return appendCommand(commandObjects.zrem(key, members)); + } + + @Override + public Response zincrby(String key, double increment, String member) { + return appendCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Response zincrby(String key, double increment, String member, ZIncrByParams params) { + return appendCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Response zrank(String key, String member) { + return appendCommand(commandObjects.zrank(key, member)); + } + + @Override + public Response zrevrank(String key, String member) { + return appendCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public Response> zrange(String key, long start, long stop) { + return appendCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public Response> zrevrange(String key, long start, long stop) { + return appendCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public Response> zrangeWithScores(String key, long start, long stop) { + return appendCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public Response> zrevrangeWithScores(String key, long start, long stop) { + return appendCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public Response zrandmember(String key) { + return appendCommand(commandObjects.zrandmember(key)); + } + + @Override + public Response> zrandmember(String key, long count) { + return appendCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public Response> zrandmemberWithScores(String key, long count) { + return appendCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public Response zcard(String key) { + return appendCommand(commandObjects.zcard(key)); + } + + @Override + public Response zscore(String key, String member) { + return appendCommand(commandObjects.zscore(key, member)); + } + + @Override + public Response> zmscore(String key, String... members) { + return appendCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Response zpopmax(String key) { + return appendCommand(commandObjects.zpopmax(key)); + } + + @Override + public Response> zpopmax(String key, int count) { + return appendCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Response zpopmin(String key) { + return appendCommand(commandObjects.zpopmin(key)); + } + + @Override + public Response> zpopmin(String key, int count) { + return appendCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public Response zcount(String key, double min, double max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response zcount(String key, String min, String max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response> zrangeByScore(String key, double min, double max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrevrangeByScore(String key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + + } + + @Override + public Response> zrangeByScore(String key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public Response> zrangeByScore(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, double min, double max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByRank(String key, long start, long stop) { + return appendCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public Response zremrangeByScore(String key, double min, double max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zremrangeByScore(String key, String min, String max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zlexcount(String key, String min, String max) { + return appendCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public Response> zrangeByLex(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public Response> zrangeByLex(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByLex(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public Response> zrevrangeByLex(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByLex(String key, String min, String max) { + return appendCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public Response> zscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public Response bzpopmax(double timeout, String... keys) { + return appendCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public Response bzpopmin(double timeout, String... keys) { + return appendCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Response> zdiff(String... keys) { + return appendCommand(commandObjects.zdiff(keys)); + } + + @Override + public Response> zdiffWithScores(String... keys) { + return appendCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public Response zdiffStore(String dstKey, String... keys) { + return appendCommand(commandObjects.zdiffStore(dstKey, keys)); + } + + @Override + public Response zinterstore(String dstKey, String... sets) { + return appendCommand(commandObjects.zinterstore(dstKey, sets)); + } + + @Override + public Response zinterstore(String dstKey, ZParams params, String... sets) { + return appendCommand(commandObjects.zinterstore(dstKey, params, sets)); + } + + @Override + public Response> zinter(ZParams params, String... keys) { + return appendCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Response> zinterWithScores(ZParams params, String... keys) { + return appendCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Response> zunion(ZParams params, String... keys) { + return appendCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Response> zunionWithScores(ZParams params, String... keys) { + return appendCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public Response zunionstore(String dstKey, String... sets) { + return appendCommand(commandObjects.zunionstore(dstKey, sets)); + } + + @Override + public Response zunionstore(String dstKey, ZParams params, String... sets) { + return appendCommand(commandObjects.zunionstore(dstKey, params, sets)); + } + + @Override + public Response geoadd(String key, double longitude, double latitude, String member) { + return appendCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public Response geoadd(String key, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public Response geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Response geodist(String key, String member1, String member2) { + return appendCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Response geodist(String key, String member1, String member2, GeoUnit unit) { + return appendCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public Response> geohash(String key, String... members) { + return appendCommand(commandObjects.geohash(key, members)); + } + + @Override + public Response> geopos(String key, String... members) { + return appendCommand(commandObjects.geopos(key, members)); + } + + @Override + public Response> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusByMember(String key, String member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMember(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public Response georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public Response georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public Response pfadd(String key, String... elements) { + return appendCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public Response pfmerge(String destkey, String... sourcekeys) { + return appendCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public Response pfcount(String key) { + return appendCommand(commandObjects.pfcount(key)); + } + + @Override + public Response pfcount(String... keys) { + return appendCommand(commandObjects.pfcount(keys)); + } + + @Override + public Response xadd(String key, StreamEntryID id, Map hash) { + return appendCommand(commandObjects.xadd(key, id, hash)); + } + + @Override + public Response xadd_v2(String key, XAddParams params, Map hash) { + return appendCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public Response xlen(String key) { + return appendCommand(commandObjects.xlen(key)); + } + + @Override + public Response> xrange(String key, StreamEntryID start, StreamEntryID end) { + return appendCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public Response> xrange(String key, StreamEntryID start, StreamEntryID end, int count) { + return appendCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start) { + return appendCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { + return appendCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public Response xack(String key, String group, StreamEntryID... ids) { + return appendCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public Response xgroupCreate(String key, String groupname, StreamEntryID id, boolean makeStream) { + return appendCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public Response xgroupSetID(String key, String groupname, StreamEntryID id) { + return appendCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public Response xgroupDestroy(String key, String groupname) { + return appendCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public Response xgroupDelConsumer(String key, String groupname, String consumername) { + return appendCommand(commandObjects.xgroupDelConsumer(key, groupname, consumername)); + } + + @Override + public Response xpending(String key, String groupname) { + return appendCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public Response> xpending(String key, String groupname, StreamEntryID start, StreamEntryID end, int count, String consumername) { + return appendCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Response> xpending(String key, String groupname, XPendingParams params) { + return appendCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public Response xdel(String key, StreamEntryID... ids) { + return appendCommand(commandObjects.xdel(key, ids)); + } + + @Override + public Response xtrim(String key, long maxLen, boolean approximate) { + return appendCommand(commandObjects.xtrim(key, maxLen, approximate)); + } + + @Override + public Response xtrim(String key, XTrimParams params) { + return appendCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Response> xclaim(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return appendCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xclaimJustId(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return appendCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response>> xautoclaim(String key, String group, String consumername, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaim(key, group, consumername, minIdleTime, start, params)); + } + + @Override + public Response>> xautoclaimJustId(String key, String group, String consumername, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaimJustId(key, group, consumername, minIdleTime, start, params)); + } + + @Override + public Response xinfoStream(String key) { + return appendCommand(commandObjects.xinfoStream(key)); + } + + @Override + public Response> xinfoGroup(String key) { + return appendCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public Response> xinfoConsumers(String key, String group) { + return appendCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public Response>>> xread(XReadParams xReadParams, Map streams) { + return appendCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public Response>>> xreadGroup(String groupname, String consumer, XReadGroupParams xReadGroupParams, Map streams) { + return appendCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public Response eval(String script) { + return appendCommand(commandObjects.eval(script)); + } + + @Override + public Response eval(String script, int keyCount, String... params) { + return appendCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Response eval(String script, List keys, List args) { + return appendCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Response evalsha(String sha1) { + return appendCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Response evalsha(String sha1, int keyCount, String... params) { + return appendCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Response evalsha(String sha1, List keys, List args) { + return appendCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Response waitReplicas(String sampleKey, int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Response eval(String script, String sampleKey) { + return appendCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Response evalsha(String sha1, String sampleKey) { + return appendCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Response> scriptExists(String sampleKey, String... sha1) { + return appendCommand(commandObjects.scriptExists(sampleKey, sha1)); + } + + @Override + public Response scriptLoad(String script, String sampleKey) { + return appendCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public Response scriptFlush(String sampleKey) { + return appendCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public Response scriptFlush(String sampleKey, FlushMode flushMode) { + return appendCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public Response scriptKill(String sampleKey) { + return appendCommand(commandObjects.scriptKill(sampleKey)); + } + + public Response publish(String channel, String message) { + return appendCommand(commandObjects.publish(channel, message)); + } + + public Response strAlgoLCSStrings(String strA, String strB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public Response geoadd(byte[] key, double longitude, double latitude, byte[] member) { + return appendCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public Response geoadd(byte[] key, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public Response geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Response geodist(byte[] key, byte[] member1, byte[] member2) { + return appendCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Response geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit) { + return appendCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public Response> geohash(byte[] key, byte[]... members) { + return appendCommand(commandObjects.geohash(key, members)); + } + + @Override + public Response> geopos(byte[] key, byte[]... members) { + return appendCommand(commandObjects.geopos(key, members)); + } + + @Override + public Response> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public Response georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public Response georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public Response hset(byte[] key, byte[] field, byte[] value) { + return appendCommand(commandObjects.hset(key, field, value)); + } + + @Override + public Response hset(byte[] key, Map hash) { + return appendCommand(commandObjects.hset(key, hash)); + } + + @Override + public Response hget(byte[] key, byte[] field) { + return appendCommand(commandObjects.hget(key, field)); + } + + @Override + public Response hsetnx(byte[] key, byte[] field, byte[] value) { + return appendCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public Response hmset(byte[] key, Map hash) { + return appendCommand(commandObjects.hmset(key, hash)); + } + + @Override + public Response> hmget(byte[] key, byte[]... fields) { + return appendCommand(commandObjects.hmget(key, fields)); + } + + @Override + public Response hincrBy(byte[] key, byte[] field, long value) { + return appendCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public Response hincrByFloat(byte[] key, byte[] field, double value) { + return appendCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public Response hexists(byte[] key, byte[] field) { + return appendCommand(commandObjects.hexists(key, field)); + } + + @Override + public Response hdel(byte[] key, byte[]... field) { + return appendCommand(commandObjects.hdel(key, field)); + } + + @Override + public Response hlen(byte[] key) { + return appendCommand(commandObjects.hlen(key)); + } + + @Override + public Response> hkeys(byte[] key) { + return appendCommand(commandObjects.hkeys(key)); + } + + @Override + public Response> hvals(byte[] key) { + return appendCommand(commandObjects.hvals(key)); + } + + @Override + public Response> hgetAll(byte[] key) { + return appendCommand(commandObjects.hgetAll(key)); + } + + @Override + public Response hrandfield(byte[] key) { + return appendCommand(commandObjects.hrandfield(key)); + } + + @Override + public Response> hrandfield(byte[] key, long count) { + return appendCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Response> hrandfieldWithValues(byte[] key, long count) { + return appendCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public Response>> hscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public Response hstrlen(byte[] key, byte[] field) { + return appendCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public Response pfadd(byte[] key, byte[]... elements) { + return appendCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public Response pfmerge(byte[] destkey, byte[]... sourcekeys) { + return appendCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public Response pfcount(byte[] key) { + return appendCommand(commandObjects.pfcount(key)); + } + + @Override + public Response pfcount(byte[]... keys) { + return appendCommand(commandObjects.pfcount(keys)); + } + + @Override + public Response exists(byte[] key) { + return appendCommand(commandObjects.exists(key)); + } + + @Override + public Response exists(byte[]... keys) { + return appendCommand(commandObjects.exists(keys)); + } + + @Override + public Response persist(byte[] key) { + return appendCommand(commandObjects.persist(key)); + } + + @Override + public Response type(byte[] key) { + return appendCommand(commandObjects.type(key)); + } + + @Override + public Response dump(byte[] key) { + return appendCommand(commandObjects.dump(key)); + } + + @Override + public Response restore(byte[] key, long ttl, byte[] serializedValue) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public Response restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public Response expire(byte[] key, long seconds) { + return appendCommand(commandObjects.expire(key, seconds)); + } + + @Override + public Response pexpire(byte[] key, long milliseconds) { + return appendCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public Response expireAt(byte[] key, long unixTime) { + return appendCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public Response pexpireAt(byte[] key, long millisecondsTimestamp) { + return appendCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public Response ttl(byte[] key) { + return appendCommand(commandObjects.ttl(key)); + } + + @Override + public Response pttl(byte[] key) { + return appendCommand(commandObjects.pttl(key)); + } + + @Override + public Response touch(byte[] key) { + return appendCommand(commandObjects.touch(key)); + } + + @Override + public Response touch(byte[]... keys) { + return appendCommand(commandObjects.touch(keys)); + } + + @Override + public Response> sort(byte[] key) { + return appendCommand(commandObjects.sort(key)); + } + + @Override + public Response> sort(byte[] key, SortingParams sortingParameters) { + return appendCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public Response del(byte[] key) { + return appendCommand(commandObjects.del(key)); + } + + @Override + public Response del(byte[]... keys) { + return appendCommand(commandObjects.del(keys)); + } + + @Override + public Response unlink(byte[] key) { + return appendCommand(commandObjects.unlink(key)); + } + + @Override + public Response unlink(byte[]... keys) { + return appendCommand(commandObjects.unlink(keys)); + } + + @Override + public Response copy(byte[] srcKey, byte[] dstKey, boolean replace) { + return appendCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public Response rename(byte[] oldkey, byte[] newkey) { + return appendCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public Response renamenx(byte[] oldkey, byte[] newkey) { + return appendCommand(commandObjects.renamenx(oldkey, newkey)); + } + + @Override + public Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey) { + return appendCommand(commandObjects.sort(key, sortingParameters, dstkey)); + } + + @Override + public Response sort(byte[] key, byte[] dstkey) { + return appendCommand(commandObjects.sort(key, dstkey)); + } + + @Override + public Response memoryUsage(byte[] key) { + return appendCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Response memoryUsage(byte[] key, int samples) { + return appendCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Response objectRefcount(byte[] key) { + return appendCommand(commandObjects.objectRefcount(key)); + } + + @Override + public Response objectEncoding(byte[] key) { + return appendCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Response objectIdletime(byte[] key) { + return appendCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Response objectFreq(byte[] key) { + return appendCommand(commandObjects.objectFreq(key)); + } + + @Override + public Response migrate(String host, int port, byte[] key, int timeout) { + return appendCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public Response migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { + return appendCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public Response> keys(byte[] pattern) { + return appendCommand(commandObjects.keys(pattern)); + } + + @Override + public Response> scan(byte[] cursor) { + return appendCommand(commandObjects.scan(cursor)); + } + + @Override + public Response> scan(byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.scan(cursor, params)); + } + + @Override + public Response> scan(byte[] cursor, ScanParams params, byte[] type) { + return appendCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Response randomBinaryKey() { + return appendCommand(commandObjects.randomBinaryKey()); + } + + @Override + public Response rpush(byte[] key, byte[]... args) { + return appendCommand(commandObjects.rpush(key, args)); + } + + @Override + public Response lpush(byte[] key, byte[]... args) { + return appendCommand(commandObjects.lpush(key, args)); + } + + @Override + public Response llen(byte[] key) { + return appendCommand(commandObjects.llen(key)); + } + + @Override + public Response> lrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public Response ltrim(byte[] key, long start, long stop) { + return appendCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public Response lindex(byte[] key, long index) { + return appendCommand(commandObjects.lindex(key, index)); + } + + @Override + public Response lset(byte[] key, long index, byte[] value) { + return appendCommand(commandObjects.lset(key, index, value)); + } + + @Override + public Response lrem(byte[] key, long count, byte[] value) { + return appendCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public Response lpop(byte[] key) { + return appendCommand(commandObjects.lpop(key)); + } + + @Override + public Response> lpop(byte[] key, int count) { + return appendCommand(commandObjects.lpop(key, count)); + } + + @Override + public Response lpos(byte[] key, byte[] element) { + return appendCommand(commandObjects.lpos(key, element)); + } + + @Override + public Response lpos(byte[] key, byte[] element, LPosParams params) { + return appendCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public Response> lpos(byte[] key, byte[] element, LPosParams params, long count) { + return appendCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Response rpop(byte[] key) { + return appendCommand(commandObjects.rpop(key)); + } + + @Override + public Response> rpop(byte[] key, int count) { + return appendCommand(commandObjects.rpop(key, count)); + } + + @Override + public Response linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value) { + return appendCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public Response lpushx(byte[] key, byte[]... arg) { + return appendCommand(commandObjects.lpushx(key, arg)); + } + + @Override + public Response rpushx(byte[] key, byte[]... arg) { + return appendCommand(commandObjects.rpushx(key, arg)); + } + + @Override + public Response> blpop(int timeout, byte[]... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> blpop(double timeout, byte[]... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> brpop(int timeout, byte[]... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response> brpop(double timeout, byte[]... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response rpoplpush(byte[] srckey, byte[] dstkey) { + return appendCommand(commandObjects.rpoplpush(srckey, dstkey)); + } + + @Override + public Response brpoplpush(byte[] source, byte[] destination, int timeout) { + return appendCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public Response lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { + return appendCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public Response blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { + return appendCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + public Response publish(byte[] channel, byte[] message) { + return appendCommand(commandObjects.publish(channel, message)); + } + + public Response strAlgoLCSStrings(byte[] strA, byte[] strB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public Response waitReplicas(byte[] sampleKey, int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Response eval(byte[] script, byte[] sampleKey) { + return appendCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Response evalsha(byte[] sha1, byte[] sampleKey) { + return appendCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Response> scriptExists(byte[] sampleKey, byte[]... sha1s) { + return appendCommand(commandObjects.scriptExists(sampleKey, sha1s)); + } + + @Override + public Response scriptLoad(byte[] script, byte[] sampleKey) { + return appendCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public Response scriptFlush(byte[] sampleKey) { + return appendCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public Response scriptFlush(byte[] sampleKey, FlushMode flushMode) { + return appendCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public Response scriptKill(byte[] sampleKey) { + return appendCommand(commandObjects.scriptKill(sampleKey)); + } + + @Override + public Response eval(byte[] script) { + return appendCommand(commandObjects.eval(script)); + } + + @Override + public Response eval(byte[] script, int keyCount, byte[]... params) { + return appendCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Response eval(byte[] script, List keys, List args) { + return appendCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Response evalsha(byte[] sha1) { + return appendCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Response evalsha(byte[] sha1, int keyCount, byte[]... params) { + return appendCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Response evalsha(byte[] sha1, List keys, List args) { + return appendCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Response sadd(byte[] key, byte[]... member) { + return appendCommand(commandObjects.sadd(key, member)); + } + + @Override + public Response> smembers(byte[] key) { + return appendCommand(commandObjects.smembers(key)); + } + + @Override + public Response srem(byte[] key, byte[]... member) { + return appendCommand(commandObjects.srem(key, member)); + } + + @Override + public Response spop(byte[] key) { + return appendCommand(commandObjects.spop(key)); + } + + @Override + public Response> spop(byte[] key, long count) { + return appendCommand(commandObjects.spop(key, count)); + } + + @Override + public Response scard(byte[] key) { + return appendCommand(commandObjects.scard(key)); + } + + @Override + public Response sismember(byte[] key, byte[] member) { + return appendCommand(commandObjects.sismember(key, member)); + } + + @Override + public Response> smismember(byte[] key, byte[]... members) { + return appendCommand(commandObjects.smismember(key, members)); + } + + @Override + public Response srandmember(byte[] key) { + return appendCommand(commandObjects.srandmember(key)); + } + + @Override + public Response> srandmember(byte[] key, int count) { + return appendCommand(commandObjects.srandmember(key, count)); + } + + @Override + public Response> sscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Response> sdiff(byte[]... keys) { + return appendCommand(commandObjects.sdiff(keys)); + } + + @Override + public Response sdiffstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sdiffstore(dstkey, keys)); + } + + @Override + public Response> sinter(byte[]... keys) { + return appendCommand(commandObjects.sinter(keys)); + } + + @Override + public Response sinterstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sinterstore(dstkey, keys)); + } + + @Override + public Response> sunion(byte[]... keys) { + return appendCommand(commandObjects.sunion(keys)); + } + + @Override + public Response sunionstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sunionstore(dstkey, keys)); + } + + @Override + public Response smove(byte[] srckey, byte[] dstkey, byte[] member) { + return appendCommand(commandObjects.smove(srckey, dstkey, member)); + } + + @Override + public Response zadd(byte[] key, double score, byte[] member) { + return appendCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public Response zadd(byte[] key, double score, byte[] member, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public Response zadd(byte[] key, Map scoreMembers) { + return appendCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public Response zadd(byte[] key, Map scoreMembers, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Response zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { + return appendCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Response zrem(byte[] key, byte[]... members) { + return appendCommand(commandObjects.zrem(key, members)); + } + + @Override + public Response zincrby(byte[] key, double increment, byte[] member) { + return appendCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Response zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params) { + return appendCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Response zrank(byte[] key, byte[] member) { + return appendCommand(commandObjects.zrank(key, member)); + } + + @Override + public Response zrevrank(byte[] key, byte[] member) { + return appendCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public Response> zrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public Response> zrevrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public Response> zrangeWithScores(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public Response> zrevrangeWithScores(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public Response zrandmember(byte[] key) { + return appendCommand(commandObjects.zrandmember(key)); + } + + @Override + public Response> zrandmember(byte[] key, long count) { + return appendCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public Response> zrandmemberWithScores(byte[] key, long count) { + return appendCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public Response zcard(byte[] key) { + return appendCommand(commandObjects.zcard(key)); + } + + @Override + public Response zscore(byte[] key, byte[] member) { + return appendCommand(commandObjects.zscore(key, member)); + } + + @Override + public Response> zmscore(byte[] key, byte[]... members) { + return appendCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Response zpopmax(byte[] key) { + return appendCommand(commandObjects.zpopmax(key)); + } + + @Override + public Response> zpopmax(byte[] key, int count) { + return appendCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Response zpopmin(byte[] key) { + return appendCommand(commandObjects.zpopmin(key)); + } + + @Override + public Response> zpopmin(byte[] key, int count) { + return appendCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public Response zcount(byte[] key, double min, double max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response zcount(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, double min, double max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public Response> zrangeByScore(byte[] key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public Response> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, double min, double max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByRank(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public Response zremrangeByScore(byte[] key, double min, double max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zremrangeByScore(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zlexcount(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public Response> zrangeByLex(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public Response> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByLex(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public Response> zscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public Response> bzpopmax(double timeout, byte[]... keys) { + return appendCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public Response> bzpopmin(double timeout, byte[]... keys) { + return appendCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Response> zdiff(byte[]... keys) { + return appendCommand(commandObjects.zdiff(keys)); + } + + @Override + public Response> zdiffWithScores(byte[]... keys) { + return appendCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public Response zdiffStore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.zdiffStore(dstkey, keys)); + } + + @Override + public Response> zinter(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Response> zinterWithScores(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Response zinterstore(byte[] dstkey, byte[]... sets) { + return appendCommand(commandObjects.zinterstore(dstkey, sets)); + } + + @Override + public Response zinterstore(byte[] dstkey, ZParams params, byte[]... sets) { + return appendCommand(commandObjects.zinterstore(dstkey, params, sets)); + } + + @Override + public Response> zunion(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Response> zunionWithScores(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public Response zunionstore(byte[] dstkey, byte[]... sets) { + return appendCommand(commandObjects.zunionstore(dstkey, sets)); + } + + @Override + public Response zunionstore(byte[] dstkey, ZParams params, byte[]... sets) { + return appendCommand(commandObjects.zunionstore(dstkey, params, sets)); + } + + @Override + public Response xadd(byte[] key, XAddParams params, Map hash) { + return appendCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public Response xlen(byte[] key) { + return appendCommand(commandObjects.xlen(key)); + } + + @Override + public Response> xrange(byte[] key, byte[] start, byte[] end) { + return appendCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public Response> xrange(byte[] key, byte[] start, byte[] end, int count) { + return appendCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public Response> xrevrange(byte[] key, byte[] end, byte[] start) { + return appendCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public Response> xrevrange(byte[] key, byte[] end, byte[] start, int count) { + return appendCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public Response xack(byte[] key, byte[] group, byte[]... ids) { + return appendCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public Response xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream) { + return appendCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public Response xgroupSetID(byte[] key, byte[] groupname, byte[] id) { + return appendCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public Response xgroupDestroy(byte[] key, byte[] groupname) { + return appendCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public Response xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName) { + return appendCommand(commandObjects.xgroupDelConsumer(key, groupname, consumerName)); + } + + @Override + public Response xdel(byte[] key, byte[]... ids) { + return appendCommand(commandObjects.xdel(key, ids)); + } + + @Override + public Response xtrim(byte[] key, long maxLen, boolean approximateLength) { + return appendCommand(commandObjects.xtrim(key, maxLen, approximateLength)); + } + + @Override + public Response xtrim(byte[] key, XTrimParams params) { + return appendCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Response xpending(byte[] key, byte[] groupname) { + return appendCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public Response> xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername) { + return appendCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Response> xpending(byte[] key, byte[] groupname, XPendingParams params) { + return appendCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public Response> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return appendCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return appendCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaim(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Response> xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Response xinfoStream(byte[] key) { + return appendCommand(commandObjects.xinfoStream(key)); + } + + @Override + public Response> xinfoGroup(byte[] key) { + return appendCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public Response> xinfoConsumers(byte[] key, byte[] group) { + return appendCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public Response> xread(XReadParams xReadParams, Map.Entry... streams) { + return appendCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public Response> xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, Map.Entry... streams) { + return appendCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public Response set(byte[] key, byte[] value) { + return appendCommand(commandObjects.set(key, value)); + } + + @Override + public Response set(byte[] key, byte[] value, SetParams params) { + return appendCommand(commandObjects.set(key, value, params)); + } + + @Override + public Response get(byte[] key) { + return appendCommand(commandObjects.get(key)); + } + + @Override + public Response getDel(byte[] key) { + return appendCommand(commandObjects.getDel(key)); + } + + @Override + public Response getEx(byte[] key, GetExParams params) { + return appendCommand(commandObjects.getEx(key, params)); + } + + @Override + public Response setbit(byte[] key, long offset, boolean value) { + return appendCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public Response getbit(byte[] key, long offset) { + return appendCommand(commandObjects.getbit(key, offset)); + } + + @Override + public Response setrange(byte[] key, long offset, byte[] value) { + return appendCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public Response getrange(byte[] key, long startOffset, long endOffset) { + return appendCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public Response getSet(byte[] key, byte[] value) { + return appendCommand(commandObjects.getSet(key, value)); + } + + @Override + public Response setnx(byte[] key, byte[] value) { + return appendCommand(commandObjects.setnx(key, value)); + } + + @Override + public Response setex(byte[] key, long seconds, byte[] value) { + return appendCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public Response psetex(byte[] key, long milliseconds, byte[] value) { + return appendCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public Response> mget(byte[]... keys) { + return appendCommand(commandObjects.mget(keys)); + } + + @Override + public Response mset(byte[]... keysvalues) { + return appendCommand(commandObjects.mset(keysvalues)); + } + + @Override + public Response msetnx(byte[]... keysvalues) { + return appendCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public Response incr(byte[] key) { + return appendCommand(commandObjects.incr(key)); + } + + @Override + public Response incrBy(byte[] key, long increment) { + return appendCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public Response incrByFloat(byte[] key, double increment) { + return appendCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public Response decr(byte[] key) { + return appendCommand(commandObjects.decr(key)); + } + + @Override + public Response decrBy(byte[] key, long decrement) { + return appendCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public Response append(byte[] key, byte[] value) { + return appendCommand(commandObjects.append(key, value)); + } + + @Override + public Response substr(byte[] key, int start, int end) { + return appendCommand(commandObjects.substr(key, start, end)); + } + + @Override + public Response strlen(byte[] key) { + return appendCommand(commandObjects.strlen(key)); + } + + @Override + public Response bitcount(byte[] key) { + return appendCommand(commandObjects.bitcount(key)); + } + + @Override + public Response bitcount(byte[] key, long start, long end) { + return appendCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public Response bitpos(byte[] key, boolean value) { + return appendCommand(commandObjects.bitpos(key, value)); + } + + @Override + public Response bitpos(byte[] key, boolean value, BitPosParams params) { + return appendCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public Response> bitfield(byte[] key, byte[]... arguments) { + return appendCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public Response> bitfieldReadonly(byte[] key, byte[]... arguments) { + return appendCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { + return appendCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public Response strAlgoLCSKeys(byte[] keyA, byte[] keyB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(keyA, keyB, params)); + } + + @Override + public Response jsonSet(String key, Path2 path, Object object) { + return appendCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public Response jsonSetWithEscape(String key, Path2 path, Object object) { + return appendCommand(commandObjects.jsonSetWithEscape(key, path, object)); + } + + @Override + public Response jsonSet(String key, Path path, Object object) { + return appendCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public Response jsonSet(String key, Path2 path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSet(key, path, object, params)); + } + + @Override + public Response jsonSetWithEscape(String key, Path2 path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSetWithEscape(key, path, object, params)); + } + + @Override + public Response jsonSet(String key, Path path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSet(key, path, object, params)); + } + + @Override + public Response jsonGet(String key) { + return appendCommand(commandObjects.jsonGet(key)); + } + + @Override + public Response jsonGet(String key, Class clazz) { + return appendCommand(commandObjects.jsonGet(key, clazz)); + } + + @Override + public Response jsonGet(String key, Path2... paths) { + return appendCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Response jsonGet(String key, Path... paths) { + return appendCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Response jsonGet(String key, Class clazz, Path... paths) { + return appendCommand(commandObjects.jsonGet(key, clazz, paths)); + } + + @Override + public Response> jsonMGet(Path2 path, String... keys) { + return appendCommand(commandObjects.jsonMGet(path, keys)); + } + + @Override + public Response> jsonMGet(Path path, Class clazz, String... keys) { + return appendCommand(commandObjects.jsonMGet(path, clazz, keys)); + } + + @Override + public Response jsonDel(String key) { + return appendCommand(commandObjects.jsonDel(key)); + } + + @Override + public Response jsonDel(String key, Path2 path) { + return appendCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public Response jsonDel(String key, Path path) { + return appendCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public Response jsonClear(String key) { + return appendCommand(commandObjects.jsonClear(key)); + } + + @Override + public Response jsonClear(String key, Path2 path) { + return appendCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public Response jsonClear(String key, Path path) { + return appendCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public Response> jsonToggle(String key, Path2 path) { + return appendCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Response jsonToggle(String key, Path path) { + return appendCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Response> jsonType(String key) { + return appendCommand(commandObjects.jsonType(key)); + } + + @Override + public Response>> jsonType(String key, Path2 path) { + return appendCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Response> jsonType(String key, Path path) { + return appendCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Response jsonStrAppend(String key, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, string)); + } + + @Override + public Response> jsonStrAppend(String key, Path2 path, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Response jsonStrAppend(String key, Path path, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Response jsonStrLen(String key) { + return appendCommand(commandObjects.jsonStrLen(key)); + } + + @Override + public Response> jsonStrLen(String key, Path2 path) { + return appendCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Response jsonStrLen(String key, Path path) { + return appendCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Response> jsonArrAppend(String key, Path2 path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public Response> jsonArrAppendWithEscape(String key, Path2 path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppendWithEscape(key, path, objects)); + } + + @Override + public Response jsonArrAppend(String key, Path path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public Response> jsonArrIndex(String key, Path2 path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public Response> jsonArrIndexWithEscape(String key, Path2 path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndexWithEscape(key, path, scalar)); + } + + @Override + public Response jsonArrIndex(String key, Path path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public Response> jsonArrInsert(String key, Path2 path, int index, Object... objects) { + return appendCommand(commandObjects.jsonArrInsert(key, path, index, objects)); + } + + @Override + public Response> jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects) { + return appendCommand(commandObjects.jsonArrInsertWithEscape(key, path, index, objects)); + } + + @Override + public Response jsonArrInsert(String key, Path path, int index, Object... pojos) { + return appendCommand(commandObjects.jsonArrInsert(key, path, index, pojos)); + } + + @Override + public Response jsonArrPop(String key) { + return appendCommand(commandObjects.jsonArrPop(key)); + } + + @Override + public Response jsonArrLen(String key, Path path) { + return appendCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Response> jsonArrTrim(String key, Path2 path, int start, int stop) { + return appendCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Response jsonArrTrim(String key, Path path, int start, int stop) { + return appendCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Response jsonArrPop(String key, Class clazz, Path path) { + return appendCommand(commandObjects.jsonArrPop(key, clazz, path)); + } + + @Override + public Response> jsonArrPop(String key, Path2 path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Response jsonArrPop(String key, Path path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Response jsonArrPop(String key, Class clazz, Path path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, clazz, path, index)); + } + + @Override + public Response jsonArrLen(String key) { + return appendCommand(commandObjects.jsonArrLen(key)); + } + + @Override + public Response> jsonArrLen(String key, Path2 path) { + return appendCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Response jsonArrPop(String key, Class clazz) { + return appendCommand(commandObjects.jsonArrPop(key, clazz)); + } + + @Override + public Response> jsonArrPop(String key, Path2 path) { + return appendCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Response jsonArrPop(String key, Path path) { + return appendCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Response ftCreate(String indexName, IndexOptions indexOptions, Schema schema) { + return appendCommand(commandObjects.ftCreate(indexName, indexOptions, schema)); + } + + @Override + public Response ftSearch(String indexName, Query query) { + return appendCommand(commandObjects.ftSearch(indexName, query)); + } + + @Override + public Response ftSearch(byte[] indexName, Query query) { + return appendCommand(commandObjects.ftSearch(indexName, query)); + } + + public Response waitReplicas(int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(replicas, timeout)); + } + + public Response sendCommand(ProtocolCommand cmd, String... args) { + return sendCommand(new CommandArguments(cmd).addObjects((Object[]) args)); + } + + public Response sendCommand(ProtocolCommand cmd, byte[]... args) { + return sendCommand(new CommandArguments(cmd).addObjects((Object[]) args)); + } + + public Response sendCommand(CommandArguments args) { + return executeCommand(new CommandObject<>(args, BuilderFactory.RAW_OBJECT)); + } + + public Response executeCommand(CommandObject command) { + return appendCommand(command); + } } diff --git a/src/main/java/redis/clients/jedis/PipelineBase.java b/src/main/java/redis/clients/jedis/PipelineBase.java deleted file mode 100644 index a9118d1acf..0000000000 --- a/src/main/java/redis/clients/jedis/PipelineBase.java +++ /dev/null @@ -1,2459 +0,0 @@ -package redis.clients.jedis; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import redis.clients.jedis.commands.BinaryRedisPipeline; -import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.commands.RedisPipeline; -import redis.clients.jedis.params.GeoAddParams; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GetExParams; -import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.params.SetParams; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.params.ZAddParams; -import redis.clients.jedis.params.ZIncrByParams; -import redis.clients.jedis.params.LPosParams; -import redis.clients.jedis.resps.LCSMatchResult; - -public abstract class PipelineBase extends Queable implements BinaryRedisPipeline, RedisPipeline { - - protected abstract Client getClient(String key); - - protected abstract Client getClient(byte[] key); - - @Override - public Response append(final String key, final String value) { - getClient(key).append(key, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response append(final byte[] key, final byte[] value) { - getClient(key).append(key, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> blpop(final String key) { - String[] temp = new String[1]; - temp[0] = key; - getClient(key).blpop(temp); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> brpop(final String key) { - String[] temp = new String[1]; - temp[0] = key; - getClient(key).brpop(temp); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> blpop(final byte[] key) { - byte[][] temp = new byte[1][]; - temp[0] = key; - getClient(key).blpop(temp); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> brpop(final byte[] key) { - byte[][] temp = new byte[1][]; - temp[0] = key; - getClient(key).brpop(temp); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response decr(final String key) { - getClient(key).decr(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response decr(final byte[] key) { - getClient(key).decr(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response decrBy(final String key, final long decrement) { - getClient(key).decrBy(key, decrement); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response decrBy(final byte[] key, final long decrement) { - getClient(key).decrBy(key, decrement); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response del(final String key) { - getClient(key).del(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response del(final byte[] key) { - getClient(key).del(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response unlink(final String key) { - getClient(key).unlink(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response unlink(final byte[] key) { - getClient(key).unlink(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response echo(final String string) { - getClient(string).echo(string); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response echo(final byte[] string) { - getClient(string).echo(string); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response exists(final String key) { - getClient(key).exists(key); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response exists(final byte[] key) { - getClient(key).exists(key); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response expire(final String key, final long seconds) { - getClient(key).expire(key, seconds); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response expire(final byte[] key, final long seconds) { - getClient(key).expire(key, seconds); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response expireAt(final String key, final long unixTime) { - getClient(key).expireAt(key, unixTime); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response expireAt(final byte[] key, final long unixTime) { - getClient(key).expireAt(key, unixTime); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response get(final String key) { - getClient(key).get(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response get(final byte[] key) { - getClient(key).get(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response getDel(final String key) { - getClient(key).getDel(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response getDel(final byte[] key) { - getClient(key).getDel(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response getEx(String key, GetExParams params) { - getClient(key).getEx(key, params); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response getEx(byte[] key, GetExParams params) { - getClient(key).getEx(key, params); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response getbit(final String key, final long offset) { - getClient(key).getbit(key, offset); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response getbit(final byte[] key, final long offset) { - getClient(key).getbit(key, offset); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response bitpos(final String key, final boolean value) { - return bitpos(key, value, new BitPosParams()); - } - - @Override - public Response bitpos(final String key, final boolean value, final BitPosParams params) { - getClient(key).bitpos(key, value, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bitpos(final byte[] key, final boolean value) { - return bitpos(key, value, new BitPosParams()); - } - - @Override - public Response bitpos(final byte[] key, final boolean value, final BitPosParams params) { - getClient(key).bitpos(key, value, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response getrange(final String key, final long startOffset, final long endOffset) { - getClient(key).getrange(key, startOffset, endOffset); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response getSet(final String key, final String value) { - getClient(key).getSet(key, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response getSet(final byte[] key, final byte[] value) { - getClient(key).getSet(key, value); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response getrange(final byte[] key, final long startOffset, final long endOffset) { - getClient(key).getrange(key, startOffset, endOffset); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response hdel(final String key, final String... field) { - getClient(key).hdel(key, field); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hdel(final byte[] key, final byte[]... field) { - getClient(key).hdel(key, field); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hexists(final String key, final String field) { - getClient(key).hexists(key, field); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response hexists(final byte[] key, final byte[] field) { - getClient(key).hexists(key, field); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response hget(final String key, final String field) { - getClient(key).hget(key, field); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response hget(final byte[] key, final byte[] field) { - getClient(key).hget(key, field); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> hgetAll(final String key) { - getClient(key).hgetAll(key); - return getResponse(BuilderFactory.STRING_MAP); - } - - @Override - public Response> hgetAll(final byte[] key) { - getClient(key).hgetAll(key); - return getResponse(BuilderFactory.BYTE_ARRAY_MAP); - } - - @Override - public Response hincrBy(final String key, final String field, final long value) { - getClient(key).hincrBy(key, field, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hincrBy(final byte[] key, final byte[] field, final long value) { - getClient(key).hincrBy(key, field, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> hkeys(final String key) { - getClient(key).hkeys(key); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response> hkeys(final byte[] key) { - getClient(key).hkeys(key); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response hlen(final String key) { - getClient(key).hlen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hlen(final byte[] key) { - getClient(key).hlen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> hmget(final String key, final String... fields) { - getClient(key).hmget(key, fields); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> hmget(final byte[] key, final byte[]... fields) { - getClient(key).hmget(key, fields); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response hmset(final String key, final Map hash) { - getClient(key).hmset(key, hash); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response hmset(final byte[] key, final Map hash) { - getClient(key).hmset(key, hash); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response hset(final String key, final String field, final String value) { - getClient(key).hset(key, field, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hset(final byte[] key, final byte[] field, final byte[] value) { - getClient(key).hset(key, field, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hset(final String key, final Map hash) { - getClient(key).hset(key, hash); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hset(final byte[] key, final Map hash) { - getClient(key).hset(key, hash); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hsetnx(final String key, final String field, final String value) { - getClient(key).hsetnx(key, field, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hsetnx(final byte[] key, final byte[] field, final byte[] value) { - getClient(key).hsetnx(key, field, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> hvals(final String key) { - getClient(key).hvals(key); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> hvals(final byte[] key) { - getClient(key).hvals(key); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response hrandfield(final byte[] key) { - getClient(key).hrandfield(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> hrandfield(final byte[] key, final long count) { - getClient(key).hrandfield(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> hrandfieldWithValues(final byte[] key, final long count) { - getClient(key).hrandfieldWithValues(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_MAP); - } - - @Override - public Response hrandfield(final String key) { - getClient(key).hrandfield(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> hrandfield(final String key, final long count) { - getClient(key).hrandfield(key, count); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> hrandfieldWithValues(final String key, final long count) { - getClient(key).hrandfieldWithValues(key, count); - return getResponse(BuilderFactory.STRING_MAP); - } - - @Override - public Response incr(final String key) { - getClient(key).incr(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response incr(final byte[] key) { - getClient(key).incr(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response incrBy(final String key, final long increment) { - getClient(key).incrBy(key, increment); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response incrBy(final byte[] key, final long increment) { - getClient(key).incrBy(key, increment); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lindex(final String key, final long index) { - getClient(key).lindex(key, index); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response lindex(final byte[] key, final long index) { - getClient(key).lindex(key, index); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response linsert(final String key, final ListPosition where, final String pivot, - final String value) { - getClient(key).linsert(key, where, pivot, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response linsert(final byte[] key, final ListPosition where, final byte[] pivot, - final byte[] value) { - getClient(key).linsert(key, where, pivot, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response llen(final String key) { - getClient(key).llen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response llen(final byte[] key) { - getClient(key).llen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpop(final String key) { - getClient(key).lpop(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response lpop(final byte[] key) { - getClient(key).lpop(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> lpop(final String key, final int count) { - getClient(key).lpop(key, count); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> lpop(final byte[] key, final int count) { - getClient(key).lpop(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response lpos(final String key, final String element) { - getClient(key).lpos(key, element); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpos(final byte[] key, final byte[] element) { - getClient(key).lpos(key, element); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpos(final String key, final String element, final LPosParams params) { - getClient(key).lpos(key, element, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpos(final byte[] key, final byte[] element, final LPosParams params) { - getClient(key).lpos(key, element, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> lpos(final String key, final String element, final LPosParams params, - final long count) { - getClient(key).lpos(key, element, params, count); - return getResponse(BuilderFactory.LONG_LIST); - } - - @Override - public Response> lpos(final byte[] key, final byte[] element, final LPosParams params, - final long count) { - getClient(key).lpos(key, element, params, count); - return getResponse(BuilderFactory.LONG_LIST); - } - - @Override - public Response lpush(final String key, final String... string) { - getClient(key).lpush(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpush(final byte[] key, final byte[]... string) { - getClient(key).lpush(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpushx(final String key, final String... string) { - getClient(key).lpushx(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lpushx(final byte[] key, final byte[]... bytes) { - getClient(key).lpushx(key, bytes); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> lrange(final String key, final long start, final long stop) { - getClient(key).lrange(key, start, stop); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> lrange(final byte[] key, final long start, final long stop) { - getClient(key).lrange(key, start, stop); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response lrem(final String key, final long count, final String value) { - getClient(key).lrem(key, count, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lrem(final byte[] key, final long count, final byte[] value) { - getClient(key).lrem(key, count, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response lset(final String key, final long index, final String value) { - getClient(key).lset(key, index, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response lset(final byte[] key, final long index, final byte[] value) { - getClient(key).lset(key, index, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response ltrim(final String key, final long start, final long stop) { - getClient(key).ltrim(key, start, stop); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response ltrim(final byte[] key, final long start, final long stop) { - getClient(key).ltrim(key, start, stop); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response move(final String key, final int dbIndex) { - getClient(key).move(key, dbIndex); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response move(final byte[] key, final int dbIndex) { - getClient(key).move(key, dbIndex); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response persist(final String key) { - getClient(key).persist(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response persist(final byte[] key) { - getClient(key).persist(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response rpop(final String key) { - getClient(key).rpop(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response rpop(final byte[] key) { - getClient(key).rpop(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> rpop(final String key, final int count) { - getClient(key).rpop(key, count); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> rpop(final byte[] key, final int count) { - getClient(key).rpop(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response rpush(final String key, final String... string) { - getClient(key).rpush(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response rpush(final byte[] key, final byte[]... string) { - getClient(key).rpush(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response rpushx(final String key, final String... string) { - getClient(key).rpushx(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response rpushx(final byte[] key, final byte[]... string) { - getClient(key).rpushx(key, string); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sadd(final String key, final String... member) { - getClient(key).sadd(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sadd(final byte[] key, final byte[]... member) { - getClient(key).sadd(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response scard(final String key) { - getClient(key).scard(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response scard(final byte[] key) { - getClient(key).scard(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response set(final String key, final String value) { - getClient(key).set(key, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response set(final byte[] key, final byte[] value) { - getClient(key).set(key, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response set(final String key, final String value, SetParams params) { - getClient(key).set(key, value, params); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response set(final byte[] key, final byte[] value, SetParams params) { - getClient(key).set(key, value, params); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response setbit(final String key, final long offset, boolean value) { - getClient(key).setbit(key, offset, value); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response setbit(final byte[] key, final long offset, final byte[] value) { - getClient(key).setbit(key, offset, value); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response setex(final String key, final long seconds, final String value) { - getClient(key).setex(key, seconds, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response setex(final byte[] key, final long seconds, final byte[] value) { - getClient(key).setex(key, seconds, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response setnx(final String key, final String value) { - getClient(key).setnx(key, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response setnx(final byte[] key, final byte[] value) { - getClient(key).setnx(key, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response setrange(final String key, final long offset, final String value) { - getClient(key).setrange(key, offset, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response setrange(final byte[] key, final long offset, final byte[] value) { - getClient(key).setrange(key, offset, value); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response sismember(final String key, final String member) { - getClient(key).sismember(key, member); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response> smismember(final String key, final String... members) { - getClient(key).smismember(key, members); - return getResponse(BuilderFactory.BOOLEAN_LIST); - } - - @Override - public Response sismember(final byte[] key, final byte[] member) { - getClient(key).sismember(key, member); - return getResponse(BuilderFactory.BOOLEAN); - } - - @Override - public Response> smismember(final byte[] key, final byte[]... members) { - getClient(key).smismember(key, members); - return getResponse(BuilderFactory.BOOLEAN_LIST); - } - - @Override - public Response> smembers(final String key) { - getClient(key).smembers(key); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response> smembers(final byte[] key) { - getClient(key).smembers(key); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> sort(final String key) { - getClient(key).sort(key); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> sort(final byte[] key) { - getClient(key).sort(key); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> sort(final String key, final SortingParams sortingParameters) { - getClient(key).sort(key, sortingParameters); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> sort(final byte[] key, final SortingParams sortingParameters) { - getClient(key).sort(key, sortingParameters); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response spop(final String key) { - getClient(key).spop(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> spop(final String key, final long count) { - getClient(key).spop(key, count); - return getResponse(BuilderFactory.STRING_SET); - } - - @Override - public Response spop(final byte[] key) { - getClient(key).spop(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> spop(final byte[] key, final long count) { - getClient(key).spop(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response srandmember(final String key) { - getClient(key).srandmember(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> srandmember(final String key, final int count) { - getClient(key).srandmember(key, count); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response srandmember(final byte[] key) { - getClient(key).srandmember(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> srandmember(final byte[] key, final int count) { - getClient(key).srandmember(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response srem(final String key, final String... member) { - getClient(key).srem(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response srem(final byte[] key, final byte[]... member) { - getClient(key).srem(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response strlen(final String key) { - getClient(key).strlen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response strlen(final byte[] key) { - getClient(key).strlen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response substr(final String key, final int start, final int end) { - getClient(key).substr(key, start, end); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response substr(final byte[] key, final int start, final int end) { - getClient(key).substr(key, start, end); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response touch(final String key) { - getClient(key).touch(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response touch(final byte[] key) { - getClient(key).touch(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response ttl(final String key) { - getClient(key).ttl(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response ttl(final byte[] key) { - getClient(key).ttl(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response type(final String key) { - getClient(key).type(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response type(final byte[] key) { - getClient(key).type(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response zadd(final String key, final double score, final String member) { - getClient(key).zadd(key, score, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final String key, final double score, final String member, - final ZAddParams params) { - getClient(key).zadd(key, score, member, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final String key, final Map scoreMembers) { - getClient(key).zadd(key, scoreMembers); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final String key, final Map scoreMembers, - final ZAddParams params) { - getClient(key).zadd(key, scoreMembers, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final byte[] key, final double score, final byte[] member) { - getClient(key).zadd(key, score, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final byte[] key, final double score, final byte[] member, - final ZAddParams params) { - getClient(key).zadd(key, score, member, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final byte[] key, final Map scoreMembers) { - getClient(key).zadd(key, scoreMembers); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zadd(final byte[] key, final Map scoreMembers, - final ZAddParams params) { - getClient(key).zadd(key, scoreMembers, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zaddIncr(String key, double score, String member, ZAddParams params) { - getClient(key).zaddIncr(key, score, member, params); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { - getClient(key).zaddIncr(key, score, member, params); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response zcard(final String key) { - getClient(key).zcard(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zcard(final byte[] key) { - getClient(key).zcard(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zcount(final String key, final double min, final double max) { - getClient(key).zcount(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zcount(final String key, final String min, final String max) { - getClient(key).zcount(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zcount(final byte[] key, final double min, final double max) { - getClient(key).zcount(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zcount(final byte[] key, final byte[] min, final byte[] max) { - getClient(key).zcount(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zincrby(final String key, final double increment, final String member) { - getClient(key).zincrby(key, increment, member); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response zincrby(final String key, final double increment, final String member, - ZIncrByParams params) { - getClient(key).zincrby(key, increment, member, params); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response zincrby(final byte[] key, final double increment, final byte[] member) { - getClient(key).zincrby(key, increment, member); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response zincrby(final byte[] key, final double increment, final byte[] member, - ZIncrByParams params) { - getClient(key).zincrby(key, increment, member); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response> zrange(final String key, final long start, final long stop) { - getClient(key).zrange(key, start, stop); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrange(final byte[] key, final long start, final long stop) { - getClient(key).zrange(key, start, stop); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByScore(final String key, final double min, final double max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrangeByScore(final byte[] key, final double min, final double max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByScore(final String key, final String min, final String max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - getClient(key).zrangeByScore(key, min, max); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByScore(final String key, final double min, final double max, - final int offset, final int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrangeByScore(final String key, final String min, final String max, - final int offset, final int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrangeByScore(final byte[] key, final double min, final double max, - final int offset, final int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByScore(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - getClient(key).zrangeByScore(key, min, max, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final String key, final double min, - final double max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final String key, final String min, - final String max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final byte[] key, final double min, - final double max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final byte[] key, final byte[] min, - final byte[] max) { - getClient(key).zrangeByScoreWithScores(key, min, max); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final String key, final double min, - final double max, final int offset, final int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final String key, final String min, - final String max, final int offset, final int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final byte[] key, final double min, - final double max, final int offset, final int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeByScoreWithScores(final byte[] key, final byte[] min, - final byte[] max, final int offset, final int count) { - getClient(key).zrangeByScoreWithScores(key, min, max, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScore(final String key, final double max, final double min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrangeByScore(final byte[] key, final double max, final double min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeByScore(final String key, final String max, final String min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrangeByScore(final byte[] key, final byte[] max, final byte[] min) { - getClient(key).zrevrangeByScore(key, max, min); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeByScore(final String key, final double max, - final double min, final int offset, final int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrangeByScore(final String key, final String max, - final String min, final int offset, final int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrangeByScore(final byte[] key, final double max, - final double min, final int offset, final int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeByScore(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { - getClient(key).zrevrangeByScore(key, max, min, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final String key, final double max, - final double min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final String key, final String max, - final String min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, - final byte[] min) { - getClient(key).zrevrangeByScoreWithScores(key, max, min); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final String key, final double max, - final double min, final int offset, final int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final String key, final String max, - final String min, final int offset, final int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final byte[] key, final double max, - final double min, final int offset, final int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeByScoreWithScores(final byte[] key, final byte[] max, - final byte[] min, final int offset, final int count) { - getClient(key).zrevrangeByScoreWithScores(key, max, min, offset, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeWithScores(final String key, final long start, final long stop) { - getClient(key).zrangeWithScores(key, start, stop); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrangeWithScores(final byte[] key, final long start, final long stop) { - getClient(key).zrangeWithScores(key, start, stop); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zrank(final String key, final String member) { - getClient(key).zrank(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zrank(final byte[] key, final byte[] member) { - getClient(key).zrank(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zrem(final String key, final String... members) { - getClient(key).zrem(key, members); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zrem(final byte[] key, final byte[]... members) { - getClient(key).zrem(key, members); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByRank(final String key, final long start, final long stop) { - getClient(key).zremrangeByRank(key, start, stop); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByRank(final byte[] key, final long start, final long stop) { - getClient(key).zremrangeByRank(key, start, stop); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByScore(final String key, final double min, final double max) { - getClient(key).zremrangeByScore(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByScore(final String key, final String min, final String max) { - getClient(key).zremrangeByScore(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByScore(final byte[] key, final double min, final double max) { - getClient(key).zremrangeByScore(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByScore(final byte[] key, final byte[] min, final byte[] max) { - getClient(key).zremrangeByScore(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> zrevrange(final String key, final long start, final long stop) { - getClient(key).zrevrange(key, start, stop); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrange(final byte[] key, final long start, final long stop) { - getClient(key).zrevrange(key, start, stop); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeWithScores(final String key, final long start, - final long stop) { - getClient(key).zrevrangeWithScores(key, start, stop); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zrevrangeWithScores(final byte[] key, final long start, - final long stop) { - getClient(key).zrevrangeWithScores(key, start, stop); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zrandmember(final byte[] key) { - getClient(key).zrandmember(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response> zrandmember(final byte[] key, final long count) { - getClient(key).zrandmember(key, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrandmemberWithScores(final byte[] key, final long count) { - getClient(key).zrandmemberWithScores(key, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zrandmember(final String key) { - getClient(key).zrandmember(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response> zrandmember(final String key, final long count) { - getClient(key).zrandmember(key, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrandmemberWithScores(final String key, final long count) { - getClient(key).zrandmemberWithScores(key, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zrevrank(final String key, final String member) { - getClient(key).zrevrank(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zrevrank(final byte[] key, final byte[] member) { - getClient(key).zrevrank(key, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zscore(final String key, final String member) { - getClient(key).zscore(key, member); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response> zmscore(final String key, final String... members) { - getClient(key).zmscore(key, members); - return getResponse(BuilderFactory.DOUBLE_LIST); - } - - @Override - public Response zscore(final byte[] key, final byte[] member) { - getClient(key).zscore(key, member); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response> zmscore(final byte[] key, final byte[]... members) { - getClient(key).zmscore(key, members); - return getResponse(BuilderFactory.DOUBLE_LIST); - } - - @Override - public Response zpopmax(final String key) { - getClient(key).zpopmax(key); - return getResponse(BuilderFactory.TUPLE); - } - - @Override - public Response zpopmax(final byte[] key) { - getClient(key).zpopmax(key); - return getResponse(BuilderFactory.TUPLE); - } - - @Override - public Response> zpopmax(final String key, final int count) { - getClient(key).zpopmax(key, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zpopmax(final byte[] key, final int count) { - getClient(key).zpopmax(key, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zpopmin(final String key) { - getClient(key).zpopmin(key); - return getResponse(BuilderFactory.TUPLE); - } - - @Override - public Response zpopmin(final byte[] key) { - getClient(key).zpopmin(key); - return getResponse(BuilderFactory.TUPLE); - } - - @Override - public Response> zpopmin(final byte[] key, final int count) { - getClient(key).zpopmin(key, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response> zpopmin(final String key, final int count) { - getClient(key).zpopmin(key, count); - return getResponse(BuilderFactory.TUPLE_ZSET); - } - - @Override - public Response zlexcount(final byte[] key, final byte[] min, final byte[] max) { - getClient(key).zlexcount(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zlexcount(final String key, final String min, final String max) { - getClient(key).zlexcount(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> zrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - getClient(key).zrangeByLex(key, min, max); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByLex(final String key, final String min, final String max) { - getClient(key).zrangeByLex(key, min, max); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrangeByLex(final byte[] key, final byte[] min, final byte[] max, - final int offset, final int count) { - getClient(key).zrangeByLex(key, min, max, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrangeByLex(final String key, final String min, final String max, - final int offset, final int count) { - getClient(key).zrangeByLex(key, min, max, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min) { - getClient(key).zrevrangeByLex(key, max, min); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeByLex(final String key, final String max, final String min) { - getClient(key).zrevrangeByLex(key, max, min); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response> zrevrangeByLex(final byte[] key, final byte[] max, final byte[] min, - final int offset, final int count) { - getClient(key).zrevrangeByLex(key, max, min, offset, count); - return getResponse(BuilderFactory.BYTE_ARRAY_ZSET); - } - - @Override - public Response> zrevrangeByLex(final String key, final String max, final String min, - final int offset, final int count) { - getClient(key).zrevrangeByLex(key, max, min, offset, count); - return getResponse(BuilderFactory.STRING_ZSET); - } - - @Override - public Response zremrangeByLex(final byte[] key, final byte[] min, final byte[] max) { - getClient(key).zremrangeByLex(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response zremrangeByLex(final String key, final String min, final String max) { - getClient(key).zremrangeByLex(key, min, max); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bitcount(final String key) { - getClient(key).bitcount(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bitcount(final String key, final long start, final long end) { - getClient(key).bitcount(key, start, end); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bitcount(final byte[] key) { - getClient(key).bitcount(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response bitcount(final byte[] key, final long start, final long end) { - getClient(key).bitcount(key, start, end); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response dump(final String key) { - getClient(key).dump(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response dump(final byte[] key) { - getClient(key).dump(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response migrate(final String host, final int port, final String key, - final int destinationDb, final int timeout) { - getClient(key).migrate(host, port, key, destinationDb, timeout); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response migrate(final String host, final int port, final byte[] key, - final int destinationDb, final int timeout) { - getClient(key).migrate(host, port, key, destinationDb, timeout); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response objectRefcount(final String key) { - getClient(key).objectRefcount(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response objectRefcount(final byte[] key) { - getClient(key).objectRefcount(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response objectEncoding(final String key) { - getClient(key).objectEncoding(key); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response objectEncoding(final byte[] key) { - getClient(key).objectEncoding(key); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response objectIdletime(final String key) { - getClient(key).objectIdletime(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response objectIdletime(final byte[] key) { - getClient(key).objectIdletime(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response objectFreq(byte[] key) { - getClient(key).objectFreq(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response objectFreq(String key) { - getClient(key).objectFreq(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pexpire(final String key, final long milliseconds) { - getClient(key).pexpire(key, milliseconds); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pexpire(final byte[] key, final long milliseconds) { - getClient(key).pexpire(key, milliseconds); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pexpireAt(final String key, final long millisecondsTimestamp) { - getClient(key).pexpireAt(key, millisecondsTimestamp); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pexpireAt(final byte[] key, final long millisecondsTimestamp) { - getClient(key).pexpireAt(key, millisecondsTimestamp); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pttl(final String key) { - getClient(key).pttl(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pttl(final byte[] key) { - getClient(key).pttl(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response restore(final String key, final long ttl, final byte[] serializedValue) { - getClient(key).restore(key, ttl, serializedValue); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response restore(final byte[] key, final long ttl, final byte[] serializedValue) { - getClient(key).restore(key, ttl, serializedValue); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response restoreReplace(final String key, final long ttl, - final byte[] serializedValue) { - getClient(key).restoreReplace(key, ttl, serializedValue); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response restoreReplace(final byte[] key, final long ttl, - final byte[] serializedValue) { - getClient(key).restoreReplace(key, ttl, serializedValue); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response restore(final byte[] key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - getClient(key).restore(key, ttl, serializedValue, params); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response restore(final String key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - getClient(key).restore(key, ttl, serializedValue, params); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response incrByFloat(final String key, final double increment) { - getClient(key).incrByFloat(key, increment); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response incrByFloat(final byte[] key, final double increment) { - getClient(key).incrByFloat(key, increment); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response psetex(final String key, final long milliseconds, final String value) { - getClient(key).psetex(key, milliseconds, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response psetex(final byte[] key, final long milliseconds, final byte[] value) { - getClient(key).psetex(key, milliseconds, value); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response hincrByFloat(final String key, final String field, final double increment) { - getClient(key).hincrByFloat(key, field, increment); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response hincrByFloat(final byte[] key, final byte[] field, final double increment) { - getClient(key).hincrByFloat(key, field, increment); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response pfadd(final byte[] key, final byte[]... elements) { - getClient(key).pfadd(key, elements); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pfcount(final byte[] key) { - getClient(key).pfcount(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pfadd(final String key, final String... elements) { - getClient(key).pfadd(key, elements); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response pfcount(final String key) { - getClient(key).pfcount(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geoadd(final byte[] key, final double longitude, final double latitude, - final byte[] member) { - getClient(key).geoadd(key, longitude, latitude, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geoadd(final byte[] key, - final Map memberCoordinateMap) { - getClient(key).geoadd(key, memberCoordinateMap); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geoadd(final String key, final double longitude, final double latitude, - final String member) { - getClient(key).geoadd(key, longitude, latitude, member); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geoadd(final String key, - final Map memberCoordinateMap) { - getClient(key).geoadd(key, memberCoordinateMap); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { - getClient(key).geoadd(key, params, memberCoordinateMap); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { - getClient(key).geoadd(key, params, memberCoordinateMap); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response geodist(final byte[] key, final byte[] member1, final byte[] member2) { - getClient(key).geodist(key, member1, member2); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response geodist(final byte[] key, final byte[] member1, final byte[] member2, - final GeoUnit unit) { - getClient(key).geodist(key, member1, member2, unit); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response geodist(final String key, final String member1, final String member2) { - getClient(key).geodist(key, member1, member2); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { - getClient(key).geodist(key, member1, member2); - return getResponse(BuilderFactory.DOUBLE); - } - - @Override - public Response> geohash(final byte[] key, final byte[]... members) { - getClient(key).geohash(key, members); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> geohash(final String key, final String... members) { - getClient(key).geohash(key, members); - return getResponse(BuilderFactory.STRING_LIST); - } - - @Override - public Response> geopos(final byte[] key, final byte[]... members) { - getClient(key).geopos(key, members); - return getResponse(BuilderFactory.GEO_COORDINATE_LIST); - } - - @Override - public Response> geopos(final String key, final String... members) { - getClient(key).geopos(key, members); - return getResponse(BuilderFactory.GEO_COORDINATE_LIST); - } - - @Override - public Response> georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - getClient(key).georadius(key, longitude, latitude, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusReadonly(final byte[] key, - final double longitude, final double latitude, final double radius, final GeoUnit unit) { - getClient(key).georadiusReadonly(key, longitude, latitude, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadius(final byte[] key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - getClient(key).georadius(key, longitude, latitude, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusReadonly(final byte[] key, - final double longitude, final double latitude, final double radius, final GeoUnit unit, - final GeoRadiusParam param) { - getClient(key).georadiusReadonly(key, longitude, latitude, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - getClient(key).georadius(key, longitude, latitude, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusReadonly(final String key, - final double longitude, final double latitude, final double radius, final GeoUnit unit) { - getClient(key).georadiusReadonly(key, longitude, latitude, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - getClient(key).georadius(key, longitude, latitude, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusReadonly(final String key, - final double longitude, final double latitude, final double radius, final GeoUnit unit, - final GeoRadiusParam param) { - getClient(key).georadiusReadonly(key, longitude, latitude, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit) { - getClient(key).georadiusByMember(key, member, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMemberReadonly(final byte[] key, - final byte[] member, final double radius, final GeoUnit unit) { - getClient(key).georadiusByMemberReadonly(key, member, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMember(final byte[] key, final byte[] member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - getClient(key).georadiusByMember(key, member, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMemberReadonly(final byte[] key, - final byte[] member, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - getClient(key).georadiusByMemberReadonly(key, member, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit) { - getClient(key).georadiusByMember(key, member, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMemberReadonly(final String key, - final String member, final double radius, final GeoUnit unit) { - getClient(key).georadiusByMemberReadonly(key, member, radius, unit); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - getClient(key).georadiusByMember(key, member, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> georadiusByMemberReadonly(final String key, - final String member, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - getClient(key).georadiusByMemberReadonly(key, member, radius, unit, param); - return getResponse(BuilderFactory.GEORADIUS_WITH_PARAMS_RESULT); - } - - @Override - public Response> bitfield(final String key, final String... elements) { - getClient(key).bitfield(key, elements); - return getResponse(BuilderFactory.LONG_LIST); - } - - @Override - public Response> bitfield(final byte[] key, final byte[]... elements) { - getClient(key).bitfield(key, elements); - return getResponse(BuilderFactory.LONG_LIST); - } - - @Override - public Response> bitfieldReadonly(byte[] key, final byte[]... arguments) { - getClient(key).bitfieldReadonly(key, arguments); - return getResponse(BuilderFactory.LONG_LIST); - } - - @Override - public Response> bitfieldReadonly(String key, final String... arguments) { - getClient(key).bitfieldReadonly(key, arguments); - return getResponse(BuilderFactory.LONG_LIST); - } - - @Override - public Response hstrlen(final String key, final String field) { - getClient(key).hstrlen(key, field); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response hstrlen(final byte[] key, final byte[] field) { - getClient(key).hstrlen(key, field); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xadd(String key, StreamEntryID id, Map hash) { - return xadd(key, id, hash, Long.MAX_VALUE, true); - } - - @Override - public Response xadd(byte[] key, byte[] id, Map hash) { - return xadd(key, id, hash, Long.MAX_VALUE, true); - } - - @Override - public Response xadd(String key, StreamEntryID id, Map hash, - long maxLen, boolean approximateLength) { - getClient(key).xadd(key, id, hash, maxLen, approximateLength); - return getResponse(BuilderFactory.STREAM_ENTRY_ID); - } - - @Override - public Response xadd(byte[] key, byte[] id, Map hash, long maxLen, - boolean approximateLength) { - getClient(key).xadd(key, id, hash, maxLen, approximateLength); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response xadd(final byte[] key, final Map hash, final XAddParams params) { - getClient(key).xadd(key, hash, params); - return getResponse(BuilderFactory.BYTE_ARRAY); - } - - @Override - public Response xadd(final String key, final Map hash, final XAddParams params) { - getClient(key).xadd(key, hash, params); - return getResponse(BuilderFactory.STREAM_ENTRY_ID); - } - - @Override - public Response xlen(String key) { - getClient(key).xlen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xlen(byte[] key) { - getClient(key).xlen(key); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> xrange(String key, StreamEntryID start, StreamEntryID end) { - getClient(key).xrange(key, start, end); - return getResponse(BuilderFactory.STREAM_ENTRY_LIST); - } - - @Override - public Response> xrange(byte[] key, byte[] start, byte[] end) { - getClient(key).xrange(key, start, end); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xrange(String key, StreamEntryID start, StreamEntryID end, - int count) { - getClient(key).xrange(key, start, end, count); - return getResponse(BuilderFactory.STREAM_ENTRY_LIST); - } - - @Override - public Response> xrange(byte[] key, byte[] start, byte[] end, int count) { - getClient(key).xrange(key, start, end, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start) { - getClient(key).xrevrange(key, end, start); - return getResponse(BuilderFactory.STREAM_ENTRY_LIST); - } - - @Override - public Response> xrevrange(byte[] key, byte[] end, byte[] start) { - getClient(key).xrevrange(key, end, start); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, - int count) { - getClient(key).xrevrange(key, end, start, count); - return getResponse(BuilderFactory.STREAM_ENTRY_LIST); - } - - @Override - public Response> xrevrange(byte[] key, byte[] end, byte[] start, int count) { - getClient(key).xrevrange(key, end, start, count); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response xack(String key, String group, StreamEntryID... ids) { - getClient(key).xack(key, group, ids); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xack(byte[] key, byte[] group, byte[]... ids) { - getClient(key).xack(key, group, ids); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xgroupCreate(String key, String groupname, StreamEntryID id, - boolean makeStream) { - getClient(key).xgroupCreate(key, groupname, id, makeStream); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream) { - getClient(key).xgroupCreate(key, groupname, id, makeStream); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response xgroupSetID(String key, String groupname, StreamEntryID id) { - getClient(key).xgroupSetID(key, groupname, id); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response xgroupSetID(byte[] key, byte[] groupname, byte[] id) { - getClient(key).xgroupSetID(key, groupname, id); - return getResponse(BuilderFactory.STRING); - } - - @Override - public Response xgroupDestroy(String key, String groupname) { - getClient(key).xgroupDestroy(key, groupname); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xgroupDestroy(byte[] key, byte[] groupname) { - getClient(key).xgroupDestroy(key, groupname); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xgroupDelConsumer(String key, String groupname, String consumername) { - getClient(key).xgroupDelConsumer(key, groupname, consumername); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumername) { - getClient(key).xgroupDelConsumer(key, groupname, consumername); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xpending(String key, String groupname) { - getClient(key).xpending(key, groupname); - return getResponse(BuilderFactory.STREAM_PENDING_SUMMARY); - } - - @Override - public Response xpending(byte[] key, byte[] groupname) { - getClient(key).xpending(key, groupname); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - @Override - public Response> xpending(String key, String groupname, - StreamEntryID start, StreamEntryID end, int count, String consumername) { - getClient(key).xpending(key, groupname, start, end, count, consumername); - return getResponse(BuilderFactory.STREAM_PENDING_ENTRY_LIST); - } - - @Override - public Response> xpending(byte[] key, byte[] groupname, byte[] start, - byte[] end, int count, byte[] consumername) { - getClient(key).xpending(key, groupname, start, end, count, consumername); - return getResponse(BuilderFactory.STREAM_PENDING_ENTRY_LIST); - } - - @Override - public Response> xpendingBinary(byte[] key, byte[] groupname, byte[] start, - byte[] end, int count, byte[] consumername) { - getClient(key).xpending(key, groupname, start, end, count, consumername); - return getResponse(BuilderFactory.RAW_OBJECT_LIST); - } - - @Override - public Response> xpending(byte[] key, byte[] groupname, XPendingParams params) { - getClient(key).xpending(key, groupname, params); - return getResponse(BuilderFactory.RAW_OBJECT_LIST); - } - - @Override - public Response> xpending(String key, String groupname, XPendingParams params) { - getClient(key).xpending(key, groupname, params); - return getResponse(BuilderFactory.STREAM_PENDING_ENTRY_LIST); - } - - @Override - public Response xdel(String key, StreamEntryID... ids) { - getClient(key).xdel(key, ids); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xdel(byte[] key, byte[]... ids) { - getClient(key).xdel(key, ids); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xtrim(String key, long maxLen, boolean approximateLength) { - getClient(key).xtrim(key, maxLen, approximateLength); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xtrim(byte[] key, long maxLen, boolean approximateLength) { - getClient(key).xtrim(key, maxLen, approximateLength); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xtrim(byte[] key, XTrimParams params) { - getClient(key).xtrim(key, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response xtrim(String key, XTrimParams params) { - getClient(key).xtrim(key, params); - return getResponse(BuilderFactory.LONG); - } - - @Override - public Response> xclaim(String key, String group, String consumername, - long minIdleTime, long newIdleTime, int retries, boolean force, StreamEntryID... ids) { - getClient(key).xclaim(key, group, consumername, minIdleTime, newIdleTime, retries, force, ids); - return getResponse(BuilderFactory.STREAM_ENTRY_LIST); - } - - @Override - public Response> xclaim(byte[] key, byte[] group, byte[] consumername, - long minIdleTime, long newIdleTime, int retries, boolean force, byte[]... ids) { - getClient(key).xclaim(key, group, consumername, minIdleTime, newIdleTime, retries, force, ids); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xclaim(String key, String group, String consumername, - long minIdleTime, XClaimParams params, StreamEntryID... ids) { - getClient(key).xclaim(key, group, consumername, minIdleTime, params, ids); - return getResponse(BuilderFactory.STREAM_ENTRY_LIST); - } - - @Override - public Response> xclaim(byte[] key, byte[] group, byte[] consumername, - long minIdleTime, XClaimParams params, byte[]... ids) { - getClient(key).xclaim(key, group, consumername, minIdleTime, params, ids); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response> xclaimJustId(String key, String group, String consumername, - long minIdleTime, XClaimParams params, StreamEntryID... ids) { - getClient(key).xclaimJustId(key, group, consumername, minIdleTime, params, ids); - return getResponse(BuilderFactory.STREAM_ENTRY_ID_LIST); - } - - @Override - public Response> xclaimJustId(byte[] key, byte[] group, byte[] consumername, - long minIdleTime, XClaimParams params, byte[]... ids) { - getClient(key).xclaimJustId(key, group, consumername, minIdleTime, params, ids); - return getResponse(BuilderFactory.BYTE_ARRAY_LIST); - } - - @Override - public Response>> xautoclaim(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params) { - getClient(key).xautoclaim(key, group, consumerName, minIdleTime, start, params); - return getResponse(BuilderFactory.STREAM_AUTO_CLAIM_RESPONSE); - } - - @Override - public Response> xautoclaim(byte[] key, byte[] group, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - getClient(key).xautoclaim(key, group, consumerName, minIdleTime, start, params); - return getResponse(BuilderFactory.RAW_OBJECT_LIST); - } - - @Override - public Response>> xautoclaimJustId(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params) { - getClient(key).xautoclaimJustId(key, group, consumerName, minIdleTime, start, params); - return getResponse(BuilderFactory.STREAM_AUTO_CLAIM_ID_RESPONSE); - } - - @Override - public Response> xautoclaimJustId(byte[] key, byte[] group, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params) { - getClient(key).xautoclaimJustId(key, group, consumerName, minIdleTime, start, params); - return getResponse(BuilderFactory.RAW_OBJECT_LIST); - } - - public Response sendCommand(final String sampleKey, final ProtocolCommand cmd, - final String... args) { - getClient(sampleKey).sendCommand(cmd, args); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - public Response sendCommand(final byte[] sampleKey, final ProtocolCommand cmd, - final byte[]... args) { - getClient(sampleKey).sendCommand(cmd, args); - return getResponse(BuilderFactory.RAW_OBJECT); - } - - @Override - public Response strAlgoLCSStrings(final String strA, final String strB, - final StrAlgoLCSParams params) { - getClient("").strAlgoLCSStrings(strA, strB, params); - return getResponse(BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); - } - - @Override - public Response strAlgoLCSStrings(final byte[] strA, final byte[] strB, - final StrAlgoLCSParams params) { - getClient("").strAlgoLCSStrings(strA, strB, params); - return getResponse(BuilderFactory.STR_ALGO_LCS_RESULT_BUILDER); - } -} diff --git a/src/main/java/redis/clients/jedis/Protocol.java b/src/main/java/redis/clients/jedis/Protocol.java index 0fd5943a2e..8c4722baf9 100644 --- a/src/main/java/redis/clients/jedis/Protocol.java +++ b/src/main/java/redis/clients/jedis/Protocol.java @@ -7,29 +7,21 @@ import java.util.List; import java.util.Locale; +import redis.clients.jedis.exceptions.*; import redis.clients.jedis.args.Rawable; import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.exceptions.*; import redis.clients.jedis.util.RedisInputStream; import redis.clients.jedis.util.RedisOutputStream; import redis.clients.jedis.util.SafeEncoder; public final class Protocol { - private static final String ASK_PREFIX = "ASK "; - private static final String MOVED_PREFIX = "MOVED "; - private static final String CLUSTERDOWN_PREFIX = "CLUSTERDOWN "; - private static final String BUSY_PREFIX = "BUSY "; - private static final String NOSCRIPT_PREFIX = "NOSCRIPT "; - private static final String WRONGPASS_PREFIX = "WRONGPASS"; - private static final String NOPERM_PREFIX = "NOPERM"; - private static final String EXECABORT_PREFIX = "EXECABORT "; - - public static final String DEFAULT_HOST = "localhost"; + public static final String DEFAULT_HOST = "127.0.0.1"; public static final int DEFAULT_PORT = 6379; public static final int DEFAULT_SENTINEL_PORT = 26379; public static final int DEFAULT_TIMEOUT = 2000; public static final int DEFAULT_DATABASE = 0; + public static final int CLUSTER_HASHSLOTS = 16384; public static final Charset CHARSET = StandardCharsets.UTF_8; @@ -39,41 +31,6 @@ public final class Protocol { public static final byte MINUS_BYTE = '-'; public static final byte COLON_BYTE = ':'; - public static final String SENTINEL_MASTERS = "masters"; - public static final String SENTINEL_GET_MASTER_ADDR_BY_NAME = "get-master-addr-by-name"; - public static final String SENTINEL_RESET = "reset"; - public static final String SENTINEL_SLAVES = "slaves"; - public static final String SENTINEL_FAILOVER = "failover"; - public static final String SENTINEL_MONITOR = "monitor"; - public static final String SENTINEL_REMOVE = "remove"; - public static final String SENTINEL_SET = "set"; - - public static final String CLUSTER_NODES = "nodes"; - public static final String CLUSTER_MEET = "meet"; - public static final String CLUSTER_RESET = "reset"; - public static final String CLUSTER_ADDSLOTS = "addslots"; - public static final String CLUSTER_DELSLOTS = "delslots"; - public static final String CLUSTER_INFO = "info"; - public static final String CLUSTER_GETKEYSINSLOT = "getkeysinslot"; - public static final String CLUSTER_SETSLOT = "setslot"; - public static final String CLUSTER_SETSLOT_NODE = "node"; - public static final String CLUSTER_SETSLOT_MIGRATING = "migrating"; - public static final String CLUSTER_SETSLOT_IMPORTING = "importing"; - public static final String CLUSTER_SETSLOT_STABLE = "stable"; - public static final String CLUSTER_FORGET = "forget"; - public static final String CLUSTER_FLUSHSLOT = "flushslots"; - public static final String CLUSTER_KEYSLOT = "keyslot"; - public static final String CLUSTER_COUNTKEYINSLOT = "countkeysinslot"; - public static final String CLUSTER_SAVECONFIG = "saveconfig"; - public static final String CLUSTER_REPLICATE = "replicate"; - public static final String CLUSTER_SLAVES = "slaves"; - public static final String CLUSTER_FAILOVER = "failover"; - public static final String CLUSTER_SLOTS = "slots"; - - public static final String PUBSUB_CHANNELS = "channels"; - public static final String PUBSUB_NUMSUB = "numsub"; - public static final String PUBSUB_NUM_PAT = "numpat"; - public static final byte[] BYTES_TRUE = toByteArray(1); public static final byte[] BYTES_FALSE = toByteArray(0); public static final byte[] BYTES_TILDE = SafeEncoder.encode("~"); @@ -83,29 +40,27 @@ public final class Protocol { public static final byte[] POSITIVE_INFINITY_BYTES = "+inf".getBytes(); public static final byte[] NEGATIVE_INFINITY_BYTES = "-inf".getBytes(); + private static final String ASK_PREFIX = "ASK "; + private static final String MOVED_PREFIX = "MOVED "; + private static final String CLUSTERDOWN_PREFIX = "CLUSTERDOWN "; + private static final String BUSY_PREFIX = "BUSY "; + private static final String NOSCRIPT_PREFIX = "NOSCRIPT "; + private static final String WRONGPASS_PREFIX = "WRONGPASS"; + private static final String NOPERM_PREFIX = "NOPERM"; + private Protocol() { // this prevent the class from instantiation } - public static void sendCommand(final RedisOutputStream os, final ProtocolCommand command, - final byte[]... args) { - sendCommand(os, command.getRaw(), args); - } - - private static void sendCommand(final RedisOutputStream os, final byte[] command, - final byte[]... args) { + public static void sendCommand(final RedisOutputStream os, CommandArguments args) { try { os.write(ASTERISK_BYTE); - os.writeIntCrLf(args.length + 1); - os.write(DOLLAR_BYTE); - os.writeIntCrLf(command.length); - os.write(command); - os.writeCrLf(); - - for (final byte[] arg : args) { + os.writeIntCrLf(args.size()); + for (Rawable arg : args) { os.write(DOLLAR_BYTE); - os.writeIntCrLf(arg.length); - os.write(arg); + final byte[] bin = arg.getRaw(); + os.writeIntCrLf(bin.length); + os.write(bin); os.writeCrLf(); } } catch (IOException e) { @@ -119,12 +74,14 @@ private static void processError(final RedisInputStream is) { // Maybe Read only first 5 bytes instead? if (message.startsWith(MOVED_PREFIX)) { String[] movedInfo = parseTargetHostAndSlot(message); - throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], - Integer.parseInt(movedInfo[2])), Integer.parseInt(movedInfo[0])); +// throw new JedisMovedDataException(message, new HostAndPort(movedInfo[1], +// Integer.parseInt(movedInfo[2])), Integer.parseInt(movedInfo[0])); + throw new JedisMovedDataException(message, HostAndPort.from(movedInfo[1]), Integer.parseInt(movedInfo[0])); } else if (message.startsWith(ASK_PREFIX)) { String[] askInfo = parseTargetHostAndSlot(message); - throw new JedisAskDataException(message, new HostAndPort(askInfo[1], - Integer.parseInt(askInfo[2])), Integer.parseInt(askInfo[0])); +// throw new JedisAskDataException(message, new HostAndPort(askInfo[1], +// Integer.parseInt(askInfo[2])), Integer.parseInt(askInfo[0])); + throw new JedisAskDataException(message, HostAndPort.from(askInfo[1]), Integer.parseInt(askInfo[0])); } else if (message.startsWith(CLUSTERDOWN_PREFIX)) { throw new JedisClusterException(message); } else if (message.startsWith(BUSY_PREFIX)) { @@ -135,8 +92,6 @@ private static void processError(final RedisInputStream is) { throw new JedisAccessControlException(message); } else if (message.startsWith(NOPERM_PREFIX)) { throw new JedisAccessControlException(message); - } else if (message.startsWith(EXECABORT_PREFIX)) { - throw new AbortedTransactionException(message); } throw new JedisDataException(message); } @@ -150,32 +105,39 @@ public static String readErrorLineIfPossible(RedisInputStream is) { return is.readLine(); } +// private static String[] parseTargetHostAndSlot(String clusterRedirectResponse) { +// String[] response = new String[3]; +// String[] messageInfo = clusterRedirectResponse.split(" "); +// String[] targetHostAndPort = HostAndPort.extractParts(messageInfo[2]); +// response[0] = messageInfo[1]; +// response[1] = targetHostAndPort[0]; +// response[2] = targetHostAndPort[1]; +// return response; +// } private static String[] parseTargetHostAndSlot(String clusterRedirectResponse) { - String[] response = new String[3]; + String[] response = new String[2]; String[] messageInfo = clusterRedirectResponse.split(" "); - String[] targetHostAndPort = HostAndPort.extractParts(messageInfo[2]); response[0] = messageInfo[1]; - response[1] = targetHostAndPort[0]; - response[2] = targetHostAndPort[1]; + response[1] = messageInfo[2]; return response; } private static Object process(final RedisInputStream is) { final byte b = is.readByte(); switch (b) { - case PLUS_BYTE: - return processStatusCodeReply(is); - case DOLLAR_BYTE: - return processBulkReply(is); - case ASTERISK_BYTE: - return processMultiBulkReply(is); - case COLON_BYTE: - return processInteger(is); - case MINUS_BYTE: - processError(is); - return null; - default: - throw new JedisConnectionException("Unknown reply: " + (char) b); + case PLUS_BYTE: + return processStatusCodeReply(is); + case DOLLAR_BYTE: + return processBulkReply(is); + case ASTERISK_BYTE: + return processMultiBulkReply(is); + case COLON_BYTE: + return processInteger(is); + case MINUS_BYTE: + processError(is); + return null; + default: + throw new JedisConnectionException("Unknown reply: " + (char) b); } } @@ -193,8 +155,9 @@ private static byte[] processBulkReply(final RedisInputStream is) { int offset = 0; while (offset < len) { final int size = is.read(read, offset, (len - offset)); - if (size == -1) throw new JedisConnectionException( - "It seems like server has closed the connection."); + if (size == -1) { + throw new JedisConnectionException("It seems like server has closed the connection."); + } offset += size; } @@ -252,29 +215,31 @@ public static final byte[] toByteArray(final double value) { } public static enum Command implements ProtocolCommand { - PING, SET, GET, GETDEL, GETEX, QUIT, EXISTS, DEL, UNLINK, TYPE, FLUSHDB, KEYS, RANDOMKEY, RENAME, - RENAMENX, RENAMEX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, MOVE, FLUSHALL, GETSET, MGET, SETNX, - SETEX, MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, - HMGET, HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, HRANDFIELD, RPUSH, LPUSH, LLEN, LRANGE, LTRIM, - LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, SISMEMBER, - SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, ZADD, ZDIFF, ZDIFFSTORE, ZRANGE, ZREM, - ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZRANDMEMBER, ZCARD, ZSCORE, ZPOPMAX, ZPOPMIN, MULTI, DISCARD, EXEC, - WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, - PUNSUBSCRIBE, PUBSUB, ZCOUNT, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZREMRANGEBYRANK, - ZREMRANGEBYSCORE, ZUNION, ZUNIONSTORE, ZINTER, ZINTERSTORE, ZLEXCOUNT, ZRANGEBYLEX, ZREVRANGEBYLEX, - ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SHUTDOWN, INFO, MONITOR, SLAVEOF, CONFIG, - STRLEN, LPUSHX, PERSIST, RPUSHX, ECHO, LINSERT, DEBUG, BRPOPLPUSH, SETBIT, GETBIT, - BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, BITOP, SENTINEL, - DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, MIGRATE, - HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, PFADD, PFCOUNT, PFMERGE, - READONLY, READWRITE, GEOADD, GEODIST, GEOHASH, GEOPOS, GEORADIUS, GEORADIUS_RO, GEORADIUSBYMEMBER, - GEORADIUSBYMEMBER_RO, MODULE, BITFIELD, HSTRLEN, TOUCH, SWAPDB, MEMORY, XADD, XLEN, XDEL, - XTRIM, XRANGE, XREVRANGE, XREAD, XACK, XGROUP, XREADGROUP, XPENDING, XCLAIM, XAUTOCLAIM, ACL, XINFO, - BITFIELD_RO, LPOS, SMISMEMBER, ZMSCORE, BZPOPMIN, BZPOPMAX, BLMOVE, LMOVE, COPY, ROLE, FAILOVER, STRALGO; + + PING, SET, GET, GETDEL, GETEX, QUIT, EXISTS, DEL, UNLINK, TYPE, FLUSHDB, KEYS, RANDOMKEY, MOVE, + RENAME, RENAMENX, DBSIZE, EXPIRE, EXPIREAT, TTL, SELECT, FLUSHALL, GETSET, MGET, SETNX, SETEX, + MSET, MSETNX, DECRBY, DECR, INCRBY, INCR, APPEND, SUBSTR, HSET, HGET, HSETNX, HMSET, HMGET, + HINCRBY, HEXISTS, HDEL, HLEN, HKEYS, HVALS, HGETALL, HRANDFIELD, RPUSH, LPUSH, LLEN, LRANGE, + LTRIM, LINDEX, LSET, LREM, LPOP, RPOP, RPOPLPUSH, SADD, SMEMBERS, SREM, SPOP, SMOVE, SCARD, + SISMEMBER, SINTER, SINTERSTORE, SUNION, SUNIONSTORE, SDIFF, SDIFFSTORE, SRANDMEMBER, SMISMEMBER, + MULTI, DISCARD, EXEC, WATCH, UNWATCH, SORT, BLPOP, BRPOP, AUTH, INFO, SHUTDOWN, MONITOR, CONFIG, + SUBSCRIBE, PUBLISH, UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBSUB, STRLEN, LPUSHX, RPUSHX, ECHO, + ZADD, ZDIFF, ZDIFFSTORE, ZRANGE, ZREM, ZINCRBY, ZRANK, ZREVRANK, ZREVRANGE, ZRANDMEMBER, ZCARD, + ZSCORE, ZPOPMAX, ZPOPMIN, ZCOUNT, ZUNION, ZUNIONSTORE, ZINTER, ZINTERSTORE, ZRANGEBYSCORE, + ZREVRANGEBYSCORE, ZREMRANGEBYRANK, ZREMRANGEBYSCORE, ZLEXCOUNT, ZRANGEBYLEX, ZREVRANGEBYLEX, + ZREMRANGEBYLEX, SAVE, BGSAVE, BGREWRITEAOF, LASTSAVE, SLAVEOF, PERSIST, LINSERT, BRPOPLPUSH, + SETBIT, GETBIT, BITPOS, SETRANGE, GETRANGE, EVAL, EVALSHA, SCRIPT, SLOWLOG, OBJECT, BITCOUNT, + BITOP, SENTINEL, DUMP, RESTORE, PEXPIRE, PEXPIREAT, PTTL, INCRBYFLOAT, PSETEX, CLIENT, TIME, + MIGRATE, HINCRBYFLOAT, SCAN, HSCAN, SSCAN, ZSCAN, WAIT, CLUSTER, ASKING, READONLY, READWRITE, + PFADD, PFCOUNT, PFMERGE, MODULE, ACL, GEOADD, GEODIST, GEOHASH, GEOPOS, GEORADIUS, GEORADIUS_RO, + GEORADIUSBYMEMBER, GEORADIUSBYMEMBER_RO, BITFIELD, HSTRLEN, TOUCH, SWAPDB, MEMORY, XADD, XLEN, + XDEL, XTRIM, XRANGE, XREVRANGE, XREAD, XACK, XGROUP, XREADGROUP, XPENDING, XCLAIM, XAUTOCLAIM, + XINFO, BITFIELD_RO, LPOS, ZMSCORE, BZPOPMIN, BZPOPMAX, BLMOVE, LMOVE, COPY, ROLE, FAILOVER, + STRALGO; private final byte[] raw; - Command() { + private Command() { raw = SafeEncoder.encode(name()); } @@ -285,19 +250,20 @@ public byte[] getRaw() { } public static enum Keyword implements Rawable { - AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, MESSAGE, NO, NOSORT, PMESSAGE, PSUBSCRIBE, - PUNSUBSCRIBE, OK, ONE, QUEUED, SET, STORE, SUBSCRIBE, UNSUBSCRIBE, WEIGHTS, WITHSCORES, - RESETSTAT, REWRITE, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, - GETNAME, SETNAME, LIST, MATCH, COUNT, TYPE, PING, PONG, UNLOAD, REPLACE, KEYS, PAUSE, DOCTOR, - BLOCK, NOACK, STREAMS, KEY, CREATE, MKSTREAM, SETID, DESTROY, DELCONSUMER, MAXLEN, GROUP, ID, - IDLE, TIME, RETRYCOUNT, FORCE, USAGE, SAMPLES, STREAM, GROUPS, CONSUMERS, HELP, FREQ, SETUSER, - GETUSER, DELUSER, WHOAMI, CAT, GENPASS, USERS, LOG, INCR, SAVE, JUSTID, WITHVALUES, UNBLOCK, - NOMKSTREAM, MINID, DB, ABSTTL, TO, TIMEOUT, ABORT, LCS, STRINGS; + + AGGREGATE, ALPHA, ASC, BY, DESC, GET, LIMIT, NO, NOSORT, ONE, SET, STORE, WEIGHTS, WITHSCORES, + RESETSTAT, REWRITE, RESET, FLUSH, EXISTS, LOAD, KILL, LEN, REFCOUNT, ENCODING, IDLETIME, DOCTOR, + HELP, FREQ, GETNAME, SETNAME, LIST, MATCH, COUNT, TYPE, UNLOAD, REPLACE, PAUSE, BLOCK, NOACK, + STREAMS, CREATE, MKSTREAM, SETID, DESTROY, DELCONSUMER, MAXLEN, GROUP, ID, IDLE, TIME, FORCE, + RETRYCOUNT, USAGE, SAMPLES, STREAM, GROUPS, CONSUMERS, SETUSER, GETUSER, DELUSER, WHOAMI, USERS, + CAT, GENPASS, LOG, INCR, SAVE, JUSTID, WITHVALUES, UNBLOCK, NOMKSTREAM, MINID, DB, ABSTTL, TO, + TIMEOUT, ABORT, NX, XX, EX, PX, EXAT, PXAT, CH, WITHCOORD, WITHDIST, WITHHASH, STOREDIST, COPY, + KEEPTTL, AUTH, AUTH2, INFO, CHANNELS, NUMPAT, NUMSUB, LCS, KEYS, STRINGS; private final byte[] raw; - Keyword() { - raw = SafeEncoder.encode(name().toLowerCase(Locale.ENGLISH)); + private Keyword() { + raw = SafeEncoder.encode(name()); } @Override @@ -307,7 +273,9 @@ public byte[] getRaw() { } public static enum SentinelKeyword implements Rawable { - MYID, MASTERS, MASTER, SENTINELS, SLAVES, REPLICAS; + + MYID, MASTERS, MASTER, SENTINELS, SLAVES, REPLICAS, RESET, FAILOVER, REMOVE, SET, MONITOR, + GET_MASTER_ADDR_BY_NAME("GET-MASTER-ADDR-BY-NAME"); private final byte[] raw; @@ -315,6 +283,26 @@ private SentinelKeyword() { raw = SafeEncoder.encode(name()); } + private SentinelKeyword(String str) { + raw = SafeEncoder.encode(str); + } + + @Override + public byte[] getRaw() { + return raw; + } + } + + public static enum ResponseKeyword implements Rawable { + + SUBSCRIBE, PSUBSCRIBE, UNSUBSCRIBE, PUNSUBSCRIBE, MESSAGE, PMESSAGE, PONG; + + private final byte[] raw; + + private ResponseKeyword() { + raw = SafeEncoder.encode(name().toLowerCase(Locale.ENGLISH)); + } + @Override public byte[] getRaw() { return raw; @@ -322,7 +310,10 @@ public byte[] getRaw() { } public static enum ClusterKeyword implements Rawable { - MEET, RESET, INFO, FAILOVER, SLOTS, FORCE, TAKEOVER, NODES, REPLICAS, MYID; + + MEET, RESET, INFO, FAILOVER, SLOTS, NODES, REPLICAS, SLAVES, MYID, ADDSLOTS, DELSLOTS, + GETKEYSINSLOT, SETSLOT, NODE, MIGRATING, IMPORTING, STABLE, FORGET, FLUSHSLOTS, KEYSLOT, + COUNTKEYSINSLOT, SAVECONFIG, REPLICATE; private final byte[] raw; diff --git a/src/main/java/redis/clients/jedis/Queable.java b/src/main/java/redis/clients/jedis/Queable.java index 3c79dc371e..2fe7c5e3ba 100644 --- a/src/main/java/redis/clients/jedis/Queable.java +++ b/src/main/java/redis/clients/jedis/Queable.java @@ -4,31 +4,28 @@ import java.util.Queue; public class Queable { - private Queue> pipelinedResponses = new LinkedList<>(); - protected void clean() { + private final Queue> pipelinedResponses = new LinkedList<>(); + + protected final void clean() { pipelinedResponses.clear(); } - protected Response generateResponse(Object data) { +// protected final void generateResponse(Object data) { +// pipelinedResponses.poll().set(data); + protected final Response generateResponse(Object data) { Response response = pipelinedResponses.poll(); - if (response != null) { - response.set(data); - } + response.set(data); return response; } - protected Response getResponse(Builder builder) { + protected final Response enqueResponse(Builder builder) { Response lr = new Response<>(builder); pipelinedResponses.add(lr); return lr; } - protected boolean hasPipelinedResponse() { - return !pipelinedResponses.isEmpty(); - } - - protected int getPipelinedResponseLength() { + protected final int getPipelinedResponseLength() { return pipelinedResponses.size(); } } diff --git a/src/main/java/redis/clients/jedis/ReliableTransaction.java b/src/main/java/redis/clients/jedis/ReliableTransaction.java new file mode 100644 index 0000000000..911156757b --- /dev/null +++ b/src/main/java/redis/clients/jedis/ReliableTransaction.java @@ -0,0 +1,53 @@ +package redis.clients.jedis; + +import java.util.List; +import redis.clients.jedis.exceptions.JedisException; + +public class ReliableTransaction extends TransactionBase { + + public ReliableTransaction(Connection connection) { + super(connection); + } + + /** + * If you want to WATCH/UNWATCH keys before MULTI command you should do {@code doMulti = true}. + */ + public ReliableTransaction(Connection connection, boolean doMulti) { + super(connection, doMulti); + } + + @Override + protected final void processMultiResponse() { + String status = connection.getStatusCodeReply(); + if (!"OK".equals(status)) { + throw new JedisException("MULTI command failed. Received response: " + status); + } + } + + @Override + protected final void processAppendStatus() { + String status = connection.getStatusCodeReply(); + if (!"QUEUED".equals(status)) { + throw new JedisException(status); + } + } + + @Override + protected final void processPipelinedResponses() { + // do nothing + } + + @Override + public final List exec() { + return super.exec(); + } + + @Override + public final String discard() { + String status = super.discard(); + if (!"OK".equals(status)) { + throw new JedisException("DISCARD command failed. Received response: " + status); + } + return status; + } +} diff --git a/src/main/java/redis/clients/jedis/Response.java b/src/main/java/redis/clients/jedis/Response.java index 03c4bbd0e0..18fba8f558 100644 --- a/src/main/java/redis/clients/jedis/Response.java +++ b/src/main/java/redis/clients/jedis/Response.java @@ -1,8 +1,9 @@ package redis.clients.jedis; +import java.util.function.Supplier; import redis.clients.jedis.exceptions.JedisDataException; -public class Response { +public class Response implements Supplier { protected T response = null; protected JedisDataException exception = null; @@ -23,6 +24,7 @@ public void set(Object data) { set = true; } + @Override public T get() { // if response has dependency response and dependency is not built, build it first and no more!! if (dependency != null && dependency.set && !dependency.built) { diff --git a/src/main/java/redis/clients/jedis/Sentinel.java b/src/main/java/redis/clients/jedis/Sentinel.java new file mode 100644 index 0000000000..d79a4d841f --- /dev/null +++ b/src/main/java/redis/clients/jedis/Sentinel.java @@ -0,0 +1,405 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.Command.SENTINEL; +import static redis.clients.jedis.Protocol.SentinelKeyword.*; + +import java.io.Closeable; +import java.net.URI; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLParameters; +import javax.net.ssl.SSLSocketFactory; + +import redis.clients.jedis.commands.SentinelCommands; +import redis.clients.jedis.exceptions.InvalidURIException; +import redis.clients.jedis.util.JedisURIHelper; +import redis.clients.jedis.util.SafeEncoder; + +public class Sentinel implements SentinelCommands, Closeable { + + protected final Connection connection; + protected static final byte[][] DUMMY_ARRAY = new byte[0][]; + + /** + * This constructor only accepts a URI string. {@link JedisURIHelper#isValid(java.net.URI)} can be + * used before this. + * @param uriString + */ + public Sentinel(final String uriString) { + this(URI.create(uriString)); + } + + public Sentinel(final HostAndPort hp) { + connection = new Connection(hp); + } + + public Sentinel(final String host, final int port) { + connection = new Connection(host, port); + } + + public Sentinel(final String host, final int port, final JedisClientConfig config) { + this(new HostAndPort(host, port), config); + } + + public Sentinel(final HostAndPort hostPort, final JedisClientConfig config) { + connection = new Connection(hostPort, config); + } + + public Sentinel(final String host, final int port, final boolean ssl) { + this(host, port, DefaultJedisClientConfig.builder().ssl(ssl).build()); + } + + public Sentinel(final String host, final int port, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(host, port, DefaultJedisClientConfig.builder().ssl(ssl) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); + } + + public Sentinel(final String host, final int port, final int timeout) { + this(host, port, timeout, timeout); + } + + public Sentinel(final String host, final int port, final int timeout, final boolean ssl) { + this(host, port, timeout, timeout, ssl); + } + + public Sentinel(final String host, final int port, final int timeout, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(host, port, timeout, timeout, ssl, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public Sentinel(final String host, final int port, final int connectionTimeout, + final int soTimeout) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).build()); + } + + public Sentinel(final String host, final int port, final int connectionTimeout, + final int soTimeout, final int infiniteSoTimeout) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) + .blockingSocketTimeoutMillis(infiniteSoTimeout).build()); + } + + public Sentinel(final String host, final int port, final int connectionTimeout, + final int soTimeout, final boolean ssl) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl) + .build()); + } + + public Sentinel(final String host, final int port, final int connectionTimeout, + final int soTimeout, final boolean ssl, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout).ssl(ssl) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); + } + + public Sentinel(final String host, final int port, final int connectionTimeout, + final int soTimeout, final int infiniteSoTimeout, final boolean ssl, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(host, port, DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(connectionTimeout).socketTimeoutMillis(soTimeout) + .blockingSocketTimeoutMillis(infiniteSoTimeout).ssl(ssl) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); + } + + public Sentinel(URI uri) { + if (!JedisURIHelper.isValid(uri)) { + throw new InvalidURIException(String.format( + "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); + } + connection = new Connection(new HostAndPort(uri.getHost(), uri.getPort()), + DefaultJedisClientConfig.builder().user(JedisURIHelper.getUser(uri)) + .password(JedisURIHelper.getPassword(uri)).database(JedisURIHelper.getDBIndex(uri)) + .ssl(JedisURIHelper.isRedisSSLScheme(uri)).build()); + } + + public Sentinel(URI uri, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(uri, DefaultJedisClientConfig.builder().sslSocketFactory(sslSocketFactory) + .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); + } + + public Sentinel(final URI uri, final int timeout) { + this(uri, timeout, timeout); + } + + public Sentinel(final URI uri, final int timeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(uri, timeout, timeout, sslSocketFactory, sslParameters, hostnameVerifier); + } + + public Sentinel(final URI uri, final int connectionTimeout, final int soTimeout) { + this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).build()); + } + + public Sentinel(final URI uri, final int connectionTimeout, final int soTimeout, + final SSLSocketFactory sslSocketFactory, final SSLParameters sslParameters, + final HostnameVerifier hostnameVerifier) { + this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).sslSocketFactory(sslSocketFactory) + .sslParameters(sslParameters).hostnameVerifier(hostnameVerifier).build()); + } + + public Sentinel(final URI uri, final int connectionTimeout, final int soTimeout, + final int infiniteSoTimeout, final SSLSocketFactory sslSocketFactory, + final SSLParameters sslParameters, final HostnameVerifier hostnameVerifier) { + this(uri, DefaultJedisClientConfig.builder().connectionTimeoutMillis(connectionTimeout) + .socketTimeoutMillis(soTimeout).blockingSocketTimeoutMillis(infiniteSoTimeout) + .sslSocketFactory(sslSocketFactory).sslParameters(sslParameters) + .hostnameVerifier(hostnameVerifier).build()); + } + + public Sentinel(final URI uri, JedisClientConfig config) { + if (!JedisURIHelper.isValid(uri)) { + throw new InvalidURIException(String.format( + "Cannot open Redis connection due invalid URI \"%s\".", uri.toString())); + } + connection = new Connection(new HostAndPort(uri.getHost(), uri.getPort()), + DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(config.getConnectionTimeoutMillis()) + .socketTimeoutMillis(config.getSocketTimeoutMillis()) + .blockingSocketTimeoutMillis(config.getBlockingSocketTimeoutMillis()) + .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) + .database(JedisURIHelper.getDBIndex(uri)).clientName(config.getClientName()) + .ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(config.getSslSocketFactory()) + .sslParameters(config.getSslParameters()).hostnameVerifier(config.getHostnameVerifier()) + .build()); + } + + public Sentinel(final Connection connection) { + this.connection = connection; + } + + @Override + public String toString() { + return "Sentinel{" + connection + '}'; + } + + // Legacy + public Connection getClient() { + return getConnection(); + } + + public Connection getConnection() { + return connection; + } + + // Legacy + public void connect() { + connection.connect(); + } + + // Legacy + public void disconnect() { + connection.disconnect(); + } + + public boolean isConnected() { + return connection.isConnected(); + } + + public boolean isBroken() { + return connection.isBroken(); + } + + @Override + public void close() { + connection.close(); + } + + @Override + public String sentinelMyId() { + connection.sendCommand(SENTINEL, MYID); + return connection.getBulkReply(); + } + + /** + *
+   * redis 127.0.0.1:26381> sentinel masters
+   * 1)  1) "name"
+   *     2) "mymaster"
+   *     3) "ip"
+   *     4) "127.0.0.1"
+   *     5) "port"
+   *     6) "6379"
+   *     7) "runid"
+   *     8) "93d4d4e6e9c06d0eea36e27f31924ac26576081d"
+   *     9) "flags"
+   *    10) "master"
+   *    11) "pending-commands"
+   *    12) "0"
+   *    13) "last-ok-ping-reply"
+   *    14) "423"
+   *    15) "last-ping-reply"
+   *    16) "423"
+   *    17) "info-refresh"
+   *    18) "6107"
+   *    19) "num-slaves"
+   *    20) "1"
+   *    21) "num-other-sentinels"
+   *    22) "2"
+   *    23) "quorum"
+   *    24) "2"
+   *
+   * 
+ * @return + */ + @Override + public List> sentinelMasters() { + connection.sendCommand(SENTINEL, MASTERS); + return connection.getObjectMultiBulkReply().stream() + .map(BuilderFactory.STRING_MAP::build).collect(Collectors.toList()); + } + + @Override + public Map sentinelMaster(String masterName) { + connection.sendCommand(SENTINEL, MASTER.name(), masterName); + return BuilderFactory.STRING_MAP.build(connection.getOne()); + } + + @Override + public List> sentinelSentinels(String masterName) { + connection.sendCommand(SENTINEL, SENTINELS.name(), masterName); + return connection.getObjectMultiBulkReply().stream() + .map(BuilderFactory.STRING_MAP::build).collect(Collectors.toList()); + } + + /** + *
+   * redis 127.0.0.1:26381> sentinel get-master-addr-by-name mymaster
+   * 1) "127.0.0.1"
+   * 2) "6379"
+   * 
+ * @param masterName + * @return two elements list of strings : host and port. + */ + @Override + public List sentinelGetMasterAddrByName(String masterName) { + connection.sendCommand(SENTINEL, GET_MASTER_ADDR_BY_NAME.getRaw(), SafeEncoder.encode(masterName)); + return connection.getMultiBulkReply(); + } + + /** + *
+   * redis 127.0.0.1:26381> sentinel reset mymaster
+   * (integer) 1
+   * 
+ * @param pattern + * @return + */ + @Override + public Long sentinelReset(String pattern) { + connection.sendCommand(SENTINEL, RESET.name(), pattern); + return connection.getIntegerReply(); + } + + /** + *
+   * redis 127.0.0.1:26381> sentinel slaves mymaster
+   * 1)  1) "name"
+   *     2) "127.0.0.1:6380"
+   *     3) "ip"
+   *     4) "127.0.0.1"
+   *     5) "port"
+   *     6) "6380"
+   *     7) "runid"
+   *     8) "d7f6c0ca7572df9d2f33713df0dbf8c72da7c039"
+   *     9) "flags"
+   *    10) "slave"
+   *    11) "pending-commands"
+   *    12) "0"
+   *    13) "last-ok-ping-reply"
+   *    14) "47"
+   *    15) "last-ping-reply"
+   *    16) "47"
+   *    17) "info-refresh"
+   *    18) "657"
+   *    19) "master-link-down-time"
+   *    20) "0"
+   *    21) "master-link-status"
+   *    22) "ok"
+   *    23) "master-host"
+   *    24) "localhost"
+   *    25) "master-port"
+   *    26) "6379"
+   *    27) "slave-priority"
+   *    28) "100"
+   * 
+ * @param masterName + * @return + */ + @Override + public List> sentinelSlaves(String masterName) { + connection.sendCommand(SENTINEL, SLAVES.name(), masterName); + return connection.getObjectMultiBulkReply().stream() + .map(BuilderFactory.STRING_MAP::build).collect(Collectors.toList()); + } + + @Override + public List> sentinelReplicas(String masterName) { + connection.sendCommand(SENTINEL, REPLICAS.name(), masterName); + return connection.getObjectMultiBulkReply().stream() + .map(BuilderFactory.STRING_MAP::build).collect(Collectors.toList()); + } + + @Override + public String sentinelFailover(String masterName) { + connection.sendCommand(SENTINEL, FAILOVER.name(), masterName); + return connection.getStatusCodeReply(); + } + + @Override + public String sentinelMonitor(String masterName, String ip, int port, int quorum) { + CommandArguments args = new CommandArguments(SENTINEL).add(MONITOR) + .add(masterName).add(ip).add(port).add(quorum); + connection.sendCommand(args); + return connection.getStatusCodeReply(); + } + + @Override + public String sentinelRemove(String masterName) { + connection.sendCommand(SENTINEL, REMOVE.name(), masterName); + return connection.getStatusCodeReply(); + } + + @Override + public String sentinelSet(String masterName, Map parameterMap) { + CommandArguments args = new CommandArguments(SENTINEL).add(SET).add(masterName); + parameterMap.entrySet().forEach(entry -> args.add(entry.getKey()).add(entry.getValue())); + connection.sendCommand(args); + return connection.getStatusCodeReply(); + } + + public void subscribe(final JedisPubSub jedisPubSub, final String... channels) { + connection.setTimeoutInfinite(); + try { + jedisPubSub.proceed(connection, channels); + } finally { + connection.rollbackTimeout(); + } + } + + public void psubscribe(final JedisPubSub jedisPubSub, final String... channels) { + connection.setTimeoutInfinite(); + try { + jedisPubSub.proceedWithPatterns(connection, channels); + } finally { + connection.rollbackTimeout(); + } + } + +} diff --git a/src/main/java/redis/clients/jedis/ShardedCommandArguments.java b/src/main/java/redis/clients/jedis/ShardedCommandArguments.java new file mode 100644 index 0000000000..30552eb7e8 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ShardedCommandArguments.java @@ -0,0 +1,59 @@ +package redis.clients.jedis; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.util.Hashing; + +public class ShardedCommandArguments extends CommandArguments { + + private final Hashing algo; + private final Pattern tagPattern; + private Long keyHash = null; + + public ShardedCommandArguments(Hashing algo, ProtocolCommand command) { + this(algo, null, command); + } + + public ShardedCommandArguments(Hashing algo, Pattern tagPattern, ProtocolCommand command) { + super(command); + this.algo = algo; + this.tagPattern = tagPattern; + } + + public Long getKeyHash() { + return keyHash; + } + + @Override + protected CommandArguments processKey(byte[] key) { + final long hash = algo.hash(key); + if (keyHash == null) { + keyHash = hash; + } else if (keyHash != hash) { + throw new JedisException("Keys must generate same hash."); + } + return this; + } + + @Override + protected CommandArguments processKey(String key) { + key = getKeyTag(key); + final long hash = algo.hash(key); + if (keyHash == null) { + keyHash = hash; + } else if (keyHash != hash) { + throw new JedisException("Keys must generate same hash."); + } + return this; + } + + private String getKeyTag(String key) { + if (tagPattern != null) { + Matcher m = tagPattern.matcher(key); + if (m.find()) return m.group(1); + } + return key; + } +} diff --git a/src/main/java/redis/clients/jedis/ShardedCommandObjects.java b/src/main/java/redis/clients/jedis/ShardedCommandObjects.java new file mode 100644 index 0000000000..da46d2048d --- /dev/null +++ b/src/main/java/redis/clients/jedis/ShardedCommandObjects.java @@ -0,0 +1,112 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.Command.KEYS; +import static redis.clients.jedis.Protocol.Command.SCAN; +import static redis.clients.jedis.Protocol.Keyword.TYPE; + +import java.util.Set; +import java.util.regex.Pattern; + +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.util.Hashing; +import redis.clients.jedis.util.JedisClusterHashTag; + +public class ShardedCommandObjects extends CommandObjects { + + private final Hashing algo; + private final Pattern tagPattern; + + public ShardedCommandObjects(Hashing algo) { + this(algo, null); + } + + public ShardedCommandObjects(Hashing algo, Pattern tagPattern) { + this.algo = algo; + this.tagPattern = tagPattern; + } + + @Override + protected ShardedCommandArguments commandArguments(ProtocolCommand command) { + return new ShardedCommandArguments(algo, tagPattern, command); + } + + @Override + public CommandObject dbSize() { + throw new UnsupportedOperationException(); + } + + private static final String KEYS_PATTERN_MESSAGE = "Cluster mode only supports KEYS command" + + " with pattern containing hash-tag ( curly-brackets enclosed string )"; + + private static final String SCAN_PATTERN_MESSAGE = "Cluster mode only supports SCAN command" + + " with MATCH pattern containing hash-tag ( curly-brackets enclosed string )"; + + @Override + public final CommandObject> keys(String pattern) { + if (!JedisClusterHashTag.isClusterCompliantMatchPattern(pattern)) { + throw new IllegalArgumentException(KEYS_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(KEYS).key(pattern).processKey(pattern), BuilderFactory.STRING_SET); + } + + @Override + public final CommandObject> keys(byte[] pattern) { + if (!JedisClusterHashTag.isClusterCompliantMatchPattern(pattern)) { + throw new IllegalArgumentException(KEYS_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(KEYS).key(pattern).processKey(pattern), BuilderFactory.BINARY_SET); + } + + @Override + public final CommandObject> scan(String cursor) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + + @Override + public final CommandObject> scan(String cursor, ScanParams params) { + String match = params.match(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match), BuilderFactory.SCAN_RESPONSE); + } + + @Override + public final CommandObject> scan(String cursor, ScanParams params, String type) { + String match = params.match(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match).add(TYPE).add(type), BuilderFactory.SCAN_RESPONSE); + } + + @Override + public final CommandObject> scan(byte[] cursor) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + + @Override + public final CommandObject> scan(byte[] cursor, ScanParams params) { + byte[] match = params.binaryMatch(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + @Override + public final CommandObject> scan(byte[] cursor, ScanParams params, byte[] type) { + byte[] match = params.binaryMatch(); + if (match == null || !JedisClusterHashTag.isClusterCompliantMatchPattern(match)) { + throw new IllegalArgumentException(SCAN_PATTERN_MESSAGE); + } + return new CommandObject<>(commandArguments(SCAN).add(cursor).addParams(params).processKey(match).add(TYPE).add(type), BuilderFactory.SCAN_BINARY_RESPONSE); + } + + @Override + public final CommandObject waitReplicas(int replicas, long timeout) { + throw new UnsupportedOperationException(); + } +} diff --git a/src/main/java/redis/clients/jedis/ShardedJedis.java b/src/main/java/redis/clients/jedis/ShardedJedis.java deleted file mode 100644 index c2df602cef..0000000000 --- a/src/main/java/redis/clients/jedis/ShardedJedis.java +++ /dev/null @@ -1,1319 +0,0 @@ -package redis.clients.jedis; - -import java.io.Closeable; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.regex.Pattern; - -import redis.clients.jedis.commands.JedisCommands; -import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.params.GeoAddParams; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GetExParams; -import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.params.SetParams; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.params.ZAddParams; -import redis.clients.jedis.params.ZIncrByParams; -import redis.clients.jedis.params.LPosParams; -import redis.clients.jedis.resps.KeyedListElement; -import redis.clients.jedis.resps.LCSMatchResult; -import redis.clients.jedis.util.Hashing; - -public class ShardedJedis extends BinaryShardedJedis implements JedisCommands, Closeable { - - protected ShardedJedisPool dataSource = null; - - public ShardedJedis(List shards) { - super(shards); - } - - public ShardedJedis(List shards, Hashing algo) { - super(shards, algo); - } - - public ShardedJedis(List shards, Pattern keyTagPattern) { - super(shards, keyTagPattern); - } - - public ShardedJedis(List shards, Hashing algo, Pattern keyTagPattern) { - super(shards, algo, keyTagPattern); - } - - @Override - public String set(final String key, final String value) { - Jedis j = getShard(key); - return j.set(key, value); - } - - @Override - public String set(final String key, final String value, SetParams params) { - Jedis j = getShard(key); - return j.set(key, value, params); - } - - @Override - public String get(final String key) { - Jedis j = getShard(key); - return j.get(key); - } - - @Override - public String getDel(final String key) { - Jedis j = getShard(key); - return j.getDel(key); - } - - @Override - public String getEx(String key, GetExParams params) { - Jedis j = getShard(key); - return j.getEx(key, params); - } - - @Override - public String echo(final String string) { - Jedis j = getShard(string); - return j.echo(string); - } - - @Override - public boolean exists(final String key) { - Jedis j = getShard(key); - return j.exists(key); - } - - @Override - public String type(final String key) { - Jedis j = getShard(key); - return j.type(key); - } - - @Override - public byte[] dump(final String key) { - Jedis j = getShard(key); - return j.dump(key); - } - - @Override - public String restore(final String key, final long ttl, final byte[] serializedValue) { - Jedis j = getShard(key); - return j.restore(key, ttl, serializedValue); - } - - @Override - public String restoreReplace(final String key, final long ttl, final byte[] serializedValue) { - Jedis j = getShard(key); - return j.restoreReplace(key, ttl, serializedValue); - } - - @Override - public String restore(final String key, final long ttl, final byte[] serializedValue, - final RestoreParams params) { - Jedis j = getShard(key); - return j.restore(key, ttl, serializedValue, params); - } - - @Override - public long expire(final String key, final long seconds) { - Jedis j = getShard(key); - return j.expire(key, seconds); - } - - @Override - public long pexpire(final String key, final long milliseconds) { - Jedis j = getShard(key); - return j.pexpire(key, milliseconds); - } - - @Override - public long expireAt(final String key, final long unixTime) { - Jedis j = getShard(key); - return j.expireAt(key, unixTime); - } - - @Override - public long pexpireAt(final String key, final long millisecondsTimestamp) { - Jedis j = getShard(key); - return j.pexpireAt(key, millisecondsTimestamp); - } - - @Override - public long ttl(final String key) { - Jedis j = getShard(key); - return j.ttl(key); - } - - @Override - public long pttl(final String key) { - Jedis j = getShard(key); - return j.pttl(key); - } - - @Override - public boolean setbit(final String key, final long offset, boolean value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); - } - - @Override - public Boolean setbit(final String key, final long offset, final String value) { - Jedis j = getShard(key); - return j.setbit(key, offset, value); - } - - @Override - public boolean getbit(final String key, final long offset) { - Jedis j = getShard(key); - return j.getbit(key, offset); - } - - @Override - public long setrange(final String key, final long offset, final String value) { - Jedis j = getShard(key); - return j.setrange(key, offset, value); - } - - @Override - public String getrange(final String key, final long startOffset, final long endOffset) { - Jedis j = getShard(key); - return j.getrange(key, startOffset, endOffset); - } - - @Override - public String getSet(final String key, final String value) { - Jedis j = getShard(key); - return j.getSet(key, value); - } - - @Override - public long setnx(final String key, final String value) { - Jedis j = getShard(key); - return j.setnx(key, value); - } - - @Override - public String setex(final String key, final long seconds, final String value) { - Jedis j = getShard(key); - return j.setex(key, seconds, value); - } - - @Override - public String psetex(final String key, final long milliseconds, final String value) { - Jedis j = getShard(key); - return j.psetex(key, milliseconds, value); - } - - @Override - public List blpop(final int timeout, final String key) { - Jedis j = getShard(key); - return j.blpop(timeout, key); - } - - @Override - public KeyedListElement blpop(final double timeout, final String key) { - Jedis j = getShard(key); - return j.blpop(timeout, key); - } - - @Override - public List brpop(final int timeout, final String key) { - Jedis j = getShard(key); - return j.brpop(timeout, key); - } - - @Override - public KeyedListElement brpop(final double timeout, final String key) { - Jedis j = getShard(key); - return j.brpop(timeout, key); - } - - @Override - public long decrBy(final String key, final long decrement) { - Jedis j = getShard(key); - return j.decrBy(key, decrement); - } - - @Override - public long decr(final String key) { - Jedis j = getShard(key); - return j.decr(key); - } - - @Override - public long incrBy(final String key, final long increment) { - Jedis j = getShard(key); - return j.incrBy(key, increment); - } - - @Override - public double incrByFloat(final String key, final double increment) { - Jedis j = getShard(key); - return j.incrByFloat(key, increment); - } - - @Override - public long incr(final String key) { - Jedis j = getShard(key); - return j.incr(key); - } - - @Override - public long append(final String key, final String value) { - Jedis j = getShard(key); - return j.append(key, value); - } - - @Override - public String substr(final String key, final int start, final int end) { - Jedis j = getShard(key); - return j.substr(key, start, end); - } - - @Override - public long hset(final String key, final String field, final String value) { - Jedis j = getShard(key); - return j.hset(key, field, value); - } - - @Override - public long hset(final String key, final Map hash) { - Jedis j = getShard(key); - return j.hset(key, hash); - } - - @Override - public String hget(final String key, final String field) { - Jedis j = getShard(key); - return j.hget(key, field); - } - - @Override - public long hsetnx(final String key, final String field, final String value) { - Jedis j = getShard(key); - return j.hsetnx(key, field, value); - } - - @Override - public String hmset(final String key, final Map hash) { - Jedis j = getShard(key); - return j.hmset(key, hash); - } - - @Override - public List hmget(final String key, String... fields) { - Jedis j = getShard(key); - return j.hmget(key, fields); - } - - @Override - public long hincrBy(final String key, final String field, final long value) { - Jedis j = getShard(key); - return j.hincrBy(key, field, value); - } - - @Override - public double hincrByFloat(final String key, final String field, final double value) { - Jedis j = getShard(key); - return j.hincrByFloat(key, field, value); - } - - @Override - public boolean hexists(final String key, final String field) { - Jedis j = getShard(key); - return j.hexists(key, field); - } - - @Override - public long del(final String key) { - Jedis j = getShard(key); - return j.del(key); - } - - @Override - public long unlink(final String key) { - Jedis j = getShard(key); - return j.unlink(key); - } - - @Override - public long hdel(final String key, String... fields) { - Jedis j = getShard(key); - return j.hdel(key, fields); - } - - @Override - public long hlen(final String key) { - Jedis j = getShard(key); - return j.hlen(key); - } - - @Override - public Set hkeys(final String key) { - Jedis j = getShard(key); - return j.hkeys(key); - } - - @Override - public List hvals(final String key) { - Jedis j = getShard(key); - return j.hvals(key); - } - - @Override - public Map hgetAll(final String key) { - Jedis j = getShard(key); - return j.hgetAll(key); - } - - @Override - public String hrandfield(final String key) { - Jedis j = getShard(key); - return j.hrandfield(key); - } - - @Override - public List hrandfield(final String key, final long count) { - Jedis j = getShard(key); - return j.hrandfield(key, count); - } - - @Override - public Map hrandfieldWithValues(final String key, final long count) { - Jedis j = getShard(key); - return j.hrandfieldWithValues(key, count); - } - - @Override - public long rpush(final String key, String... strings) { - Jedis j = getShard(key); - return j.rpush(key, strings); - } - - @Override - public long lpush(final String key, String... strings) { - Jedis j = getShard(key); - return j.lpush(key, strings); - } - - @Override - public long lpushx(final String key, String... string) { - Jedis j = getShard(key); - return j.lpushx(key, string); - } - - @Override - public long strlen(final String key) { - Jedis j = getShard(key); - return j.strlen(key); - } - - public long move(final String key, final int dbIndex) { - Jedis j = getShard(key); - return j.move(key, dbIndex); - } - - @Override - public long rpushx(final String key, String... string) { - Jedis j = getShard(key); - return j.rpushx(key, string); - } - - @Override - public long persist(final String key) { - Jedis j = getShard(key); - return j.persist(key); - } - - @Override - public long llen(final String key) { - Jedis j = getShard(key); - return j.llen(key); - } - - @Override - public List lrange(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.lrange(key, start, stop); - } - - @Override - public String ltrim(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.ltrim(key, start, stop); - } - - @Override - public String lindex(final String key, final long index) { - Jedis j = getShard(key); - return j.lindex(key, index); - } - - @Override - public String lset(final String key, final long index, final String value) { - Jedis j = getShard(key); - return j.lset(key, index, value); - } - - @Override - public long lrem(final String key, final long count, final String value) { - Jedis j = getShard(key); - return j.lrem(key, count, value); - } - - @Override - public String lpop(final String key) { - Jedis j = getShard(key); - return j.lpop(key); - } - - @Override - public List lpop(final String key, final int count) { - Jedis j = getShard(key); - return j.lpop(key, count); - } - - @Override - public Long lpos(final String key, final String element) { - Jedis j = getShard(key); - return j.lpos(key, element); - } - - @Override - public Long lpos(final String key, final String element, final LPosParams params) { - Jedis j = getShard(key); - return j.lpos(key, element, params); - } - - @Override - public List lpos(final String key, final String element, final LPosParams params, - final long count) { - Jedis j = getShard(key); - return j.lpos(key, element, params, count); - } - - @Override - public String rpop(final String key) { - Jedis j = getShard(key); - return j.rpop(key); - } - - @Override - public List rpop(final String key, final int count) { - Jedis j = getShard(key); - return j.rpop(key, count); - } - - @Override - public long sadd(final String key, String... members) { - Jedis j = getShard(key); - return j.sadd(key, members); - } - - @Override - public Set smembers(final String key) { - Jedis j = getShard(key); - return j.smembers(key); - } - - @Override - public long srem(final String key, String... members) { - Jedis j = getShard(key); - return j.srem(key, members); - } - - @Override - public String spop(final String key) { - Jedis j = getShard(key); - return j.spop(key); - } - - @Override - public Set spop(final String key, final long count) { - Jedis j = getShard(key); - return j.spop(key, count); - } - - @Override - public long scard(final String key) { - Jedis j = getShard(key); - return j.scard(key); - } - - @Override - public boolean sismember(final String key, final String member) { - Jedis j = getShard(key); - return j.sismember(key, member); - } - - @Override - public List smismember(final String key, final String... members) { - Jedis j = getShard(key); - return j.smismember(key, members); - } - - @Override - public String srandmember(final String key) { - Jedis j = getShard(key); - return j.srandmember(key); - } - - @Override - public List srandmember(final String key, final int count) { - Jedis j = getShard(key); - return j.srandmember(key, count); - } - - @Override - public long zadd(final String key, final double score, final String member) { - Jedis j = getShard(key); - return j.zadd(key, score, member); - } - - @Override - public long zadd(final String key, final double score, final String member, - final ZAddParams params) { - Jedis j = getShard(key); - return j.zadd(key, score, member, params); - } - - @Override - public long zadd(final String key, final Map scoreMembers) { - Jedis j = getShard(key); - return j.zadd(key, scoreMembers); - } - - @Override - public long zadd(final String key, final Map scoreMembers, final ZAddParams params) { - Jedis j = getShard(key); - return j.zadd(key, scoreMembers, params); - } - - @Override - public Double zaddIncr(final String key, final double score, final String member, final ZAddParams params) { - Jedis j = getShard(key); - return j.zaddIncr(key, score, member, params); - } - - @Override - public Set zrange(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrange(key, start, stop); - } - - @Override - public long zrem(final String key, String... members) { - Jedis j = getShard(key); - return j.zrem(key, members); - } - - @Override - public double zincrby(final String key, final double increment, final String member) { - Jedis j = getShard(key); - return j.zincrby(key, increment, member); - } - - @Override - public Double zincrby(final String key, final double increment, final String member, - ZIncrByParams params) { - Jedis j = getShard(key); - return j.zincrby(key, increment, member, params); - } - - @Override - public Long zrank(final String key, final String member) { - Jedis j = getShard(key); - return j.zrank(key, member); - } - - @Override - public Long zrevrank(final String key, final String member) { - Jedis j = getShard(key); - return j.zrevrank(key, member); - } - - @Override - public Set zrevrange(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrevrange(key, start, stop); - } - - @Override - public Set zrangeWithScores(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrangeWithScores(key, start, stop); - } - - @Override - public Set zrevrangeWithScores(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zrevrangeWithScores(key, start, stop); - } - - @Override - public String zrandmember(final String key) { - Jedis j = getShard(key); - return j.zrandmember(key); - } - - @Override - public Set zrandmember(final String key, final long count) { - Jedis j = getShard(key); - return j.zrandmember(key, count); - } - - @Override - public Set zrandmemberWithScores(final String key, final long count) { - Jedis j = getShard(key); - return j.zrandmemberWithScores(key, count); - } - - @Override - public long zcard(final String key) { - Jedis j = getShard(key); - return j.zcard(key); - } - - @Override - public Double zscore(final String key, final String member) { - Jedis j = getShard(key); - return j.zscore(key, member); - } - - @Override - public List zmscore(final String key, final String... members) { - Jedis j = getShard(key); - return j.zmscore(key, members); - } - - @Override - public Tuple zpopmax(final String key) { - Jedis j = getShard(key); - return j.zpopmax(key); - } - - @Override - public Set zpopmax(final String key, final int count) { - Jedis j = getShard(key); - return j.zpopmax(key, count); - } - - @Override - public Tuple zpopmin(final String key) { - Jedis j = getShard(key); - return j.zpopmin(key); - } - - @Override - public Set zpopmin(final String key, final int count) { - Jedis j = getShard(key); - return j.zpopmin(key, count); - } - - @Override - public List sort(final String key) { - Jedis j = getShard(key); - return j.sort(key); - } - - @Override - public List sort(final String key, final SortingParams sortingParameters) { - Jedis j = getShard(key); - return j.sort(key, sortingParameters); - } - - @Override - public long zcount(final String key, final double min, final double max) { - Jedis j = getShard(key); - return j.zcount(key, min, max); - } - - @Override - public long zcount(final String key, final String min, final String max) { - Jedis j = getShard(key); - return j.zcount(key, min, max); - } - - @Override - public Set zrangeByScore(final String key, final double min, final double max) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max); - } - - @Override - public Set zrevrangeByScore(final String key, final double max, final double min) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min); - } - - @Override - public Set zrangeByScore(final String key, final double min, final double max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByScore(final String key, final double max, final double min, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min, offset, count); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final double max, final double min) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final double min, final double max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final double max, - final double min, final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - - @Override - public Set zrangeByScore(final String key, final String min, final String max) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max); - } - - @Override - public Set zrevrangeByScore(final String key, final String max, final String min) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min); - } - - @Override - public Set zrangeByScore(final String key, final String min, final String max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScore(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByScore(final String key, final String max, final String min, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScore(key, max, min, offset, count); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final String max, final String min) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min); - } - - @Override - public Set zrangeByScoreWithScores(final String key, final String min, final String max, - final int offset, final int count) { - Jedis j = getShard(key); - return j.zrangeByScoreWithScores(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByScoreWithScores(final String key, final String max, - final String min, final int offset, final int count) { - Jedis j = getShard(key); - return j.zrevrangeByScoreWithScores(key, max, min, offset, count); - } - - @Override - public long zremrangeByRank(final String key, final long start, final long stop) { - Jedis j = getShard(key); - return j.zremrangeByRank(key, start, stop); - } - - @Override - public long zremrangeByScore(final String key, final double min, final double max) { - Jedis j = getShard(key); - return j.zremrangeByScore(key, min, max); - } - - @Override - public long zremrangeByScore(final String key, final String min, final String max) { - Jedis j = getShard(key); - return j.zremrangeByScore(key, min, max); - } - - @Override - public long zlexcount(final String key, final String min, final String max) { - return getShard(key).zlexcount(key, min, max); - } - - @Override - public Set zrangeByLex(final String key, final String min, final String max) { - return getShard(key).zrangeByLex(key, min, max); - } - - @Override - public Set zrangeByLex(final String key, final String min, final String max, - final int offset, final int count) { - return getShard(key).zrangeByLex(key, min, max, offset, count); - } - - @Override - public Set zrevrangeByLex(final String key, final String max, final String min) { - return getShard(key).zrevrangeByLex(key, max, min); - } - - @Override - public Set zrevrangeByLex(final String key, final String max, final String min, - final int offset, final int count) { - return getShard(key).zrevrangeByLex(key, max, min, offset, count); - } - - @Override - public long zremrangeByLex(final String key, final String min, final String max) { - return getShard(key).zremrangeByLex(key, min, max); - } - - @Override - public long linsert(final String key, final ListPosition where, final String pivot, - final String value) { - Jedis j = getShard(key); - return j.linsert(key, where, pivot, value); - } - - @Override - public long bitcount(final String key) { - Jedis j = getShard(key); - return j.bitcount(key); - } - - @Override - public long bitcount(final String key, final long start, final long end) { - Jedis j = getShard(key); - return j.bitcount(key, start, end); - } - - @Override - public long bitpos(final String key, final boolean value) { - Jedis j = getShard(key); - return j.bitpos(key, value); - } - - @Override - public long bitpos(final String key, boolean value, final BitPosParams params) { - Jedis j = getShard(key); - return j.bitpos(key, value, params); - } - - @Override - public ScanResult> hscan(final String key, final String cursor, - final ScanParams params) { - Jedis j = getShard(key); - return j.hscan(key, cursor, params); - } - - @Override - public ScanResult zscan(final String key, final String cursor, final ScanParams params) { - Jedis j = getShard(key); - return j.zscan(key, cursor, params); - } - - @Override - public ScanResult sscan(final String key, final String cursor, final ScanParams params) { - Jedis j = getShard(key); - return j.sscan(key, cursor, params); - } - - @Override - public void close() { - if (dataSource != null) { - boolean broken = false; - - for (Jedis jedis : getAllShards()) { - if (jedis.isBroken()) { - broken = true; - break; - } - } - ShardedJedisPool pool = this.dataSource; - this.dataSource = null; - if (broken) { - pool.returnBrokenResource(this); - } else { - pool.returnResource(this); - } - - } else { - disconnect(); - } - } - - public void setDataSource(ShardedJedisPool shardedJedisPool) { - this.dataSource = shardedJedisPool; - } - - public void resetState() { - for (Jedis jedis : getAllShards()) { - jedis.resetState(); - } - } - - @Override - public long pfadd(final String key, final String... elements) { - Jedis j = getShard(key); - return j.pfadd(key, elements); - } - - @Override - public long pfcount(final String key) { - Jedis j = getShard(key); - return j.pfcount(key); - } - - @Override - public long touch(final String key) { - Jedis j = getShard(key); - return j.touch(key); - } - - @Override - public long geoadd(final String key, final double longitude, final double latitude, - final String member) { - Jedis j = getShard(key); - return j.geoadd(key, longitude, latitude, member); - } - - @Override - public long geoadd(final String key, final Map memberCoordinateMap) { - Jedis j = getShard(key); - return j.geoadd(key, memberCoordinateMap); - } - - @Override - public long geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { - Jedis j = getShard(key); - return j.geoadd(key, params, memberCoordinateMap); - } - - @Override - public Double geodist(final String key, final String member1, final String member2) { - Jedis j = getShard(key); - return j.geodist(key, member1, member2); - } - - @Override - public Double geodist(final String key, final String member1, final String member2, - final GeoUnit unit) { - Jedis j = getShard(key); - return j.geodist(key, member1, member2, unit); - } - - @Override - public List geohash(final String key, final String... members) { - Jedis j = getShard(key); - return j.geohash(key, members); - } - - @Override - public List geopos(final String key, final String... members) { - Jedis j = getShard(key); - return j.geopos(key, members); - } - - @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadius(key, longitude, latitude, radius, unit); - } - - @Override - public List georadiusReadonly(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadiusReadonly(key, longitude, latitude, radius, unit); - } - - @Override - public List georadius(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadius(key, longitude, latitude, radius, unit, param); - } - - @Override - public List georadiusReadonly(final String key, final double longitude, - final double latitude, final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadiusReadonly(key, longitude, latitude, radius, unit, param); - } - - @Override - public List georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadiusByMember(key, member, radius, unit); - } - - @Override - public List georadiusByMemberReadonly(final String key, final String member, - final double radius, final GeoUnit unit) { - Jedis j = getShard(key); - return j.georadiusByMemberReadonly(key, member, radius, unit); - } - - @Override - public List georadiusByMember(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadiusByMember(key, member, radius, unit, param); - } - - @Override - public List georadiusByMemberReadonly(final String key, final String member, - final double radius, final GeoUnit unit, final GeoRadiusParam param) { - Jedis j = getShard(key); - return j.georadiusByMemberReadonly(key, member, radius, unit, param); - } - - @Override - public List bitfield(final String key, final String... arguments) { - Jedis j = getShard(key); - return j.bitfield(key, arguments); - } - - @Override - public List bitfieldReadonly(String key, final String... arguments) { - Jedis j = getShard(key); - return j.bitfieldReadonly(key, arguments); - } - - @Override - public long hstrlen(final String key, final String field) { - Jedis j = getShard(key); - return j.hstrlen(key, field); - } - - @Override - public Long memoryUsage(String key) { - Jedis j = getShard(key); - return j.memoryUsage(key); - } - - @Override - public Long memoryUsage(String key, int samples) { - Jedis j = getShard(key); - return j.memoryUsage(key, samples); - } - - @Override - public StreamEntryID xadd(String key, StreamEntryID id, Map hash) { - Jedis j = getShard(key); - return j.xadd(key, id, hash); - } - - @Override - public StreamEntryID xadd(String key, StreamEntryID id, Map hash, long maxLen, - boolean approximateLength) { - Jedis j = getShard(key); - return j.xadd(key, id, hash, maxLen, approximateLength); - } - - @Override - public StreamEntryID xadd(final String key, final Map hash, final XAddParams params) { - Jedis j = getShard(key); - return j.xadd(key, hash, params); - } - - @Override - public long xlen(String key) { - Jedis j = getShard(key); - return j.xlen(key); - } - - @Override - public List xrange(String key, StreamEntryID start, StreamEntryID end) { - Jedis j = getShard(key); - return j.xrange(key, start, end); - } - - @Override - public List xrange(String key, StreamEntryID start, StreamEntryID end, int count) { - Jedis j = getShard(key); - return j.xrange(key, start, end, count); - } - - @Override - public long xack(String key, String group, StreamEntryID... ids) { - Jedis j = getShard(key); - return j.xack(key, group, ids); - } - - @Override - public String xgroupCreate(String key, String consumer, StreamEntryID id, boolean makeStream) { - Jedis j = getShard(key); - return j.xgroupCreate(key, consumer, id, makeStream); - } - - @Override - public String xgroupSetID(String key, String groupname, StreamEntryID id) { - Jedis j = getShard(key); - return j.xgroupSetID(key, groupname, id); - } - - @Override - public long xgroupDestroy(String key, String groupname) { - Jedis j = getShard(key); - return j.xgroupDestroy(key, groupname); - } - - @Override - public long xgroupDelConsumer(String key, String groupname, String consumername) { - Jedis j = getShard(key); - return j.xgroupDelConsumer(key, groupname, consumername); - } - - @Override - public long xdel(String key, StreamEntryID... ids) { - Jedis j = getShard(key); - return j.xdel(key, ids); - } - - @Override - public long xtrim(String key, long maxLen, boolean approximateLength) { - Jedis j = getShard(key); - return j.xtrim(key, maxLen, approximateLength); - } - - @Override - public long xtrim(String key, XTrimParams params) { - Jedis j = getShard(key); - return j.xtrim(key, params); - } - - @Override - public List xrevrange(String key, StreamEntryID end, StreamEntryID start) { - Jedis j = getShard(key); - return j.xrevrange(key, end, start); - } - - @Override - public List xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { - Jedis j = getShard(key); - return j.xrevrange(key, end, start, count); - } - - @Override - public StreamPendingSummary xpending(String key, String groupname) { - Jedis j = getShard(key); - return j.xpending(key, groupname); - } - - @Override - public List xpending(String key, String groupname, StreamEntryID start, - StreamEntryID end, int count, String consumername) { - Jedis j = getShard(key); - return j.xpending(key, groupname, start, end, count, consumername); - } - - @Override - public List xpending(String key, String groupname, XPendingParams params) { - Jedis j = getShard(key); - return j.xpending(key, groupname, params); - } - - @Override - public List xclaim(String key, String group, String consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, StreamEntryID... ids) { - Jedis j = getShard(key); - return j.xclaim(key, group, consumername, minIdleTime, newIdleTime, retries, force, ids); - } - - @Override - public List xclaim(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids) { - Jedis j = getShard(key); - return j.xclaim(key, group, consumername, minIdleTime, params, ids); - } - - @Override - public List xclaimJustId(String key, String group, String consumername, - long minIdleTime, XClaimParams params, StreamEntryID... ids) { - Jedis j = getShard(key); - return j.xclaimJustId(key, group, consumername, minIdleTime, params, ids); - } - - @Override - public Map.Entry> xautoclaim(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params) { - Jedis j = getShard(key); - return j.xautoclaim(key, group, consumerName, minIdleTime, start, params); - } - - @Override - public Map.Entry> xautoclaimJustId(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params) { - Jedis j = getShard(key); - return j.xautoclaimJustId(key, group, consumerName, minIdleTime, start, params); - } - - @Override - public StreamInfo xinfoStream(String key) { - - Jedis j = getShard(key); - return j.xinfoStream(key); - } - - @Override - public List xinfoGroup(String key) { - - Jedis j = getShard(key); - return j.xinfoGroup(key); - } - - @Override - public List xinfoConsumers(String key, String group) { - Jedis j = getShard(key); - return j.xinfoConsumers(key, group); - } - - public Object sendCommand(ProtocolCommand cmd, String... args) { - // default since no sample key provided in JedisCommands interface - String sampleKey = args.length > 0 ? args[0] : cmd.toString(); - Jedis j = getShard(sampleKey); - return j.sendCommand(cmd, args); - } - - public Object sendBlockingCommand(ProtocolCommand cmd, String... args) { - // default since no sample key provided in JedisCommands interface - String sampleKey = args.length > 0 ? args[0] : cmd.toString(); - Jedis j = getShard(sampleKey); - return j.sendBlockingCommand(cmd, args); - } - - @Override - public LCSMatchResult strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params) { - Jedis j = getShard(""); - return j.strAlgoLCSStrings(strA, strB, params); - } -} diff --git a/src/main/java/redis/clients/jedis/ShardedJedisPool.java b/src/main/java/redis/clients/jedis/ShardedJedisPool.java deleted file mode 100644 index 352d23fa81..0000000000 --- a/src/main/java/redis/clients/jedis/ShardedJedisPool.java +++ /dev/null @@ -1,128 +0,0 @@ -package redis.clients.jedis; - -import java.util.List; -import java.util.regex.Pattern; - -import org.apache.commons.pool2.PooledObject; -import org.apache.commons.pool2.PooledObjectFactory; -import org.apache.commons.pool2.impl.DefaultPooledObject; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import redis.clients.jedis.util.Hashing; -import redis.clients.jedis.util.Pool; - -public class ShardedJedisPool extends Pool { - - private static final Logger logger = LoggerFactory.getLogger(ShardedJedisPool.class); - - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - List shards) { - this(poolConfig, shards, Hashing.MURMUR_HASH); - } - - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - List shards, Hashing algo) { - this(poolConfig, shards, algo, null); - } - - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - List shards, Pattern keyTagPattern) { - this(poolConfig, shards, Hashing.MURMUR_HASH, keyTagPattern); - } - - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - List shards, Hashing algo, Pattern keyTagPattern) { - this(poolConfig, new ShardedJedisFactory(shards, algo, keyTagPattern)); - } - - public ShardedJedisPool(final GenericObjectPoolConfig poolConfig, - PooledObjectFactory shardedJedisPooledObjectFactory) { - super(poolConfig, shardedJedisPooledObjectFactory); - } - - @Override - public ShardedJedis getResource() { - ShardedJedis jedis = super.getResource(); - jedis.setDataSource(this); - return jedis; - } - - @Override - public void returnResource(final ShardedJedis resource) { - if (resource != null) { - resource.resetState(); - super.returnResource(resource); - } - } - - /** - * PoolableObjectFactory custom impl. - */ - public static class ShardedJedisFactory implements PooledObjectFactory { - - private final List shards; - private final Hashing algo; - private final Pattern keyTagPattern; - - public ShardedJedisFactory(List shards, Hashing algo, Pattern keyTagPattern) { - this.shards = shards; - this.algo = algo; - this.keyTagPattern = keyTagPattern; - } - - @Override - public PooledObject makeObject() throws Exception { - ShardedJedis jedis = new ShardedJedis(shards, algo, keyTagPattern); - return new DefaultPooledObject<>(jedis); - } - - @Override - public void destroyObject(PooledObject pooledShardedJedis) throws Exception { - final ShardedJedis shardedJedis = pooledShardedJedis.getObject(); - for (Jedis jedis : shardedJedis.getAllShards()) { - if (jedis.isConnected()) { - try { - // need a proper test, probably with mock - if (!jedis.isBroken()) { - jedis.quit(); - } - } catch (RuntimeException e) { - logger.warn("Error while QUIT", e); - } - try { - jedis.disconnect(); - } catch (RuntimeException e) { - logger.warn("Error while disconnect", e); - } - } - } - } - - @Override - public boolean validateObject(PooledObject pooledShardedJedis) { - try { - ShardedJedis jedis = pooledShardedJedis.getObject(); - for (Jedis shard : jedis.getAllShards()) { - if (!shard.ping().equals("PONG")) { - return false; - } - } - return true; - } catch (RuntimeException ex) { - return false; - } - } - - @Override - public void activateObject(PooledObject p) throws Exception { - - } - - @Override - public void passivateObject(PooledObject p) throws Exception { - - } - } -} diff --git a/src/main/java/redis/clients/jedis/ShardedPipeline.java b/src/main/java/redis/clients/jedis/ShardedPipeline.java new file mode 100644 index 0000000000..d2afd848c4 --- /dev/null +++ b/src/main/java/redis/clients/jedis/ShardedPipeline.java @@ -0,0 +1,29 @@ +package redis.clients.jedis; + +import redis.clients.jedis.providers.ShardedConnectionProvider; +import java.util.regex.Pattern; + +public class ShardedPipeline extends MultiNodePipelineBase { + + private final ShardedConnectionProvider provider; + + public ShardedPipeline(ShardedConnectionProvider provider) { + super(new ShardedCommandObjects(provider.getHashingAlgo())); + this.provider = provider; + } + + public ShardedPipeline(ShardedConnectionProvider provider, Pattern tagPattern) { + super(new ShardedCommandObjects(provider.getHashingAlgo(), tagPattern)); + this.provider = provider; + } + + @Override + protected HostAndPort getNodeKey(CommandArguments args) { + return provider.getNode(((ShardedCommandArguments) args).getKeyHash()); + } + + @Override + protected Connection getConnection(HostAndPort nodeKey) { + return provider.getConnection(nodeKey); + } +} diff --git a/src/main/java/redis/clients/jedis/Transaction.java b/src/main/java/redis/clients/jedis/Transaction.java index f2b09b702d..278e5fd4bd 100644 --- a/src/main/java/redis/clients/jedis/Transaction.java +++ b/src/main/java/redis/clients/jedis/Transaction.java @@ -1,94 +1,68 @@ package redis.clients.jedis; -import java.io.Closeable; -import java.util.ArrayList; import java.util.List; -import redis.clients.jedis.exceptions.JedisDataException; +public class Transaction extends TransactionBase { -/** - * Transaction is nearly identical to Pipeline, only differences are the multi/discard behaviors - */ -public class Transaction extends MultiKeyPipelineBase implements Closeable { + private final Jedis jedis; - protected boolean inTransaction = true; + public Transaction(Jedis jedis) { + super(jedis.getConnection()); + this.jedis = jedis; + } - protected Transaction() { - // client will be set later in transaction block + public Transaction(Connection connection) { + super(connection); + this.jedis = null; } - public Transaction(final Client client) { - this.client = client; + /** + * If you want to WATCH/UNWATCH keys before MULTI command you should do {@code doMulti = true}. + */ + public Transaction(Connection connection, boolean doMulti) { + super(connection, doMulti); + this.jedis = null; } @Override - protected Client getClient(String key) { - return client; + protected final void processMultiResponse() { + // do nothing } @Override - protected Client getClient(byte[] key) { - return client; + protected final void processAppendStatus() { + // do nothing } - public void clear() { - if (inTransaction) { - discard(); - } + @Override + protected final void processPipelinedResponses() { + // ignore QUEUED or ERROR + connection.getMany(1 + getPipelinedResponseLength()); } - public List exec() { - // Discard QUEUED or ERROR - client.getMany(getPipelinedResponseLength()); - client.exec(); - inTransaction = false; - - List unformatted = client.getObjectMultiBulkReply(); - if (unformatted == null) { - return null; - } - List formatted = new ArrayList<>(); - for (Object o : unformatted) { - try { - formatted.add(generateResponse(o).get()); - } catch (JedisDataException e) { - formatted.add(e); + @Override + public final List exec() { + List ret; + try { + ret = super.exec(); + } finally { + if (jedis != null) { + jedis.resetState(); } } - return formatted; - } - - public List> execGetResponse() { - // Discard QUEUED or ERROR - client.getMany(getPipelinedResponseLength()); - client.exec(); - inTransaction = false; - - List unformatted = client.getObjectMultiBulkReply(); - if (unformatted == null) { - return null; - } - List> response = new ArrayList<>(); - for (Object o : unformatted) { - response.add(generateResponse(o)); - } - return response; - } - - public String discard() { - client.getMany(getPipelinedResponseLength()); - client.discard(); - inTransaction = false; - clean(); - return client.getStatusCodeReply(); - } - - public void setClient(Client client) { - this.client = client; + return ret; } @Override - public void close() { - clear(); + public final String discard() { + String ret; + try { + ret = super.discard(); + } finally { + if (jedis != null) { + jedis.resetState(); + } + } + return ret; } } diff --git a/src/main/java/redis/clients/jedis/TransactionBase.java b/src/main/java/redis/clients/jedis/TransactionBase.java new file mode 100644 index 0000000000..28fc6ebea4 --- /dev/null +++ b/src/main/java/redis/clients/jedis/TransactionBase.java @@ -0,0 +1,3078 @@ +package redis.clients.jedis; + +import static redis.clients.jedis.Protocol.Command.DISCARD; +import static redis.clients.jedis.Protocol.Command.EXEC; +import static redis.clients.jedis.Protocol.Command.MULTI; +import static redis.clients.jedis.Protocol.Command.UNWATCH; +import static redis.clients.jedis.Protocol.Command.WATCH; + +import java.io.Closeable; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.json.JSONArray; + +import redis.clients.jedis.args.*; +import redis.clients.jedis.commands.PipelineBinaryCommands; +import redis.clients.jedis.commands.PipelineCommands; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.commands.RedisModulePipelineCommands; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; +import redis.clients.jedis.search.*; + +public abstract class TransactionBase extends Queable implements PipelineCommands, + PipelineBinaryCommands, RedisModulePipelineCommands, Closeable { + + protected final Connection connection; + private final CommandObjects commandObjects; + + private boolean inWatch = false; + private boolean inMulti = false; + + public TransactionBase(Connection connection) { + this(connection, true); + } + + /** + * If you want to WATCH/UNWATCH keys before MULTI command you should do {@code doMulti = true}. + */ + public TransactionBase(Connection connection, boolean doMulti) { + this.connection = connection; + this.commandObjects = new CommandObjects(); + if (doMulti) multi(); + } + + public final void multi() { + connection.sendCommand(MULTI); + processMultiResponse(); + inMulti = true; + } + + public String watch(final String... keys) { + connection.sendCommand(WATCH, keys); + String status = connection.getStatusCodeReply(); + inWatch = true; + return status; + } + + public String watch(final byte[]... keys) { + connection.sendCommand(WATCH, keys); + String status = connection.getStatusCodeReply(); + inWatch = true; + return status; + } + + public String unwatch() { + connection.sendCommand(UNWATCH); + String status = connection.getStatusCodeReply(); + inWatch = false; + return status; + } + + protected abstract void processMultiResponse(); + + protected abstract void processAppendStatus(); + + protected final Response appendCommand(CommandObject commandObject) { + connection.sendCommand(commandObject.getArguments()); + processAppendStatus(); + return enqueResponse(commandObject.getBuilder()); + } + + @Override + public final void close() { + clear(); + } + + public final void clear() { + if (inMulti) { + discard(); + } else if (inWatch) { + unwatch(); + } + } + + protected abstract void processPipelinedResponses(); + + public List exec() { + if (!inMulti) throw new IllegalStateException("EXEC without MULTI"); + // ignore QUEUED or ERROR +// connection.getMany(1 + getPipelinedResponseLength()); + processPipelinedResponses(); + connection.sendCommand(EXEC); + inMulti = false; + inWatch = false; + + List unformatted = connection.getObjectMultiBulkReply(); + if (unformatted == null) { + clean(); + return null; + } + List formatted = new ArrayList<>(unformatted.size()); + for (Object o : unformatted) { + try { + formatted.add(generateResponse(o).get()); + } catch (JedisDataException e) { + formatted.add(e); + } + } + return formatted; + } + + public String discard() { + if (!inMulti) throw new IllegalStateException("DISCARD without MULTI"); + // ignore QUEUED or ERROR +// connection.getMany(1 + getPipelinedResponseLength()); + processPipelinedResponses(); + connection.sendCommand(DISCARD); + String status = connection.getStatusCodeReply(); // OK + inMulti = false; + inWatch = false; + clean(); + return status; + } + + @Override + public Response exists(String key) { + return appendCommand(commandObjects.exists(key)); + } + + @Override + public Response exists(String... keys) { + return appendCommand(commandObjects.exists(keys)); + } + + @Override + public Response persist(String key) { + return appendCommand(commandObjects.persist(key)); + } + + @Override + public Response type(String key) { + return appendCommand(commandObjects.type(key)); + } + + @Override + public Response dump(String key) { + return appendCommand(commandObjects.dump(key)); + } + + @Override + public Response restore(String key, long ttl, byte[] serializedValue) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public Response restore(String key, long ttl, byte[] serializedValue, RestoreParams params) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public Response expire(String key, long seconds) { + return appendCommand(commandObjects.expire(key, seconds)); + } + + @Override + public Response pexpire(String key, long milliseconds) { + return appendCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public Response expireAt(String key, long unixTime) { + return appendCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public Response pexpireAt(String key, long millisecondsTimestamp) { + return appendCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public Response ttl(String key) { + return appendCommand(commandObjects.ttl(key)); + } + + @Override + public Response pttl(String key) { + return appendCommand(commandObjects.pttl(key)); + } + + @Override + public Response touch(String key) { + return appendCommand(commandObjects.touch(key)); + } + + @Override + public Response touch(String... keys) { + return appendCommand(commandObjects.touch(keys)); + } + + @Override + public Response> sort(String key) { + return appendCommand(commandObjects.sort(key)); + } + + @Override + public Response sort(String key, String dstKey) { + return appendCommand(commandObjects.sort(key, dstKey)); + } + + @Override + public Response> sort(String key, SortingParams sortingParameters) { + return appendCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public Response sort(String key, SortingParams sortingParameters, String dstKey) { + return appendCommand(commandObjects.sort(key, sortingParameters, dstKey)); + } + + @Override + public Response del(String key) { + return appendCommand(commandObjects.del(key)); + } + + @Override + public Response del(String... keys) { + return appendCommand(commandObjects.del(keys)); + } + + @Override + public Response unlink(String key) { + return appendCommand(commandObjects.unlink(key)); + } + + @Override + public Response unlink(String... keys) { + return appendCommand(commandObjects.unlink(keys)); + } + + @Override + public Response copy(String srcKey, String dstKey, boolean replace) { + return appendCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public Response rename(String oldkey, String newkey) { + return appendCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public Response renamenx(String oldkey, String newkey) { + return appendCommand(commandObjects.renamenx(oldkey, newkey)); + } + + @Override + public Response memoryUsage(String key) { + return appendCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Response memoryUsage(String key, int samples) { + return appendCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Response objectRefcount(String key) { + return appendCommand(commandObjects.objectRefcount(key)); + } + + @Override + public Response objectEncoding(String key) { + return appendCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Response objectIdletime(String key) { + return appendCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Response objectFreq(String key) { + return appendCommand(commandObjects.objectFreq(key)); + } + + @Override + public Response migrate(String host, int port, String key, int timeout) { + return appendCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public Response migrate(String host, int port, int timeout, MigrateParams params, String... keys) { + return appendCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public Response> keys(String pattern) { + return appendCommand(commandObjects.keys(pattern)); + } + + @Override + public Response> scan(String cursor) { + return appendCommand(commandObjects.scan(cursor)); + } + + @Override + public Response> scan(String cursor, ScanParams params) { + return appendCommand(commandObjects.scan(cursor, params)); + } + + @Override + public Response> scan(String cursor, ScanParams params, String type) { + return appendCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Response randomKey() { + return appendCommand(commandObjects.randomKey()); + } + + @Override + public Response get(String key) { + return appendCommand(commandObjects.get(key)); + } + + @Override + public Response getDel(String key) { + return appendCommand(commandObjects.getDel(key)); + } + + @Override + public Response getEx(String key, GetExParams params) { + return appendCommand(commandObjects.getEx(key, params)); + } + + @Override + public Response setbit(String key, long offset, boolean value) { + return appendCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public Response getbit(String key, long offset) { + return appendCommand(commandObjects.getbit(key, offset)); + } + + @Override + public Response setrange(String key, long offset, String value) { + return appendCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public Response getrange(String key, long startOffset, long endOffset) { + return appendCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public Response getSet(String key, String value) { + return appendCommand(commandObjects.getSet(key, value)); + } + + @Override + public Response setnx(String key, String value) { + return appendCommand(commandObjects.setnx(key, value)); + } + + @Override + public Response setex(String key, long seconds, String value) { + return appendCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public Response psetex(String key, long milliseconds, String value) { + return appendCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public Response> mget(String... keys) { + return appendCommand(commandObjects.mget(keys)); + } + + @Override + public Response mset(String... keysvalues) { + return appendCommand(commandObjects.mset(keysvalues)); + } + + @Override + public Response msetnx(String... keysvalues) { + return appendCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public Response incr(String key) { + return appendCommand(commandObjects.incr(key)); + } + + @Override + public Response incrBy(String key, long increment) { + return appendCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public Response incrByFloat(String key, double increment) { + return appendCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public Response decr(String key) { + return appendCommand(commandObjects.decr(key)); + } + + @Override + public Response decrBy(String key, long decrement) { + return appendCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public Response append(String key, String value) { + return appendCommand(commandObjects.append(key, value)); + } + + @Override + public Response substr(String key, int start, int end) { + return appendCommand(commandObjects.substr(key, start, end)); + } + + @Override + public Response strlen(String key) { + return appendCommand(commandObjects.strlen(key)); + } + + @Override + public Response bitcount(String key) { + return appendCommand(commandObjects.bitcount(key)); + } + + @Override + public Response bitcount(String key, long start, long end) { + return appendCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public Response bitpos(String key, boolean value) { + return appendCommand(commandObjects.bitpos(key, value)); + } + + @Override + public Response bitpos(String key, boolean value, BitPosParams params) { + return appendCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public Response> bitfield(String key, String... arguments) { + return appendCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public Response> bitfieldReadonly(String key, String... arguments) { + return appendCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public Response bitop(BitOP op, String destKey, String... srcKeys) { + return appendCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public Response strAlgoLCSKeys(String keyA, String keyB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); + } + + @Override + public Response set(String key, String value) { + return appendCommand(commandObjects.set(key, value)); + } + + @Override + public Response set(String key, String value, SetParams params) { + return appendCommand(commandObjects.set(key, value, params)); + } + + @Override + public Response rpush(String key, String... string) { + return appendCommand(commandObjects.rpush(key, string)); + + } + + @Override + public Response lpush(String key, String... string) { + return appendCommand(commandObjects.lpush(key, string)); + } + + @Override + public Response llen(String key) { + return appendCommand(commandObjects.llen(key)); + } + + @Override + public Response> lrange(String key, long start, long stop) { + return appendCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public Response ltrim(String key, long start, long stop) { + return appendCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public Response lindex(String key, long index) { + return appendCommand(commandObjects.lindex(key, index)); + } + + @Override + public Response lset(String key, long index, String value) { + return appendCommand(commandObjects.lset(key, index, value)); + } + + @Override + public Response lrem(String key, long count, String value) { + return appendCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public Response lpop(String key) { + return appendCommand(commandObjects.lpop(key)); + } + + @Override + public Response> lpop(String key, int count) { + return appendCommand(commandObjects.lpop(key, count)); + } + + @Override + public Response lpos(String key, String element) { + return appendCommand(commandObjects.lpos(key, element)); + } + + @Override + public Response lpos(String key, String element, LPosParams params) { + return appendCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public Response> lpos(String key, String element, LPosParams params, long count) { + return appendCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Response rpop(String key) { + return appendCommand(commandObjects.rpop(key)); + } + + @Override + public Response> rpop(String key, int count) { + return appendCommand(commandObjects.rpop(key, count)); + } + + @Override + public Response linsert(String key, ListPosition where, String pivot, String value) { + return appendCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public Response lpushx(String key, String... string) { + return appendCommand(commandObjects.lpushx(key, string)); + } + + @Override + public Response rpushx(String key, String... string) { + return appendCommand(commandObjects.rpushx(key, string)); + } + + @Override + public Response> blpop(int timeout, String key) { + return appendCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public Response blpop(double timeout, String key) { + return appendCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public Response> brpop(int timeout, String key) { + return appendCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public Response brpop(double timeout, String key) { + return appendCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public Response> blpop(int timeout, String... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response blpop(double timeout, String... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> brpop(int timeout, String... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response brpop(double timeout, String... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response rpoplpush(String srcKey, String dstKey) { + return appendCommand(commandObjects.rpoplpush(srcKey, dstKey)); + } + + @Override + public Response brpoplpush(String source, String destination, int timeout) { + return appendCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public Response lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { + return appendCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public Response blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout) { + return appendCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + @Override + public Response hset(String key, String field, String value) { + return appendCommand(commandObjects.hset(key, field, value)); + } + + @Override + public Response hset(String key, Map hash) { + return appendCommand(commandObjects.hset(key, hash)); + } + + @Override + public Response hget(String key, String field) { + return appendCommand(commandObjects.hget(key, field)); + } + + @Override + public Response hsetnx(String key, String field, String value) { + return appendCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public Response hmset(String key, Map hash) { + return appendCommand(commandObjects.hmset(key, hash)); + } + + @Override + public Response> hmget(String key, String... fields) { + return appendCommand(commandObjects.hmget(key, fields)); + } + + @Override + public Response hincrBy(String key, String field, long value) { + return appendCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public Response hincrByFloat(String key, String field, double value) { + return appendCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public Response hexists(String key, String field) { + return appendCommand(commandObjects.hexists(key, field)); + } + + @Override + public Response hdel(String key, String... field) { + return appendCommand(commandObjects.hdel(key, field)); + } + + @Override + public Response hlen(String key) { + return appendCommand(commandObjects.hlen(key)); + } + + @Override + public Response> hkeys(String key) { + return appendCommand(commandObjects.hkeys(key)); + } + + @Override + public Response> hvals(String key) { + return appendCommand(commandObjects.hvals(key)); + } + + @Override + public Response> hgetAll(String key) { + return appendCommand(commandObjects.hgetAll(key)); + } + + @Override + public Response hrandfield(String key) { + return appendCommand(commandObjects.hrandfield(key)); + } + + @Override + public Response> hrandfield(String key, long count) { + return appendCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Response> hrandfieldWithValues(String key, long count) { + return appendCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public Response>> hscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public Response hstrlen(String key, String field) { + return appendCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public Response sadd(String key, String... member) { + return appendCommand(commandObjects.sadd(key, member)); + } + + @Override + public Response> smembers(String key) { + return appendCommand(commandObjects.smembers(key)); + } + + @Override + public Response srem(String key, String... member) { + return appendCommand(commandObjects.srem(key, member)); + } + + @Override + public Response spop(String key) { + return appendCommand(commandObjects.spop(key)); + } + + @Override + public Response> spop(String key, long count) { + return appendCommand(commandObjects.spop(key, count)); + } + + @Override + public Response scard(String key) { + return appendCommand(commandObjects.scard(key)); + } + + @Override + public Response sismember(String key, String member) { + return appendCommand(commandObjects.sismember(key, member)); + } + + @Override + public Response> smismember(String key, String... members) { + return appendCommand(commandObjects.smismember(key, members)); + } + + @Override + public Response srandmember(String key) { + return appendCommand(commandObjects.srandmember(key)); + } + + @Override + public Response> srandmember(String key, int count) { + return appendCommand(commandObjects.srandmember(key, count)); + } + + @Override + public Response> sscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Response> sdiff(String... keys) { + return appendCommand(commandObjects.sdiff(keys)); + } + + @Override + public Response sdiffstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sdiffstore(dstKey, keys)); + } + + @Override + public Response> sinter(String... keys) { + return appendCommand(commandObjects.sinter(keys)); + } + + @Override + public Response sinterstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sinterstore(dstKey, keys)); + } + + @Override + public Response> sunion(String... keys) { + return appendCommand(commandObjects.sunion(keys)); + } + + @Override + public Response sunionstore(String dstKey, String... keys) { + return appendCommand(commandObjects.sunionstore(dstKey, keys)); + } + + @Override + public Response smove(String srcKey, String dstKey, String member) { + return appendCommand(commandObjects.smove(srcKey, dstKey, member)); + } + + @Override + public Response zadd(String key, double score, String member) { + return appendCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public Response zadd(String key, double score, String member, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public Response zadd(String key, Map scoreMembers) { + return appendCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public Response zadd(String key, Map scoreMembers, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Response zaddIncr(String key, double score, String member, ZAddParams params) { + return appendCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Response zrem(String key, String... members) { + return appendCommand(commandObjects.zrem(key, members)); + } + + @Override + public Response zincrby(String key, double increment, String member) { + return appendCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Response zincrby(String key, double increment, String member, ZIncrByParams params) { + return appendCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Response zrank(String key, String member) { + return appendCommand(commandObjects.zrank(key, member)); + } + + @Override + public Response zrevrank(String key, String member) { + return appendCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public Response> zrange(String key, long start, long stop) { + return appendCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public Response> zrevrange(String key, long start, long stop) { + return appendCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public Response> zrangeWithScores(String key, long start, long stop) { + return appendCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public Response> zrevrangeWithScores(String key, long start, long stop) { + return appendCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public Response zrandmember(String key) { + return appendCommand(commandObjects.zrandmember(key)); + } + + @Override + public Response> zrandmember(String key, long count) { + return appendCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public Response> zrandmemberWithScores(String key, long count) { + return appendCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public Response zcard(String key) { + return appendCommand(commandObjects.zcard(key)); + } + + @Override + public Response zscore(String key, String member) { + return appendCommand(commandObjects.zscore(key, member)); + } + + @Override + public Response> zmscore(String key, String... members) { + return appendCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Response zpopmax(String key) { + return appendCommand(commandObjects.zpopmax(key)); + } + + @Override + public Response> zpopmax(String key, int count) { + return appendCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Response zpopmin(String key) { + return appendCommand(commandObjects.zpopmin(key)); + } + + @Override + public Response> zpopmin(String key, int count) { + return appendCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public Response zcount(String key, double min, double max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response zcount(String key, String min, String max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response> zrangeByScore(String key, double min, double max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrevrangeByScore(String key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + + } + + @Override + public Response> zrangeByScore(String key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public Response> zrangeByScore(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, double min, double max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public Response> zrangeByScoreWithScores(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByRank(String key, long start, long stop) { + return appendCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public Response zremrangeByScore(String key, double min, double max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zremrangeByScore(String key, String min, String max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zlexcount(String key, String min, String max) { + return appendCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public Response> zrangeByLex(String key, String min, String max) { + return appendCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public Response> zrangeByLex(String key, String min, String max, int offset, int count) { + return appendCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByLex(String key, String max, String min) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public Response> zrevrangeByLex(String key, String max, String min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public Response zremrangeByLex(String key, String min, String max) { + return appendCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public Response> zscan(String key, String cursor, ScanParams params) { + return appendCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public Response bzpopmax(double timeout, String... keys) { + return appendCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public Response bzpopmin(double timeout, String... keys) { + return appendCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Response> zdiff(String... keys) { + return appendCommand(commandObjects.zdiff(keys)); + } + + @Override + public Response> zdiffWithScores(String... keys) { + return appendCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public Response zdiffStore(String dstKey, String... keys) { + return appendCommand(commandObjects.zdiffStore(dstKey, keys)); + } + + @Override + public Response zinterstore(String dstKey, String... sets) { + return appendCommand(commandObjects.zinterstore(dstKey, sets)); + } + + @Override + public Response zinterstore(String dstKey, ZParams params, String... sets) { + return appendCommand(commandObjects.zinterstore(dstKey, params, sets)); + } + + @Override + public Response> zinter(ZParams params, String... keys) { + return appendCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Response> zinterWithScores(ZParams params, String... keys) { + return appendCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Response> zunion(ZParams params, String... keys) { + return appendCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Response> zunionWithScores(ZParams params, String... keys) { + return appendCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public Response zunionstore(String dstKey, String... sets) { + return appendCommand(commandObjects.zunionstore(dstKey, sets)); + } + + @Override + public Response zunionstore(String dstKey, ZParams params, String... sets) { + return appendCommand(commandObjects.zunionstore(dstKey, params, sets)); + } + + @Override + public Response geoadd(String key, double longitude, double latitude, String member) { + return appendCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public Response geoadd(String key, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public Response geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Response geodist(String key, String member1, String member2) { + return appendCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Response geodist(String key, String member1, String member2, GeoUnit unit) { + return appendCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public Response> geohash(String key, String... members) { + return appendCommand(commandObjects.geohash(key, members)); + } + + @Override + public Response> geopos(String key, String... members) { + return appendCommand(commandObjects.geopos(key, members)); + } + + @Override + public Response> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusByMember(String key, String member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMember(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public Response georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public Response georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public Response pfadd(String key, String... elements) { + return appendCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public Response pfmerge(String destkey, String... sourcekeys) { + return appendCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public Response pfcount(String key) { + return appendCommand(commandObjects.pfcount(key)); + } + + @Override + public Response pfcount(String... keys) { + return appendCommand(commandObjects.pfcount(keys)); + } + + @Override + public Response xadd(String key, StreamEntryID id, Map hash) { + return appendCommand(commandObjects.xadd(key, id, hash)); + } + + @Override + public Response xadd_v2(String key, XAddParams params, Map hash) { + return appendCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public Response xlen(String key) { + return appendCommand(commandObjects.xlen(key)); + } + + @Override + public Response> xrange(String key, StreamEntryID start, StreamEntryID end) { + return appendCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public Response> xrange(String key, StreamEntryID start, StreamEntryID end, int count) { + return appendCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start) { + return appendCommand(commandObjects.xrevrange(key, start, end)); + } + + @Override + public Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { + return appendCommand(commandObjects.xrevrange(key, start, end, count)); + } + + @Override + public Response xack(String key, String group, StreamEntryID... ids) { + return appendCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public Response xgroupCreate(String key, String groupname, StreamEntryID id, boolean makeStream) { + return appendCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public Response xgroupSetID(String key, String groupname, StreamEntryID id) { + return appendCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public Response xgroupDestroy(String key, String groupname) { + return appendCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public Response xgroupDelConsumer(String key, String groupname, String consumername) { + return appendCommand(commandObjects.xgroupDelConsumer(key, groupname, consumername)); + } + + @Override + public Response xpending(String key, String groupname) { + return appendCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public Response> xpending(String key, String groupname, StreamEntryID start, StreamEntryID end, int count, String consumername) { + return appendCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Response> xpending(String key, String groupname, XPendingParams params) { + return appendCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public Response xdel(String key, StreamEntryID... ids) { + return appendCommand(commandObjects.xdel(key, ids)); + } + + @Override + public Response xtrim(String key, long maxLen, boolean approximate) { + return appendCommand(commandObjects.xtrim(key, maxLen, approximate)); + } + + @Override + public Response xtrim(String key, XTrimParams params) { + return appendCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Response> xclaim(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return appendCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xclaimJustId(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return appendCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response>> xautoclaim(String key, String group, String consumername, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaim(key, group, consumername, minIdleTime, start, params)); + } + + @Override + public Response>> xautoclaimJustId(String key, String group, String consumername, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaimJustId(key, group, consumername, minIdleTime, start, params)); + } + + @Override + public Response xinfoStream(String key) { + return appendCommand(commandObjects.xinfoStream(key)); + } + + @Override + public Response> xinfoGroup(String key) { + return appendCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public Response> xinfoConsumers(String key, String group) { + return appendCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public Response>>> xread(XReadParams xReadParams, Map streams) { + return appendCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public Response>>> xreadGroup(String groupname, String consumer, XReadGroupParams xReadGroupParams, Map streams) { + return appendCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public Response eval(String script) { + return appendCommand(commandObjects.eval(script)); + } + + @Override + public Response eval(String script, int keyCount, String... params) { + return appendCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Response eval(String script, List keys, List args) { + return appendCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Response evalsha(String sha1) { + return appendCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Response evalsha(String sha1, int keyCount, String... params) { + return appendCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Response evalsha(String sha1, List keys, List args) { + return appendCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Response waitReplicas(String sampleKey, int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Response eval(String script, String sampleKey) { + return appendCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Response evalsha(String sha1, String sampleKey) { + return appendCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Response> scriptExists(String sampleKey, String... sha1) { + return appendCommand(commandObjects.scriptExists(sampleKey, sha1)); + } + + @Override + public Response scriptLoad(String script, String sampleKey) { + return appendCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public Response scriptFlush(String sampleKey) { + return appendCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public Response scriptFlush(String sampleKey, FlushMode flushMode) { + return appendCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public Response scriptKill(String sampleKey) { + return appendCommand(commandObjects.scriptKill(sampleKey)); + } + + public Response publish(String channel, String message) { + return appendCommand(commandObjects.publish(channel, message)); + } + + public Response strAlgoLCSStrings(String strA, String strB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public Response geoadd(byte[] key, double longitude, double latitude, byte[] member) { + return appendCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public Response geoadd(byte[] key, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public Response geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { + return appendCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Response geodist(byte[] key, byte[] member1, byte[] member2) { + return appendCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Response geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit) { + return appendCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public Response> geohash(byte[] key, byte[]... members) { + return appendCommand(commandObjects.geohash(key, members)); + } + + @Override + public Response> geopos(byte[] key, byte[]... members) { + return appendCommand(commandObjects.geopos(key, members)); + } + + @Override + public Response> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public Response> georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return appendCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public Response georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public Response georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return appendCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public Response hset(byte[] key, byte[] field, byte[] value) { + return appendCommand(commandObjects.hset(key, field, value)); + } + + @Override + public Response hset(byte[] key, Map hash) { + return appendCommand(commandObjects.hset(key, hash)); + } + + @Override + public Response hget(byte[] key, byte[] field) { + return appendCommand(commandObjects.hget(key, field)); + } + + @Override + public Response hsetnx(byte[] key, byte[] field, byte[] value) { + return appendCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public Response hmset(byte[] key, Map hash) { + return appendCommand(commandObjects.hmset(key, hash)); + } + + @Override + public Response> hmget(byte[] key, byte[]... fields) { + return appendCommand(commandObjects.hmget(key, fields)); + } + + @Override + public Response hincrBy(byte[] key, byte[] field, long value) { + return appendCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public Response hincrByFloat(byte[] key, byte[] field, double value) { + return appendCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public Response hexists(byte[] key, byte[] field) { + return appendCommand(commandObjects.hexists(key, field)); + } + + @Override + public Response hdel(byte[] key, byte[]... field) { + return appendCommand(commandObjects.hdel(key, field)); + } + + @Override + public Response hlen(byte[] key) { + return appendCommand(commandObjects.hlen(key)); + } + + @Override + public Response> hkeys(byte[] key) { + return appendCommand(commandObjects.hkeys(key)); + } + + @Override + public Response> hvals(byte[] key) { + return appendCommand(commandObjects.hvals(key)); + } + + @Override + public Response> hgetAll(byte[] key) { + return appendCommand(commandObjects.hgetAll(key)); + } + + @Override + public Response hrandfield(byte[] key) { + return appendCommand(commandObjects.hrandfield(key)); + } + + @Override + public Response> hrandfield(byte[] key, long count) { + return appendCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Response> hrandfieldWithValues(byte[] key, long count) { + return appendCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public Response>> hscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public Response hstrlen(byte[] key, byte[] field) { + return appendCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public Response pfadd(byte[] key, byte[]... elements) { + return appendCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public Response pfmerge(byte[] destkey, byte[]... sourcekeys) { + return appendCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public Response pfcount(byte[] key) { + return appendCommand(commandObjects.pfcount(key)); + } + + @Override + public Response pfcount(byte[]... keys) { + return appendCommand(commandObjects.pfcount(keys)); + } + + @Override + public Response exists(byte[] key) { + return appendCommand(commandObjects.exists(key)); + } + + @Override + public Response exists(byte[]... keys) { + return appendCommand(commandObjects.exists(keys)); + } + + @Override + public Response persist(byte[] key) { + return appendCommand(commandObjects.persist(key)); + } + + @Override + public Response type(byte[] key) { + return appendCommand(commandObjects.type(key)); + } + + @Override + public Response dump(byte[] key) { + return appendCommand(commandObjects.dump(key)); + } + + @Override + public Response restore(byte[] key, long ttl, byte[] serializedValue) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public Response restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params) { + return appendCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public Response expire(byte[] key, long seconds) { + return appendCommand(commandObjects.expire(key, seconds)); + } + + @Override + public Response pexpire(byte[] key, long milliseconds) { + return appendCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public Response expireAt(byte[] key, long unixTime) { + return appendCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public Response pexpireAt(byte[] key, long millisecondsTimestamp) { + return appendCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public Response ttl(byte[] key) { + return appendCommand(commandObjects.ttl(key)); + } + + @Override + public Response pttl(byte[] key) { + return appendCommand(commandObjects.pttl(key)); + } + + @Override + public Response touch(byte[] key) { + return appendCommand(commandObjects.touch(key)); + } + + @Override + public Response touch(byte[]... keys) { + return appendCommand(commandObjects.touch(keys)); + } + + @Override + public Response> sort(byte[] key) { + return appendCommand(commandObjects.sort(key)); + } + + @Override + public Response> sort(byte[] key, SortingParams sortingParameters) { + return appendCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public Response del(byte[] key) { + return appendCommand(commandObjects.del(key)); + } + + @Override + public Response del(byte[]... keys) { + return appendCommand(commandObjects.del(keys)); + } + + @Override + public Response unlink(byte[] key) { + return appendCommand(commandObjects.unlink(key)); + } + + @Override + public Response unlink(byte[]... keys) { + return appendCommand(commandObjects.unlink(keys)); + } + + @Override + public Response copy(byte[] srcKey, byte[] dstKey, boolean replace) { + return appendCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public Response rename(byte[] oldkey, byte[] newkey) { + return appendCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public Response renamenx(byte[] oldkey, byte[] newkey) { + return appendCommand(commandObjects.renamenx(oldkey, newkey)); + } + + @Override + public Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey) { + return appendCommand(commandObjects.sort(key, sortingParameters, dstkey)); + } + + @Override + public Response sort(byte[] key, byte[] dstkey) { + return appendCommand(commandObjects.sort(key, dstkey)); + } + + @Override + public Response memoryUsage(byte[] key) { + return appendCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Response memoryUsage(byte[] key, int samples) { + return appendCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Response objectRefcount(byte[] key) { + return appendCommand(commandObjects.objectRefcount(key)); + } + + @Override + public Response objectEncoding(byte[] key) { + return appendCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Response objectIdletime(byte[] key) { + return appendCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Response objectFreq(byte[] key) { + return appendCommand(commandObjects.objectFreq(key)); + } + + @Override + public Response migrate(String host, int port, byte[] key, int timeout) { + return appendCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public Response migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { + return appendCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public Response> keys(byte[] pattern) { + return appendCommand(commandObjects.keys(pattern)); + } + + @Override + public Response> scan(byte[] cursor) { + return appendCommand(commandObjects.scan(cursor)); + } + + @Override + public Response> scan(byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.scan(cursor, params)); + } + + @Override + public Response> scan(byte[] cursor, ScanParams params, byte[] type) { + return appendCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Response randomBinaryKey() { + return appendCommand(commandObjects.randomBinaryKey()); + } + + @Override + public Response rpush(byte[] key, byte[]... args) { + return appendCommand(commandObjects.rpush(key, args)); + } + + @Override + public Response lpush(byte[] key, byte[]... args) { + return appendCommand(commandObjects.lpush(key, args)); + } + + @Override + public Response llen(byte[] key) { + return appendCommand(commandObjects.llen(key)); + } + + @Override + public Response> lrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public Response ltrim(byte[] key, long start, long stop) { + return appendCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public Response lindex(byte[] key, long index) { + return appendCommand(commandObjects.lindex(key, index)); + } + + @Override + public Response lset(byte[] key, long index, byte[] value) { + return appendCommand(commandObjects.lset(key, index, value)); + } + + @Override + public Response lrem(byte[] key, long count, byte[] value) { + return appendCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public Response lpop(byte[] key) { + return appendCommand(commandObjects.lpop(key)); + } + + @Override + public Response> lpop(byte[] key, int count) { + return appendCommand(commandObjects.lpop(key, count)); + } + + @Override + public Response lpos(byte[] key, byte[] element) { + return appendCommand(commandObjects.lpos(key, element)); + } + + @Override + public Response lpos(byte[] key, byte[] element, LPosParams params) { + return appendCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public Response> lpos(byte[] key, byte[] element, LPosParams params, long count) { + return appendCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Response rpop(byte[] key) { + return appendCommand(commandObjects.rpop(key)); + } + + @Override + public Response> rpop(byte[] key, int count) { + return appendCommand(commandObjects.rpop(key, count)); + } + + @Override + public Response linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value) { + return appendCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public Response lpushx(byte[] key, byte[]... arg) { + return appendCommand(commandObjects.lpushx(key, arg)); + } + + @Override + public Response rpushx(byte[] key, byte[]... arg) { + return appendCommand(commandObjects.rpushx(key, arg)); + } + + @Override + public Response> blpop(int timeout, byte[]... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> blpop(double timeout, byte[]... keys) { + return appendCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public Response> brpop(int timeout, byte[]... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response> brpop(double timeout, byte[]... keys) { + return appendCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public Response rpoplpush(byte[] srckey, byte[] dstkey) { + return appendCommand(commandObjects.rpoplpush(srckey, dstkey)); + } + + @Override + public Response brpoplpush(byte[] source, byte[] destination, int timeout) { + return appendCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public Response lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { + return appendCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public Response blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { + return appendCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + public Response publish(byte[] channel, byte[] message) { + return appendCommand(commandObjects.publish(channel, message)); + } + + public Response strAlgoLCSStrings(byte[] strA, byte[] strB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + @Override + public Response waitReplicas(byte[] sampleKey, int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Response eval(byte[] script, byte[] sampleKey) { + return appendCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Response evalsha(byte[] sha1, byte[] sampleKey) { + return appendCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Response> scriptExists(byte[] sampleKey, byte[]... sha1s) { + return appendCommand(commandObjects.scriptExists(sampleKey, sha1s)); + } + + @Override + public Response scriptLoad(byte[] script, byte[] sampleKey) { + return appendCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public Response scriptFlush(byte[] sampleKey) { + return appendCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public Response scriptFlush(byte[] sampleKey, FlushMode flushMode) { + return appendCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public Response scriptKill(byte[] sampleKey) { + return appendCommand(commandObjects.scriptKill(sampleKey)); + } + + @Override + public Response eval(byte[] script) { + return appendCommand(commandObjects.eval(script)); + } + + @Override + public Response eval(byte[] script, int keyCount, byte[]... params) { + return appendCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Response eval(byte[] script, List keys, List args) { + return appendCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Response evalsha(byte[] sha1) { + return appendCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Response evalsha(byte[] sha1, int keyCount, byte[]... params) { + return appendCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Response evalsha(byte[] sha1, List keys, List args) { + return appendCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Response sadd(byte[] key, byte[]... member) { + return appendCommand(commandObjects.sadd(key, member)); + } + + @Override + public Response> smembers(byte[] key) { + return appendCommand(commandObjects.smembers(key)); + } + + @Override + public Response srem(byte[] key, byte[]... member) { + return appendCommand(commandObjects.srem(key, member)); + } + + @Override + public Response spop(byte[] key) { + return appendCommand(commandObjects.spop(key)); + } + + @Override + public Response> spop(byte[] key, long count) { + return appendCommand(commandObjects.spop(key, count)); + } + + @Override + public Response scard(byte[] key) { + return appendCommand(commandObjects.scard(key)); + } + + @Override + public Response sismember(byte[] key, byte[] member) { + return appendCommand(commandObjects.sismember(key, member)); + } + + @Override + public Response> smismember(byte[] key, byte[]... members) { + return appendCommand(commandObjects.smismember(key, members)); + } + + @Override + public Response srandmember(byte[] key) { + return appendCommand(commandObjects.srandmember(key)); + } + + @Override + public Response> srandmember(byte[] key, int count) { + return appendCommand(commandObjects.srandmember(key, count)); + } + + @Override + public Response> sscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Response> sdiff(byte[]... keys) { + return appendCommand(commandObjects.sdiff(keys)); + } + + @Override + public Response sdiffstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sdiffstore(dstkey, keys)); + } + + @Override + public Response> sinter(byte[]... keys) { + return appendCommand(commandObjects.sinter(keys)); + } + + @Override + public Response sinterstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sinterstore(dstkey, keys)); + } + + @Override + public Response> sunion(byte[]... keys) { + return appendCommand(commandObjects.sunion(keys)); + } + + @Override + public Response sunionstore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.sunionstore(dstkey, keys)); + } + + @Override + public Response smove(byte[] srckey, byte[] dstkey, byte[] member) { + return appendCommand(commandObjects.smove(srckey, dstkey, member)); + } + + @Override + public Response zadd(byte[] key, double score, byte[] member) { + return appendCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public Response zadd(byte[] key, double score, byte[] member, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public Response zadd(byte[] key, Map scoreMembers) { + return appendCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public Response zadd(byte[] key, Map scoreMembers, ZAddParams params) { + return appendCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Response zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { + return appendCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public Response zrem(byte[] key, byte[]... members) { + return appendCommand(commandObjects.zrem(key, members)); + } + + @Override + public Response zincrby(byte[] key, double increment, byte[] member) { + return appendCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Response zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params) { + return appendCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Response zrank(byte[] key, byte[] member) { + return appendCommand(commandObjects.zrank(key, member)); + } + + @Override + public Response zrevrank(byte[] key, byte[] member) { + return appendCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public Response> zrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public Response> zrevrange(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public Response> zrangeWithScores(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public Response> zrevrangeWithScores(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public Response zrandmember(byte[] key) { + return appendCommand(commandObjects.zrandmember(key)); + } + + @Override + public Response> zrandmember(byte[] key, long count) { + return appendCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public Response> zrandmemberWithScores(byte[] key, long count) { + return appendCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public Response zcard(byte[] key) { + return appendCommand(commandObjects.zcard(key)); + } + + @Override + public Response zscore(byte[] key, byte[] member) { + return appendCommand(commandObjects.zscore(key, member)); + } + + @Override + public Response> zmscore(byte[] key, byte[]... members) { + return appendCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Response zpopmax(byte[] key) { + return appendCommand(commandObjects.zpopmax(key)); + } + + @Override + public Response> zpopmax(byte[] key, int count) { + return appendCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Response zpopmin(byte[] key) { + return appendCommand(commandObjects.zpopmin(key)); + } + + @Override + public Response> zpopmin(byte[] key, int count) { + return appendCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public Response zcount(byte[] key, double min, double max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response zcount(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, double min, double max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max)); + } + + @Override + public Response> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, double min, double max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScore(key, min, max, offset, count)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max)); + } + + @Override + public Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public Response zremrangeByRank(byte[] key, long start, long stop) { + return appendCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public Response zremrangeByScore(byte[] key, double min, double max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zremrangeByScore(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public Response zlexcount(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public Response> zrangeByLex(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public Response> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count) { + return appendCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min) { + return appendCommand(commandObjects.zrevrangeByLex(key, min, max)); + } + + @Override + public Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { + return appendCommand(commandObjects.zrevrangeByLex(key, min, max, offset, count)); + } + + @Override + public Response zremrangeByLex(byte[] key, byte[] min, byte[] max) { + return appendCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public Response> zscan(byte[] key, byte[] cursor, ScanParams params) { + return appendCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public Response> bzpopmax(double timeout, byte[]... keys) { + return appendCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public Response> bzpopmin(double timeout, byte[]... keys) { + return appendCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Response> zdiff(byte[]... keys) { + return appendCommand(commandObjects.zdiff(keys)); + } + + @Override + public Response> zdiffWithScores(byte[]... keys) { + return appendCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public Response zdiffStore(byte[] dstkey, byte[]... keys) { + return appendCommand(commandObjects.zdiffStore(dstkey, keys)); + } + + @Override + public Response> zinter(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Response> zinterWithScores(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Response zinterstore(byte[] dstkey, byte[]... sets) { + return appendCommand(commandObjects.zinterstore(dstkey, sets)); + } + + @Override + public Response zinterstore(byte[] dstkey, ZParams params, byte[]... sets) { + return appendCommand(commandObjects.zinterstore(dstkey, params, sets)); + } + + @Override + public Response> zunion(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Response> zunionWithScores(ZParams params, byte[]... keys) { + return appendCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public Response zunionstore(byte[] dstkey, byte[]... sets) { + return appendCommand(commandObjects.zunionstore(dstkey, sets)); + } + + @Override + public Response zunionstore(byte[] dstkey, ZParams params, byte[]... sets) { + return appendCommand(commandObjects.zunionstore(dstkey, params, sets)); + } + + @Override + public Response xadd(byte[] key, XAddParams params, Map hash) { + return appendCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public Response xlen(byte[] key) { + return appendCommand(commandObjects.xlen(key)); + } + + @Override + public Response> xrange(byte[] key, byte[] start, byte[] end) { + return appendCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public Response> xrange(byte[] key, byte[] start, byte[] end, int count) { + return appendCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public Response> xrevrange(byte[] key, byte[] end, byte[] start) { + return appendCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public Response> xrevrange(byte[] key, byte[] end, byte[] start, int count) { + return appendCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public Response xack(byte[] key, byte[] group, byte[]... ids) { + return appendCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public Response xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream) { + return appendCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public Response xgroupSetID(byte[] key, byte[] groupname, byte[] id) { + return appendCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public Response xgroupDestroy(byte[] key, byte[] groupname) { + return appendCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public Response xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName) { + return appendCommand(commandObjects.xgroupDelConsumer(key, groupname, consumerName)); + } + + @Override + public Response xdel(byte[] key, byte[]... ids) { + return appendCommand(commandObjects.xdel(key, ids)); + } + + @Override + public Response xtrim(byte[] key, long maxLen, boolean approximateLength) { + return appendCommand(commandObjects.xtrim(key, maxLen, approximateLength)); + } + + @Override + public Response xtrim(byte[] key, XTrimParams params) { + return appendCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Response xpending(byte[] key, byte[] groupname) { + return appendCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public Response> xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername) { + return appendCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public Response> xpending(byte[] key, byte[] groupname, XPendingParams params) { + return appendCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public Response> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return appendCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return appendCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Response> xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaim(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Response> xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return appendCommand(commandObjects.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Response xinfoStream(byte[] key) { + return appendCommand(commandObjects.xinfoStream(key)); + } + + @Override + public Response> xinfoGroup(byte[] key) { + return appendCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public Response> xinfoConsumers(byte[] key, byte[] group) { + return appendCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public Response> xread(XReadParams xReadParams, Map.Entry... streams) { + return appendCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public Response> xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, Map.Entry... streams) { + return appendCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public Response set(byte[] key, byte[] value) { + return appendCommand(commandObjects.set(key, value)); + } + + @Override + public Response set(byte[] key, byte[] value, SetParams params) { + return appendCommand(commandObjects.set(key, value, params)); + } + + @Override + public Response get(byte[] key) { + return appendCommand(commandObjects.get(key)); + } + + @Override + public Response getDel(byte[] key) { + return appendCommand(commandObjects.getDel(key)); + } + + @Override + public Response getEx(byte[] key, GetExParams params) { + return appendCommand(commandObjects.getEx(key, params)); + } + + @Override + public Response setbit(byte[] key, long offset, boolean value) { + return appendCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public Response getbit(byte[] key, long offset) { + return appendCommand(commandObjects.getbit(key, offset)); + } + + @Override + public Response setrange(byte[] key, long offset, byte[] value) { + return appendCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public Response getrange(byte[] key, long startOffset, long endOffset) { + return appendCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public Response getSet(byte[] key, byte[] value) { + return appendCommand(commandObjects.getSet(key, value)); + } + + @Override + public Response setnx(byte[] key, byte[] value) { + return appendCommand(commandObjects.setnx(key, value)); + } + + @Override + public Response setex(byte[] key, long seconds, byte[] value) { + return appendCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public Response psetex(byte[] key, long milliseconds, byte[] value) { + return appendCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public Response> mget(byte[]... keys) { + return appendCommand(commandObjects.mget(keys)); + } + + @Override + public Response mset(byte[]... keysvalues) { + return appendCommand(commandObjects.mset(keysvalues)); + } + + @Override + public Response msetnx(byte[]... keysvalues) { + return appendCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public Response incr(byte[] key) { + return appendCommand(commandObjects.incr(key)); + } + + @Override + public Response incrBy(byte[] key, long increment) { + return appendCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public Response incrByFloat(byte[] key, double increment) { + return appendCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public Response decr(byte[] key) { + return appendCommand(commandObjects.decr(key)); + } + + @Override + public Response decrBy(byte[] key, long decrement) { + return appendCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public Response append(byte[] key, byte[] value) { + return appendCommand(commandObjects.append(key, value)); + } + + @Override + public Response substr(byte[] key, int start, int end) { + return appendCommand(commandObjects.substr(key, start, end)); + } + + @Override + public Response strlen(byte[] key) { + return appendCommand(commandObjects.strlen(key)); + } + + @Override + public Response bitcount(byte[] key) { + return appendCommand(commandObjects.bitcount(key)); + } + + @Override + public Response bitcount(byte[] key, long start, long end) { + return appendCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public Response bitpos(byte[] key, boolean value) { + return appendCommand(commandObjects.bitpos(key, value)); + } + + @Override + public Response bitpos(byte[] key, boolean value, BitPosParams params) { + return appendCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public Response> bitfield(byte[] key, byte[]... arguments) { + return appendCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public Response> bitfieldReadonly(byte[] key, byte[]... arguments) { + return appendCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { + return appendCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public Response strAlgoLCSKeys(byte[] keyA, byte[] keyB, StrAlgoLCSParams params) { + return appendCommand(commandObjects.strAlgoLCSStrings(keyA, keyB, params)); + } + + @Override + public Response jsonSet(String key, Path2 path, Object object) { + return appendCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public Response jsonSetWithEscape(String key, Path2 path, Object object) { + return appendCommand(commandObjects.jsonSetWithEscape(key, path, object)); + } + + @Override + public Response jsonSet(String key, Path path, Object object) { + return appendCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public Response jsonSet(String key, Path2 path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSet(key, path, object, params)); + } + + @Override + public Response jsonSetWithEscape(String key, Path2 path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSetWithEscape(key, path, object, params)); + } + + @Override + public Response jsonSet(String key, Path path, Object object, JsonSetParams params) { + return appendCommand(commandObjects.jsonSet(key, path, object, params)); + } + + @Override + public Response jsonGet(String key) { + return appendCommand(commandObjects.jsonGet(key)); + } + + @Override + public Response jsonGet(String key, Class clazz) { + return appendCommand(commandObjects.jsonGet(key, clazz)); + } + + @Override + public Response jsonGet(String key, Path2... paths) { + return appendCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Response jsonGet(String key, Path... paths) { + return appendCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Response jsonGet(String key, Class clazz, Path... paths) { + return appendCommand(commandObjects.jsonGet(key, clazz, paths)); + } + + @Override + public Response> jsonMGet(Path2 path, String... keys) { + return appendCommand(commandObjects.jsonMGet(path, keys)); + } + + @Override + public Response> jsonMGet(Path path, Class clazz, String... keys) { + return appendCommand(commandObjects.jsonMGet(path, clazz, keys)); + } + + @Override + public Response jsonDel(String key) { + return appendCommand(commandObjects.jsonDel(key)); + } + + @Override + public Response jsonDel(String key, Path2 path) { + return appendCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public Response jsonDel(String key, Path path) { + return appendCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public Response jsonClear(String key) { + return appendCommand(commandObjects.jsonClear(key)); + } + + @Override + public Response jsonClear(String key, Path2 path) { + return appendCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public Response jsonClear(String key, Path path) { + return appendCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public Response> jsonToggle(String key, Path2 path) { + return appendCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Response jsonToggle(String key, Path path) { + return appendCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Response> jsonType(String key) { + return appendCommand(commandObjects.jsonType(key)); + } + + @Override + public Response>> jsonType(String key, Path2 path) { + return appendCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Response> jsonType(String key, Path path) { + return appendCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Response jsonStrAppend(String key, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, string)); + } + + @Override + public Response> jsonStrAppend(String key, Path2 path, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Response jsonStrAppend(String key, Path path, Object string) { + return appendCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Response jsonStrLen(String key) { + return appendCommand(commandObjects.jsonStrLen(key)); + } + + @Override + public Response> jsonStrLen(String key, Path2 path) { + return appendCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Response jsonStrLen(String key, Path path) { + return appendCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Response> jsonArrAppend(String key, Path2 path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public Response> jsonArrAppendWithEscape(String key, Path2 path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppendWithEscape(key, path, objects)); + } + + @Override + public Response jsonArrAppend(String key, Path path, Object... objects) { + return appendCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public Response> jsonArrIndex(String key, Path2 path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public Response> jsonArrIndexWithEscape(String key, Path2 path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndexWithEscape(key, path, scalar)); + } + + @Override + public Response jsonArrIndex(String key, Path path, Object scalar) { + return appendCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public Response> jsonArrInsert(String key, Path2 path, int index, Object... objects) { + return appendCommand(commandObjects.jsonArrInsert(key, path, index, objects)); + } + + @Override + public Response> jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects) { + return appendCommand(commandObjects.jsonArrInsertWithEscape(key, path, index, objects)); + } + + @Override + public Response jsonArrInsert(String key, Path path, int index, Object... pojos) { + return appendCommand(commandObjects.jsonArrInsert(key, path, index, pojos)); + } + + @Override + public Response jsonArrPop(String key) { + return appendCommand(commandObjects.jsonArrPop(key)); + } + + @Override + public Response jsonArrLen(String key, Path path) { + return appendCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Response> jsonArrTrim(String key, Path2 path, int start, int stop) { + return appendCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Response jsonArrTrim(String key, Path path, int start, int stop) { + return appendCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Response jsonArrPop(String key, Class clazz, Path path) { + return appendCommand(commandObjects.jsonArrPop(key, clazz, path)); + } + + @Override + public Response> jsonArrPop(String key, Path2 path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Response jsonArrPop(String key, Path path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Response jsonArrPop(String key, Class clazz, Path path, int index) { + return appendCommand(commandObjects.jsonArrPop(key, clazz, path, index)); + } + + @Override + public Response jsonArrLen(String key) { + return appendCommand(commandObjects.jsonArrLen(key)); + } + + @Override + public Response> jsonArrLen(String key, Path2 path) { + return appendCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Response jsonArrPop(String key, Class clazz) { + return appendCommand(commandObjects.jsonArrPop(key, clazz)); + } + + @Override + public Response> jsonArrPop(String key, Path2 path) { + return appendCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Response jsonArrPop(String key, Path path) { + return appendCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Response ftCreate(String indexName, IndexOptions indexOptions, Schema schema) { + return appendCommand(commandObjects.ftCreate(indexName, indexOptions, schema)); + } + + @Override + public Response ftSearch(String indexName, Query query) { + return appendCommand(commandObjects.ftSearch(indexName, query)); + } + + @Override + public Response ftSearch(byte[] indexName, Query query) { + return appendCommand(commandObjects.ftSearch(indexName, query)); + } + + public Response waitReplicas(int replicas, long timeout) { + return appendCommand(commandObjects.waitReplicas(replicas, timeout)); + } + + public Response sendCommand(ProtocolCommand cmd, String... args) { + return sendCommand(new CommandArguments(cmd).addObjects((Object[]) args)); + } + + public Response sendCommand(ProtocolCommand cmd, byte[]... args) { + return sendCommand(new CommandArguments(cmd).addObjects((Object[]) args)); + } + + public Response sendCommand(CommandArguments args) { + return executeCommand(new CommandObject<>(args, BuilderFactory.RAW_OBJECT)); + } + + public Response executeCommand(CommandObject command) { + return appendCommand(command); + } +} diff --git a/src/main/java/redis/clients/jedis/UnifiedJedis.java b/src/main/java/redis/clients/jedis/UnifiedJedis.java new file mode 100644 index 0000000000..f4e9d8a754 --- /dev/null +++ b/src/main/java/redis/clients/jedis/UnifiedJedis.java @@ -0,0 +1,3235 @@ +package redis.clients.jedis; + +import java.net.URI; +import java.time.Duration; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.Pattern; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.json.JSONArray; + +import redis.clients.jedis.args.*; +import redis.clients.jedis.commands.JedisCommands; +import redis.clients.jedis.commands.JedisBinaryCommands; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.commands.SampleBinaryKeyedCommands; +import redis.clients.jedis.commands.SampleKeyedCommands; +import redis.clients.jedis.commands.RedisModuleCommands; +import redis.clients.jedis.executors.*; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.params.*; +import redis.clients.jedis.providers.ClusterConnectionProvider; +import redis.clients.jedis.providers.ConnectionProvider; +import redis.clients.jedis.providers.PooledConnectionProvider; +import redis.clients.jedis.providers.ShardedConnectionProvider; +import redis.clients.jedis.resps.*; +import redis.clients.jedis.search.IndexOptions; +import redis.clients.jedis.search.Query; +import redis.clients.jedis.search.Schema; +import redis.clients.jedis.search.SearchResult; +import redis.clients.jedis.search.aggr.AggregationBuilder; +import redis.clients.jedis.search.aggr.AggregationResult; +import redis.clients.jedis.util.IOUtils; +import redis.clients.jedis.util.JedisURIHelper; + +public class UnifiedJedis implements JedisCommands, JedisBinaryCommands, + SampleKeyedCommands, SampleBinaryKeyedCommands, RedisModuleCommands, + AutoCloseable { + + protected final ConnectionProvider provider; + protected final CommandExecutor executor; + private final CommandObjects commandObjects; + + public UnifiedJedis() { + this(new HostAndPort(Protocol.DEFAULT_HOST, Protocol.DEFAULT_PORT)); + } + + public UnifiedJedis(HostAndPort hostAndPort) { +// this(new Connection(hostAndPort)); + this(new PooledConnectionProvider(hostAndPort)); + } + + public UnifiedJedis(final String url) { + this(URI.create(url)); + } + + public UnifiedJedis(final URI uri) { + this(JedisURIHelper.getHostAndPort(uri), DefaultJedisClientConfig.builder() + .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) + .database(JedisURIHelper.getDBIndex(uri)).ssl(JedisURIHelper.isRedisSSLScheme(uri)).build()); + } + + public UnifiedJedis(final URI uri, JedisClientConfig config) { + this(JedisURIHelper.getHostAndPort(uri), DefaultJedisClientConfig.builder() + .connectionTimeoutMillis(config.getConnectionTimeoutMillis()) + .socketTimeoutMillis(config.getSocketTimeoutMillis()) + .blockingSocketTimeoutMillis(config.getBlockingSocketTimeoutMillis()) + .user(JedisURIHelper.getUser(uri)).password(JedisURIHelper.getPassword(uri)) + .database(JedisURIHelper.getDBIndex(uri)).clientName(config.getClientName()) + .ssl(JedisURIHelper.isRedisSSLScheme(uri)).sslSocketFactory(config.getSslSocketFactory()) + .sslParameters(config.getSslParameters()).hostnameVerifier(config.getHostnameVerifier()) + .build()); + } + + public UnifiedJedis(HostAndPort hostAndPort, JedisClientConfig clientConfig) { +// this(new Connection(hostAndPort, clientConfig)); + this(new PooledConnectionProvider(hostAndPort, clientConfig)); + } + + public UnifiedJedis(ConnectionProvider provider) { + this.provider = provider; + this.executor = new DefaultCommandExecutor(provider); + this.commandObjects = new CommandObjects(); + } + + public UnifiedJedis(JedisSocketFactory socketFactory) { + this(new Connection(socketFactory)); + } + + public UnifiedJedis(Connection connection) { + this.provider = null; + this.executor = new SimpleCommandExecutor(connection); + this.commandObjects = new CommandObjects(); + } + + public UnifiedJedis(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts) { + this(new ClusterConnectionProvider(jedisClusterNodes, clientConfig), maxAttempts, + Duration.ofMillis(maxAttempts * clientConfig.getSocketTimeoutMillis())); + } + + public UnifiedJedis(Set jedisClusterNodes, JedisClientConfig clientConfig, int maxAttempts, Duration maxTotalRetriesDuration) { + this(new ClusterConnectionProvider(jedisClusterNodes, clientConfig), maxAttempts, maxTotalRetriesDuration); + } + + public UnifiedJedis(Set jedisClusterNodes, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig, int maxAttempts, Duration maxTotalRetriesDuration) { + this(new ClusterConnectionProvider(jedisClusterNodes, clientConfig, poolConfig), maxAttempts, maxTotalRetriesDuration); + } + + public UnifiedJedis(ClusterConnectionProvider provider, int maxAttempts, Duration maxTotalRetriesDuration) { + this.provider = provider; + this.executor = new ClusterCommandExecutor(provider, maxAttempts, maxTotalRetriesDuration); + this.commandObjects = new ClusterCommandObjects(); + } + + public UnifiedJedis(ShardedConnectionProvider provider) { + this.provider = provider; + this.executor = new DefaultCommandExecutor(provider); + this.commandObjects = new ShardedCommandObjects(provider.getHashingAlgo()); + } + + public UnifiedJedis(ShardedConnectionProvider provider, Pattern tagPattern) { + this.provider = provider; + this.executor = new DefaultCommandExecutor(provider); + this.commandObjects = new ShardedCommandObjects(provider.getHashingAlgo(), tagPattern); + } + + public UnifiedJedis(ConnectionProvider provider, int maxAttempts, Duration maxTotalRetriesDuration) { + this.provider = provider; + this.executor = new RetryableCommandExecutor(provider, maxAttempts, maxTotalRetriesDuration); + this.commandObjects = new CommandObjects(); + } + + @Override + public void close() { + IOUtils.closeQuietly(this.executor); + } + + public final T executeCommand(CommandObject commandObject) { + return executor.executeCommand(commandObject); + } + + // Key commands + @Override + public boolean exists(String key) { + return executeCommand(commandObjects.exists(key)); + } + + @Override + public long exists(String... keys) { + return executeCommand(commandObjects.exists(keys)); + } + + @Override + public long persist(String key) { + return executeCommand(commandObjects.persist(key)); + } + + @Override + public String type(String key) { + return executeCommand(commandObjects.type(key)); + } + + @Override + public boolean exists(byte[] key) { + return executeCommand(commandObjects.exists(key)); + } + + @Override + public long exists(byte[]... keys) { + return executeCommand(commandObjects.exists(keys)); + } + + @Override + public long persist(byte[] key) { + return executeCommand(commandObjects.persist(key)); + } + + @Override + public String type(byte[] key) { + return executeCommand(commandObjects.type(key)); + } + + @Override + public byte[] dump(String key) { + return executeCommand(commandObjects.dump(key)); + } + + @Override + public String restore(String key, long ttl, byte[] serializedValue) { + return executeCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public String restore(String key, long ttl, byte[] serializedValue, RestoreParams params) { + return executeCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public byte[] dump(byte[] key) { + return executeCommand(commandObjects.dump(key)); + } + + @Override + public String restore(byte[] key, long ttl, byte[] serializedValue) { + return executeCommand(commandObjects.restore(key, ttl, serializedValue)); + } + + @Override + public String restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params) { + return executeCommand(commandObjects.restore(key, ttl, serializedValue, params)); + } + + @Override + public long expire(String key, long seconds) { + return executeCommand(commandObjects.expire(key, seconds)); + } + + @Override + public long pexpire(String key, long milliseconds) { + return executeCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public long expireAt(String key, long unixTime) { + return executeCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public long pexpireAt(String key, long millisecondsTimestamp) { + return executeCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public long expire(byte[] key, long seconds) { + return executeCommand(commandObjects.expire(key, seconds)); + } + + @Override + public long pexpire(byte[] key, long milliseconds) { + return executeCommand(commandObjects.pexpire(key, milliseconds)); + } + + @Override + public long expireAt(byte[] key, long unixTime) { + return executeCommand(commandObjects.expireAt(key, unixTime)); + } + + @Override + public long pexpireAt(byte[] key, long millisecondsTimestamp) { + return executeCommand(commandObjects.pexpireAt(key, millisecondsTimestamp)); + } + + @Override + public long ttl(String key) { + return executeCommand(commandObjects.ttl(key)); + } + + @Override + public long pttl(String key) { + return executeCommand(commandObjects.pttl(key)); + } + + @Override + public long touch(String key) { + return executeCommand(commandObjects.touch(key)); + } + + @Override + public long touch(String... keys) { + return executeCommand(commandObjects.touch(keys)); + } + + @Override + public long ttl(byte[] key) { + return executeCommand(commandObjects.ttl(key)); + } + + @Override + public long pttl(byte[] key) { + return executeCommand(commandObjects.pttl(key)); + } + + @Override + public long touch(byte[] key) { + return executeCommand(commandObjects.touch(key)); + } + + @Override + public long touch(byte[]... keys) { + return executeCommand(commandObjects.touch(keys)); + } + + @Override + public List sort(String key) { + return executeCommand(commandObjects.sort(key)); + } + + @Override + public List sort(String key, SortingParams sortingParameters) { + return executeCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public long sort(String key, String dstkey) { + return executeCommand(commandObjects.sort(key, dstkey)); + } + + @Override + public long sort(String key, SortingParams sortingParameters, String dstkey) { + return executeCommand(commandObjects.sort(key, sortingParameters, dstkey)); + } + + @Override + public List sort(byte[] key) { + return executeCommand(commandObjects.sort(key)); + } + + @Override + public List sort(byte[] key, SortingParams sortingParameters) { + return executeCommand(commandObjects.sort(key, sortingParameters)); + } + + @Override + public long sort(byte[] key, byte[] dstkey) { + return executeCommand(commandObjects.sort(key, dstkey)); + } + + @Override + public long sort(byte[] key, SortingParams sortingParameters, byte[] dstkey) { + return executeCommand(commandObjects.sort(key, sortingParameters, dstkey)); + } + + @Override + public long del(String key) { + return executeCommand(commandObjects.del(key)); + } + + @Override + public long del(String... keys) { + return executeCommand(commandObjects.del(keys)); + } + + @Override + public long unlink(String key) { + return executeCommand(commandObjects.unlink(key)); + } + + @Override + public long unlink(String... keys) { + return executeCommand(commandObjects.unlink(keys)); + } + + @Override + public long del(byte[] key) { + return executeCommand(commandObjects.del(key)); + } + + @Override + public long del(byte[]... keys) { + return executeCommand(commandObjects.del(keys)); + } + + @Override + public long unlink(byte[] key) { + return executeCommand(commandObjects.unlink(key)); + } + + @Override + public long unlink(byte[]... keys) { + return executeCommand(commandObjects.unlink(keys)); + } + + @Override + public Long memoryUsage(String key) { + return executeCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Long memoryUsage(String key, int samples) { + return executeCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public Long memoryUsage(byte[] key) { + return executeCommand(commandObjects.memoryUsage(key)); + } + + @Override + public Long memoryUsage(byte[] key, int samples) { + return executeCommand(commandObjects.memoryUsage(key, samples)); + } + + @Override + public boolean copy(String srcKey, String dstKey, boolean replace) { + return executeCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public String rename(String oldkey, String newkey) { + return executeCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public long renamenx(String oldkey, String newkey) { + return executeCommand(commandObjects.renamenx(oldkey, newkey)); + } + + @Override + public boolean copy(byte[] srcKey, byte[] dstKey, boolean replace) { + return executeCommand(commandObjects.copy(srcKey, dstKey, replace)); + } + + @Override + public String rename(byte[] oldkey, byte[] newkey) { + return executeCommand(commandObjects.rename(oldkey, newkey)); + } + + @Override + public long renamenx(byte[] oldkey, byte[] newkey) { + return executeCommand(commandObjects.renamenx(oldkey, newkey)); + } + + public long dbSize() { + return executeCommand(commandObjects.dbSize()); + } + + @Override + public Set keys(String pattern) { + return executeCommand(commandObjects.keys(pattern)); + } + + @Override + public ScanResult scan(String cursor) { + return executeCommand(commandObjects.scan(cursor)); + } + + @Override + public ScanResult scan(String cursor, ScanParams params) { + return executeCommand(commandObjects.scan(cursor, params)); + } + + @Override + public ScanResult scan(String cursor, ScanParams params, String type) { + return executeCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public Set keys(byte[] pattern) { + return executeCommand(commandObjects.keys(pattern)); + } + + @Override + public ScanResult scan(byte[] cursor) { + return executeCommand(commandObjects.scan(cursor)); + } + + @Override + public ScanResult scan(byte[] cursor, ScanParams params) { + return executeCommand(commandObjects.scan(cursor, params)); + } + + @Override + public ScanResult scan(byte[] cursor, ScanParams params, byte[] type) { + return executeCommand(commandObjects.scan(cursor, params, type)); + } + + @Override + public String randomKey() { + return executeCommand(commandObjects.randomKey()); + } + + @Override + public byte[] randomBinaryKey() { + return executeCommand(commandObjects.randomBinaryKey()); + } + // Key commands + + // String commands + @Override + public String set(String key, String value) { + return executeCommand(commandObjects.set(key, value)); + } + + @Override + public String set(String key, String value, SetParams params) { + return executeCommand(commandObjects.set(key, value, params)); + } + + @Override + public String get(String key) { + return executeCommand(commandObjects.get(key)); + } + + @Override + public String getDel(String key) { + return executeCommand(commandObjects.getDel(key)); + } + + @Override + public String getEx(String key, GetExParams params) { + return executeCommand(commandObjects.getEx(key, params)); + } + + @Override + public String set(byte[] key, byte[] value) { + return executeCommand(commandObjects.set(key, value)); + } + + @Override + public String set(byte[] key, byte[] value, SetParams params) { + return executeCommand(commandObjects.set(key, value, params)); + } + + @Override + public byte[] get(byte[] key) { + return executeCommand(commandObjects.get(key)); + } + + @Override + public byte[] getDel(byte[] key) { + return executeCommand(commandObjects.getDel(key)); + } + + @Override + public byte[] getEx(byte[] key, GetExParams params) { + return executeCommand(commandObjects.getEx(key, params)); + } + + @Override + public boolean setbit(String key, long offset, boolean value) { + return executeCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public boolean getbit(String key, long offset) { + return executeCommand(commandObjects.getbit(key, offset)); + } + + @Override + public long setrange(String key, long offset, String value) { + return executeCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public String getrange(String key, long startOffset, long endOffset) { + return executeCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public boolean setbit(byte[] key, long offset, boolean value) { + return executeCommand(commandObjects.setbit(key, offset, value)); + } + + @Override + public boolean getbit(byte[] key, long offset) { + return executeCommand(commandObjects.getbit(key, offset)); + } + + @Override + public long setrange(byte[] key, long offset, byte[] value) { + return executeCommand(commandObjects.setrange(key, offset, value)); + } + + @Override + public byte[] getrange(byte[] key, long startOffset, long endOffset) { + return executeCommand(commandObjects.getrange(key, startOffset, endOffset)); + } + + @Override + public String getSet(String key, String value) { + return executeCommand(commandObjects.getSet(key, value)); + } + + @Override + public long setnx(String key, String value) { + return executeCommand(commandObjects.setnx(key, value)); + } + + @Override + public String setex(String key, long seconds, String value) { + return executeCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public String psetex(String key, long milliseconds, String value) { + return executeCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public byte[] getSet(byte[] key, byte[] value) { + return executeCommand(commandObjects.getSet(key, value)); + } + + @Override + public long setnx(byte[] key, byte[] value) { + return executeCommand(commandObjects.setnx(key, value)); + } + + @Override + public String setex(byte[] key, long seconds, byte[] value) { + return executeCommand(commandObjects.setex(key, seconds, value)); + } + + @Override + public String psetex(byte[] key, long milliseconds, byte[] value) { + return executeCommand(commandObjects.psetex(key, milliseconds, value)); + } + + @Override + public long incr(String key) { + return executeCommand(commandObjects.incr(key)); + } + + @Override + public long incrBy(String key, long increment) { + return executeCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public double incrByFloat(String key, double increment) { + return executeCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public long decr(String key) { + return executeCommand(commandObjects.decr(key)); + } + + @Override + public long decrBy(String key, long decrement) { + return executeCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public long incr(byte[] key) { + return executeCommand(commandObjects.incr(key)); + } + + @Override + public long incrBy(byte[] key, long increment) { + return executeCommand(commandObjects.incrBy(key, increment)); + } + + @Override + public double incrByFloat(byte[] key, double increment) { + return executeCommand(commandObjects.incrByFloat(key, increment)); + } + + @Override + public long decr(byte[] key) { + return executeCommand(commandObjects.decr(key)); + } + + @Override + public long decrBy(byte[] key, long decrement) { + return executeCommand(commandObjects.decrBy(key, decrement)); + } + + @Override + public List mget(String... keys) { + return executeCommand(commandObjects.mget(keys)); + } + + @Override + public String mset(String... keysvalues) { + return executeCommand(commandObjects.mset(keysvalues)); + } + + @Override + public long msetnx(String... keysvalues) { + return executeCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public List mget(byte[]... keys) { + return executeCommand(commandObjects.mget(keys)); + } + + @Override + public String mset(byte[]... keysvalues) { + return executeCommand(commandObjects.mset(keysvalues)); + } + + @Override + public long msetnx(byte[]... keysvalues) { + return executeCommand(commandObjects.msetnx(keysvalues)); + } + + @Override + public long append(String key, String value) { + return executeCommand(commandObjects.append(key, value)); + } + + @Override + public String substr(String key, int start, int end) { + return executeCommand(commandObjects.substr(key, start, end)); + } + + @Override + public long strlen(String key) { + return executeCommand(commandObjects.strlen(key)); + } + + @Override + public long append(byte[] key, byte[] value) { + return executeCommand(commandObjects.append(key, value)); + } + + @Override + public byte[] substr(byte[] key, int start, int end) { + return executeCommand(commandObjects.substr(key, start, end)); + } + + @Override + public long strlen(byte[] key) { + return executeCommand(commandObjects.strlen(key)); + } + + @Override + public long bitcount(String key) { + return executeCommand(commandObjects.bitcount(key)); + } + + @Override + public long bitcount(String key, long start, long end) { + return executeCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public long bitpos(String key, boolean value) { + return executeCommand(commandObjects.bitpos(key, value)); + } + + @Override + public long bitpos(String key, boolean value, BitPosParams params) { + return executeCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public long bitcount(byte[] key) { + return executeCommand(commandObjects.bitcount(key)); + } + + @Override + public long bitcount(byte[] key, long start, long end) { + return executeCommand(commandObjects.bitcount(key, start, end)); + } + + @Override + public long bitpos(byte[] key, boolean value) { + return executeCommand(commandObjects.bitpos(key, value)); + } + + @Override + public long bitpos(byte[] key, boolean value, BitPosParams params) { + return executeCommand(commandObjects.bitpos(key, value, params)); + } + + @Override + public List bitfield(String key, String... arguments) { + return executeCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public List bitfieldReadonly(String key, String... arguments) { + return executeCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public List bitfield(byte[] key, byte[]... arguments) { + return executeCommand(commandObjects.bitfield(key, arguments)); + } + + @Override + public List bitfieldReadonly(byte[] key, byte[]... arguments) { + return executeCommand(commandObjects.bitfieldReadonly(key, arguments)); + } + + @Override + public long bitop(BitOP op, String destKey, String... srcKeys) { + return executeCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public long bitop(BitOP op, byte[] destKey, byte[]... srcKeys) { + return executeCommand(commandObjects.bitop(op, destKey, srcKeys)); + } + + @Override + public LCSMatchResult strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params) { + return executeCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); + } + + @Override + public LCSMatchResult strAlgoLCSKeys(byte[] keyA, byte[] keyB, StrAlgoLCSParams params) { + return executeCommand(commandObjects.strAlgoLCSKeys(keyA, keyB, params)); + } + // String commands + + // List commands + @Override + public long rpush(String key, String... string) { + return executeCommand(commandObjects.rpush(key, string)); + } + + @Override + public long lpush(String key, String... string) { + return executeCommand(commandObjects.lpush(key, string)); + } + + @Override + public long llen(String key) { + return executeCommand(commandObjects.llen(key)); + } + + @Override + public List lrange(String key, long start, long stop) { + return executeCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public String ltrim(String key, long start, long stop) { + return executeCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public String lindex(String key, long index) { + return executeCommand(commandObjects.lindex(key, index)); + } + + @Override + public long rpush(byte[] key, byte[]... args) { + return executeCommand(commandObjects.rpush(key, args)); + } + + @Override + public long lpush(byte[] key, byte[]... args) { + return executeCommand(commandObjects.lpush(key, args)); + } + + @Override + public long llen(byte[] key) { + return executeCommand(commandObjects.llen(key)); + } + + @Override + public List lrange(byte[] key, long start, long stop) { + return executeCommand(commandObjects.lrange(key, start, stop)); + } + + @Override + public String ltrim(byte[] key, long start, long stop) { + return executeCommand(commandObjects.ltrim(key, start, stop)); + } + + @Override + public byte[] lindex(byte[] key, long index) { + return executeCommand(commandObjects.lindex(key, index)); + } + + @Override + public String lset(String key, long index, String value) { + return executeCommand(commandObjects.lset(key, index, value)); + } + + @Override + public long lrem(String key, long count, String value) { + return executeCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public String lpop(String key) { + return executeCommand(commandObjects.lpop(key)); + } + + @Override + public List lpop(String key, int count) { + return executeCommand(commandObjects.lpop(key, count)); + } + + @Override + public String lset(byte[] key, long index, byte[] value) { + return executeCommand(commandObjects.lset(key, index, value)); + } + + @Override + public long lrem(byte[] key, long count, byte[] value) { + return executeCommand(commandObjects.lrem(key, count, value)); + } + + @Override + public byte[] lpop(byte[] key) { + return executeCommand(commandObjects.lpop(key)); + } + + @Override + public List lpop(byte[] key, int count) { + return executeCommand(commandObjects.lpop(key, count)); + } + + @Override + public Long lpos(String key, String element) { + return executeCommand(commandObjects.lpos(key, element)); + } + + @Override + public Long lpos(String key, String element, LPosParams params) { + return executeCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public List lpos(String key, String element, LPosParams params, long count) { + return executeCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public Long lpos(byte[] key, byte[] element) { + return executeCommand(commandObjects.lpos(key, element)); + } + + @Override + public Long lpos(byte[] key, byte[] element, LPosParams params) { + return executeCommand(commandObjects.lpos(key, element, params)); + } + + @Override + public List lpos(byte[] key, byte[] element, LPosParams params, long count) { + return executeCommand(commandObjects.lpos(key, element, params, count)); + } + + @Override + public String rpop(String key) { + return executeCommand(commandObjects.rpop(key)); + } + + @Override + public List rpop(String key, int count) { + return executeCommand(commandObjects.rpop(key, count)); + } + + @Override + public byte[] rpop(byte[] key) { + return executeCommand(commandObjects.rpop(key)); + } + + @Override + public List rpop(byte[] key, int count) { + return executeCommand(commandObjects.rpop(key, count)); + } + + @Override + public long linsert(String key, ListPosition where, String pivot, String value) { + return executeCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public long lpushx(String key, String... string) { + return executeCommand(commandObjects.lpushx(key, string)); + } + + @Override + public long rpushx(String key, String... string) { + return executeCommand(commandObjects.rpushx(key, string)); + } + + @Override + public long linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value) { + return executeCommand(commandObjects.linsert(key, where, pivot, value)); + } + + @Override + public long lpushx(byte[] key, byte[]... arg) { + return executeCommand(commandObjects.lpushx(key, arg)); + } + + @Override + public long rpushx(byte[] key, byte[]... arg) { + return executeCommand(commandObjects.rpushx(key, arg)); + } + + @Override + public List blpop(int timeout, String key) { + return executeCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public KeyedListElement blpop(double timeout, String key) { + return executeCommand(commandObjects.blpop(timeout, key)); + } + + @Override + public List brpop(int timeout, String key) { + return executeCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public KeyedListElement brpop(double timeout, String key) { + return executeCommand(commandObjects.brpop(timeout, key)); + } + + @Override + public List blpop(int timeout, String... keys) { + return executeCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public KeyedListElement blpop(double timeout, String... keys) { + return executeCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public List brpop(int timeout, String... keys) { + return executeCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public KeyedListElement brpop(double timeout, String... keys) { + return executeCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public List blpop(int timeout, byte[]... keys) { + return executeCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public List blpop(double timeout, byte[]... keys) { + return executeCommand(commandObjects.blpop(timeout, keys)); + } + + @Override + public List brpop(int timeout, byte[]... keys) { + return executeCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public List brpop(double timeout, byte[]... keys) { + return executeCommand(commandObjects.brpop(timeout, keys)); + } + + @Override + public String rpoplpush(String srckey, String dstkey) { + return executeCommand(commandObjects.rpoplpush(srckey, dstkey)); + } + + @Override + public String brpoplpush(String source, String destination, int timeout) { + return executeCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public byte[] rpoplpush(byte[] srckey, byte[] dstkey) { + return executeCommand(commandObjects.rpoplpush(srckey, dstkey)); + } + + @Override + public byte[] brpoplpush(byte[] source, byte[] destination, int timeout) { + return executeCommand(commandObjects.brpoplpush(source, destination, timeout)); + } + + @Override + public String lmove(String srcKey, String dstKey, ListDirection from, ListDirection to) { + return executeCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public String blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout) { + return executeCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + + @Override + public byte[] lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to) { + return executeCommand(commandObjects.lmove(srcKey, dstKey, from, to)); + } + + @Override + public byte[] blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout) { + return executeCommand(commandObjects.blmove(srcKey, dstKey, from, to, timeout)); + } + // List commands + + // Hash commands + @Override + public long hset(String key, String field, String value) { + return executeCommand(commandObjects.hset(key, field, value)); + } + + @Override + public long hset(String key, Map hash) { + return executeCommand(commandObjects.hset(key, hash)); + } + + @Override + public String hget(String key, String field) { + return executeCommand(commandObjects.hget(key, field)); + } + + @Override + public long hsetnx(String key, String field, String value) { + return executeCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public String hmset(String key, Map hash) { + return executeCommand(commandObjects.hmset(key, hash)); + } + + @Override + public List hmget(String key, String... fields) { + return executeCommand(commandObjects.hmget(key, fields)); + } + + @Override + public long hset(byte[] key, byte[] field, byte[] value) { + return executeCommand(commandObjects.hset(key, field, value)); + } + + @Override + public long hset(byte[] key, Map hash) { + return executeCommand(commandObjects.hset(key, hash)); + } + + @Override + public byte[] hget(byte[] key, byte[] field) { + return executeCommand(commandObjects.hget(key, field)); + } + + @Override + public long hsetnx(byte[] key, byte[] field, byte[] value) { + return executeCommand(commandObjects.hsetnx(key, field, value)); + } + + @Override + public String hmset(byte[] key, Map hash) { + return executeCommand(commandObjects.hmset(key, hash)); + } + + @Override + public List hmget(byte[] key, byte[]... fields) { + return executeCommand(commandObjects.hmget(key, fields)); + } + + @Override + public long hincrBy(String key, String field, long value) { + return executeCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public double hincrByFloat(String key, String field, double value) { + return executeCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public boolean hexists(String key, String field) { + return executeCommand(commandObjects.hexists(key, field)); + } + + @Override + public long hdel(String key, String... field) { + return executeCommand(commandObjects.hdel(key, field)); + } + + @Override + public long hlen(String key) { + return executeCommand(commandObjects.hlen(key)); + } + + @Override + public long hincrBy(byte[] key, byte[] field, long value) { + return executeCommand(commandObjects.hincrBy(key, field, value)); + } + + @Override + public double hincrByFloat(byte[] key, byte[] field, double value) { + return executeCommand(commandObjects.hincrByFloat(key, field, value)); + } + + @Override + public boolean hexists(byte[] key, byte[] field) { + return executeCommand(commandObjects.hexists(key, field)); + } + + @Override + public long hdel(byte[] key, byte[]... field) { + return executeCommand(commandObjects.hdel(key, field)); + } + + @Override + public long hlen(byte[] key) { + return executeCommand(commandObjects.hlen(key)); + } + + @Override + public Set hkeys(String key) { + return executeCommand(commandObjects.hkeys(key)); + } + + @Override + public List hvals(String key) { + return executeCommand(commandObjects.hvals(key)); + } + + @Override + public Map hgetAll(String key) { + return executeCommand(commandObjects.hgetAll(key)); + } + + @Override + public Set hkeys(byte[] key) { + return executeCommand(commandObjects.hkeys(key)); + } + + @Override + public List hvals(byte[] key) { + return executeCommand(commandObjects.hvals(key)); + } + + @Override + public Map hgetAll(byte[] key) { + return executeCommand(commandObjects.hgetAll(key)); + } + + @Override + public String hrandfield(String key) { + return executeCommand(commandObjects.hrandfield(key)); + } + + @Override + public List hrandfield(String key, long count) { + return executeCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Map hrandfieldWithValues(String key, long count) { + return executeCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public ScanResult> hscan(String key, String cursor, ScanParams params) { + return executeCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public long hstrlen(String key, String field) { + return executeCommand(commandObjects.hstrlen(key, field)); + } + + @Override + public byte[] hrandfield(byte[] key) { + return executeCommand(commandObjects.hrandfield(key)); + } + + @Override + public List hrandfield(byte[] key, long count) { + return executeCommand(commandObjects.hrandfield(key, count)); + } + + @Override + public Map hrandfieldWithValues(byte[] key, long count) { + return executeCommand(commandObjects.hrandfieldWithValues(key, count)); + } + + @Override + public ScanResult> hscan(byte[] key, byte[] cursor, ScanParams params) { + return executeCommand(commandObjects.hscan(key, cursor, params)); + } + + @Override + public long hstrlen(byte[] key, byte[] field) { + return executeCommand(commandObjects.hstrlen(key, field)); + } + // Hash commands + + // Set commands + @Override + public long sadd(String key, String... member) { + return executeCommand(commandObjects.sadd(key, member)); + } + + @Override + public Set smembers(String key) { + return executeCommand(commandObjects.smembers(key)); + } + + @Override + public long srem(String key, String... member) { + return executeCommand(commandObjects.srem(key, member)); + } + + @Override + public String spop(String key) { + return executeCommand(commandObjects.spop(key)); + } + + @Override + public Set spop(String key, long count) { + return executeCommand(commandObjects.spop(key, count)); + } + + @Override + public long scard(String key) { + return executeCommand(commandObjects.scard(key)); + } + + @Override + public boolean sismember(String key, String member) { + return executeCommand(commandObjects.sismember(key, member)); + } + + @Override + public List smismember(String key, String... members) { + return executeCommand(commandObjects.smismember(key, members)); + } + + @Override + public long sadd(byte[] key, byte[]... member) { + return executeCommand(commandObjects.sadd(key, member)); + } + + @Override + public Set smembers(byte[] key) { + return executeCommand(commandObjects.smembers(key)); + } + + @Override + public long srem(byte[] key, byte[]... member) { + return executeCommand(commandObjects.srem(key, member)); + } + + @Override + public byte[] spop(byte[] key) { + return executeCommand(commandObjects.spop(key)); + } + + @Override + public Set spop(byte[] key, long count) { + return executeCommand(commandObjects.spop(key, count)); + } + + @Override + public long scard(byte[] key) { + return executeCommand(commandObjects.scard(key)); + } + + @Override + public boolean sismember(byte[] key, byte[] member) { + return executeCommand(commandObjects.sismember(key, member)); + } + + @Override + public List smismember(byte[] key, byte[]... members) { + return executeCommand(commandObjects.smismember(key, members)); + } + + @Override + public String srandmember(String key) { + return executeCommand(commandObjects.srandmember(key)); + } + + @Override + public List srandmember(String key, int count) { + return executeCommand(commandObjects.srandmember(key, count)); + } + + @Override + public ScanResult sscan(String key, String cursor, ScanParams params) { + return executeCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public byte[] srandmember(byte[] key) { + return executeCommand(commandObjects.srandmember(key)); + } + + @Override + public List srandmember(byte[] key, int count) { + return executeCommand(commandObjects.srandmember(key, count)); + } + + @Override + public ScanResult sscan(byte[] key, byte[] cursor, ScanParams params) { + return executeCommand(commandObjects.sscan(key, cursor, params)); + } + + @Override + public Set sdiff(String... keys) { + return executeCommand(commandObjects.sdiff(keys)); + } + + @Override + public long sdiffstore(String dstkey, String... keys) { + return executeCommand(commandObjects.sdiffstore(dstkey, keys)); + } + + @Override + public Set sinter(String... keys) { + return executeCommand(commandObjects.sinter(keys)); + } + + @Override + public long sinterstore(String dstkey, String... keys) { + return executeCommand(commandObjects.sinterstore(dstkey, keys)); + } + + @Override + public Set sunion(String... keys) { + return executeCommand(commandObjects.sunion(keys)); + } + + @Override + public long sunionstore(String dstkey, String... keys) { + return executeCommand(commandObjects.sunionstore(dstkey, keys)); + } + + @Override + public long smove(String srckey, String dstkey, String member) { + return executeCommand(commandObjects.smove(srckey, dstkey, member)); + } + + @Override + public Set sdiff(byte[]... keys) { + return executeCommand(commandObjects.sdiff(keys)); + } + + @Override + public long sdiffstore(byte[] dstkey, byte[]... keys) { + return executeCommand(commandObjects.sdiffstore(dstkey, keys)); + } + + @Override + public Set sinter(byte[]... keys) { + return executeCommand(commandObjects.sinter(keys)); + } + + @Override + public long sinterstore(byte[] dstkey, byte[]... keys) { + return executeCommand(commandObjects.sinterstore(dstkey, keys)); + } + + @Override + public Set sunion(byte[]... keys) { + return executeCommand(commandObjects.sunion(keys)); + } + + @Override + public long sunionstore(byte[] dstkey, byte[]... keys) { + return executeCommand(commandObjects.sunionstore(dstkey, keys)); + } + + @Override + public long smove(byte[] srckey, byte[] dstkey, byte[] member) { + return executeCommand(commandObjects.smove(srckey, dstkey, member)); + } + // Set commands + + // Sorted Set commands + @Override + public long zadd(String key, double score, String member) { + return executeCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public long zadd(String key, double score, String member, ZAddParams params) { + return executeCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public long zadd(String key, Map scoreMembers) { + return executeCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public long zadd(String key, Map scoreMembers, ZAddParams params) { + return executeCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Double zaddIncr(String key, double score, String member, ZAddParams params) { + return executeCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public long zadd(byte[] key, double score, byte[] member) { + return executeCommand(commandObjects.zadd(key, score, member)); + } + + @Override + public long zadd(byte[] key, double score, byte[] member, ZAddParams params) { + return executeCommand(commandObjects.zadd(key, score, member, params)); + } + + @Override + public long zadd(byte[] key, Map scoreMembers) { + return executeCommand(commandObjects.zadd(key, scoreMembers)); + } + + @Override + public long zadd(byte[] key, Map scoreMembers, ZAddParams params) { + return executeCommand(commandObjects.zadd(key, scoreMembers, params)); + } + + @Override + public Double zaddIncr(byte[] key, double score, byte[] member, ZAddParams params) { + return executeCommand(commandObjects.zaddIncr(key, score, member, params)); + } + + @Override + public long zrem(String key, String... members) { + return executeCommand(commandObjects.zrem(key, members)); + } + + @Override + public double zincrby(String key, double increment, String member) { + return executeCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Double zincrby(String key, double increment, String member, ZIncrByParams params) { + return executeCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Long zrank(String key, String member) { + return executeCommand(commandObjects.zrank(key, member)); + } + + @Override + public Long zrevrank(String key, String member) { + return executeCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public long zrem(byte[] key, byte[]... members) { + return executeCommand(commandObjects.zrem(key, members)); + } + + @Override + public double zincrby(byte[] key, double increment, byte[] member) { + return executeCommand(commandObjects.zincrby(key, increment, member)); + } + + @Override + public Double zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params) { + return executeCommand(commandObjects.zincrby(key, increment, member, params)); + } + + @Override + public Long zrank(byte[] key, byte[] member) { + return executeCommand(commandObjects.zrank(key, member)); + } + + @Override + public Long zrevrank(byte[] key, byte[] member) { + return executeCommand(commandObjects.zrevrank(key, member)); + } + + @Override + public String zrandmember(String key) { + return executeCommand(commandObjects.zrandmember(key)); + } + + @Override + public List zrandmember(String key, long count) { + return executeCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public List zrandmemberWithScores(String key, long count) { + return executeCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public long zcard(String key) { + return executeCommand(commandObjects.zcard(key)); + } + + @Override + public Double zscore(String key, String member) { + return executeCommand(commandObjects.zscore(key, member)); + } + + @Override + public List zmscore(String key, String... members) { + return executeCommand(commandObjects.zmscore(key, members)); + } + + @Override + public byte[] zrandmember(byte[] key) { + return executeCommand(commandObjects.zrandmember(key)); + } + + @Override + public List zrandmember(byte[] key, long count) { + return executeCommand(commandObjects.zrandmember(key, count)); + } + + @Override + public List zrandmemberWithScores(byte[] key, long count) { + return executeCommand(commandObjects.zrandmemberWithScores(key, count)); + } + + @Override + public long zcard(byte[] key) { + return executeCommand(commandObjects.zcard(key)); + } + + @Override + public Double zscore(byte[] key, byte[] member) { + return executeCommand(commandObjects.zscore(key, member)); + } + + @Override + public List zmscore(byte[] key, byte[]... members) { + return executeCommand(commandObjects.zmscore(key, members)); + } + + @Override + public Tuple zpopmax(String key) { + return executeCommand(commandObjects.zpopmax(key)); + } + + @Override + public List zpopmax(String key, int count) { + return executeCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Tuple zpopmin(String key) { + return executeCommand(commandObjects.zpopmin(key)); + } + + @Override + public List zpopmin(String key, int count) { + return executeCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public long zcount(String key, double min, double max) { + return executeCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public long zcount(String key, String min, String max) { + return executeCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public Tuple zpopmax(byte[] key) { + return executeCommand(commandObjects.zpopmax(key)); + } + + @Override + public List zpopmax(byte[] key, int count) { + return executeCommand(commandObjects.zpopmax(key, count)); + } + + @Override + public Tuple zpopmin(byte[] key) { + return executeCommand(commandObjects.zpopmin(key)); + } + + @Override + public List zpopmin(byte[] key, int count) { + return executeCommand(commandObjects.zpopmin(key, count)); + } + + @Override + public long zcount(byte[] key, double min, double max) { + return executeCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public long zcount(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zcount(key, min, max)); + } + + @Override + public List zrange(String key, long start, long stop) { + return executeCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public List zrevrange(String key, long start, long stop) { + return executeCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public List zrangeWithScores(String key, long start, long stop) { + return executeCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public List zrevrangeWithScores(String key, long start, long stop) { + return executeCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public List zrangeByScore(String key, double min, double max) { + return executeCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public List zrangeByScore(String key, String min, String max) { + return executeCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public List zrevrangeByScore(String key, double max, double min) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public List zrangeByScore(String key, double min, double max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(String key, String max, String min) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public List zrangeByScore(String key, String min, String max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(String key, double max, double min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public List zrangeByScoreWithScores(String key, double min, double max) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public List zrevrangeByScoreWithScores(String key, double max, double min) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public List zrangeByScoreWithScores(String key, double min, double max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(String key, String max, String min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public List zrangeByScoreWithScores(String key, String min, String max) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public List zrevrangeByScoreWithScores(String key, String max, String min) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public List zrangeByScoreWithScores(String key, String min, String max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public List zrange(byte[] key, long start, long stop) { + return executeCommand(commandObjects.zrange(key, start, stop)); + } + + @Override + public List zrevrange(byte[] key, long start, long stop) { + return executeCommand(commandObjects.zrevrange(key, start, stop)); + } + + @Override + public List zrangeWithScores(byte[] key, long start, long stop) { + return executeCommand(commandObjects.zrangeWithScores(key, start, stop)); + } + + @Override + public List zrevrangeWithScores(byte[] key, long start, long stop) { + return executeCommand(commandObjects.zrevrangeWithScores(key, start, stop)); + } + + @Override + public List zrangeByScore(byte[] key, double min, double max) { + return executeCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public List zrangeByScore(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zrangeByScore(key, min, max)); + } + + @Override + public List zrevrangeByScore(byte[] key, double max, double min) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public List zrangeByScore(byte[] key, double min, double max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(byte[] key, byte[] max, byte[] min) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min)); + } + + @Override + public List zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScore(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(byte[] key, double max, double min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public List zrangeByScoreWithScores(byte[] key, double min, double max) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public List zrevrangeByScoreWithScores(byte[] key, double max, double min) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public List zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScore(key, max, min, offset, count)); + } + + @Override + public List zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max)); + } + + @Override + public List zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min)); + } + + @Override + public List zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count) { + return executeCommand(commandObjects.zrangeByScoreWithScores(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public List zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByScoreWithScores(key, max, min, offset, count)); + } + + @Override + public long zremrangeByRank(String key, long start, long stop) { + return executeCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public long zremrangeByScore(String key, double min, double max) { + return executeCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public long zremrangeByScore(String key, String min, String max) { + return executeCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public long zremrangeByRank(byte[] key, long start, long stop) { + return executeCommand(commandObjects.zremrangeByRank(key, start, stop)); + } + + @Override + public long zremrangeByScore(byte[] key, double min, double max) { + return executeCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public long zremrangeByScore(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zremrangeByScore(key, min, max)); + } + + @Override + public long zlexcount(String key, String min, String max) { + return executeCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public List zrangeByLex(String key, String min, String max) { + return executeCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public List zrangeByLex(String key, String min, String max, int offset, int count) { + return executeCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByLex(String key, String max, String min) { + return executeCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public List zrevrangeByLex(String key, String max, String min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public long zremrangeByLex(String key, String min, String max) { + return executeCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public long zlexcount(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zlexcount(key, min, max)); + } + + @Override + public List zrangeByLex(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zrangeByLex(key, min, max)); + } + + @Override + public List zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count) { + return executeCommand(commandObjects.zrangeByLex(key, min, max, offset, count)); + } + + @Override + public List zrevrangeByLex(byte[] key, byte[] max, byte[] min) { + return executeCommand(commandObjects.zrevrangeByLex(key, max, min)); + } + + @Override + public List zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count) { + return executeCommand(commandObjects.zrevrangeByLex(key, max, min, offset, count)); + } + + @Override + public long zremrangeByLex(byte[] key, byte[] min, byte[] max) { + return executeCommand(commandObjects.zremrangeByLex(key, min, max)); + } + + @Override + public ScanResult zscan(String key, String cursor, ScanParams params) { + return executeCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public ScanResult zscan(byte[] key, byte[] cursor, ScanParams params) { + return executeCommand(commandObjects.zscan(key, cursor, params)); + } + + @Override + public KeyedZSetElement bzpopmax(double timeout, String... keys) { + return executeCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public KeyedZSetElement bzpopmin(double timeout, String... keys) { + return executeCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public List bzpopmax(double timeout, byte[]... keys) { + return executeCommand(commandObjects.bzpopmax(timeout, keys)); + } + + @Override + public List bzpopmin(double timeout, byte[]... keys) { + return executeCommand(commandObjects.bzpopmin(timeout, keys)); + } + + @Override + public Set zdiff(String... keys) { + return executeCommand(commandObjects.zdiff(keys)); + } + + @Override + public Set zdiffWithScores(String... keys) { + return executeCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public long zdiffStore(String dstkey, String... keys) { + return executeCommand(commandObjects.zdiffStore(dstkey, keys)); + } + + @Override + public Set zdiff(byte[]... keys) { + return executeCommand(commandObjects.zdiff(keys)); + } + + @Override + public Set zdiffWithScores(byte[]... keys) { + return executeCommand(commandObjects.zdiffWithScores(keys)); + } + + @Override + public long zdiffStore(byte[] dstkey, byte[]... keys) { + return executeCommand(commandObjects.zdiffStore(dstkey, keys)); + } + + @Override + public long zinterstore(String dstkey, String... sets) { + return executeCommand(commandObjects.zinterstore(dstkey, sets)); + } + + @Override + public long zinterstore(String dstkey, ZParams params, String... sets) { + return executeCommand(commandObjects.zinterstore(dstkey, params, sets)); + } + + @Override + public Set zinter(ZParams params, String... keys) { + return executeCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Set zinterWithScores(ZParams params, String... keys) { + return executeCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public long zinterstore(byte[] dstkey, byte[]... sets) { + return executeCommand(commandObjects.zinterstore(dstkey, sets)); + } + + @Override + public long zinterstore(byte[] dstkey, ZParams params, byte[]... sets) { + return executeCommand(commandObjects.zinterstore(dstkey, params, sets)); + } + + @Override + public Set zinter(ZParams params, byte[]... keys) { + return executeCommand(commandObjects.zinter(params, keys)); + } + + @Override + public Set zinterWithScores(ZParams params, byte[]... keys) { + return executeCommand(commandObjects.zinterWithScores(params, keys)); + } + + @Override + public Set zunion(ZParams params, String... keys) { + return executeCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Set zunionWithScores(ZParams params, String... keys) { + return executeCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public long zunionstore(String dstkey, String... sets) { + return executeCommand(commandObjects.zunionstore(dstkey, sets)); + } + + @Override + public long zunionstore(String dstkey, ZParams params, String... sets) { + return executeCommand(commandObjects.zunionstore(dstkey, params, sets)); + } + + @Override + public Set zunion(ZParams params, byte[]... keys) { + return executeCommand(commandObjects.zunion(params, keys)); + } + + @Override + public Set zunionWithScores(ZParams params, byte[]... keys) { + return executeCommand(commandObjects.zunionWithScores(params, keys)); + } + + @Override + public long zunionstore(byte[] dstkey, byte[]... sets) { + return executeCommand(commandObjects.zunionstore(dstkey, sets)); + } + + @Override + public long zunionstore(byte[] dstkey, ZParams params, byte[]... sets) { + return executeCommand(commandObjects.zunionstore(dstkey, params, sets)); + } + // Sorted Set commands + + // Geo commands + @Override + public long geoadd(String key, double longitude, double latitude, String member) { + return executeCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public long geoadd(String key, Map memberCoordinateMap) { + return executeCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public long geoadd(String key, GeoAddParams params, Map memberCoordinateMap) { + return executeCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Double geodist(String key, String member1, String member2) { + return executeCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Double geodist(String key, String member1, String member2, GeoUnit unit) { + return executeCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public List geohash(String key, String... members) { + return executeCommand(commandObjects.geohash(key, members)); + } + + @Override + public List geopos(String key, String... members) { + return executeCommand(commandObjects.geopos(key, members)); + } + + @Override + public long geoadd(byte[] key, double longitude, double latitude, byte[] member) { + return executeCommand(commandObjects.geoadd(key, longitude, latitude, member)); + } + + @Override + public long geoadd(byte[] key, Map memberCoordinateMap) { + return executeCommand(commandObjects.geoadd(key, memberCoordinateMap)); + } + + @Override + public long geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap) { + return executeCommand(commandObjects.geoadd(key, params, memberCoordinateMap)); + } + + @Override + public Double geodist(byte[] key, byte[] member1, byte[] member2) { + return executeCommand(commandObjects.geodist(key, member1, member2)); + } + + @Override + public Double geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit) { + return executeCommand(commandObjects.geodist(key, member1, member2, unit)); + } + + @Override + public List geohash(byte[] key, byte[]... members) { + return executeCommand(commandObjects.geohash(key, members)); + } + + @Override + public List geopos(byte[] key, byte[]... members) { + return executeCommand(commandObjects.geopos(key, members)); + } + + @Override + public List georadius(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public List georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public List georadius(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public List georadiusReadonly(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public List georadiusByMember(String key, String member, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public List georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public List georadiusByMember(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public List georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public long georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return executeCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public long georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return executeCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + + @Override + public List georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit)); + } + + @Override + public List georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit)); + } + + @Override + public List georadius(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadius(key, longitude, latitude, radius, unit, param)); + } + + @Override + public List georadiusReadonly(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadiusReadonly(key, longitude, latitude, radius, unit, param)); + } + + @Override + public List georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadiusByMember(key, member, radius, unit)); + } + + @Override + public List georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit) { + return executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit)); + } + + @Override + public List georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadiusByMember(key, member, radius, unit, param)); + } + + @Override + public List georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param) { + return executeCommand(commandObjects.georadiusByMemberReadonly(key, member, radius, unit, param)); + } + + @Override + public long georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return executeCommand(commandObjects.georadiusStore(key, longitude, latitude, radius, unit, param, storeParam)); + } + + @Override + public long georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam) { + return executeCommand(commandObjects.georadiusByMemberStore(key, member, radius, unit, param, storeParam)); + } + // Geo commands + + // Hyper Log Log commands + @Override + public long pfadd(String key, String... elements) { + return executeCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public String pfmerge(String destkey, String... sourcekeys) { + return executeCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public long pfcount(String key) { + return executeCommand(commandObjects.pfcount(key)); + } + + @Override + public long pfcount(String... keys) { + return executeCommand(commandObjects.pfcount(keys)); + } + + @Override + public long pfadd(byte[] key, byte[]... elements) { + return executeCommand(commandObjects.pfadd(key, elements)); + } + + @Override + public String pfmerge(byte[] destkey, byte[]... sourcekeys) { + return executeCommand(commandObjects.pfmerge(destkey, sourcekeys)); + } + + @Override + public long pfcount(byte[] key) { + return executeCommand(commandObjects.pfcount(key)); + } + + @Override + public long pfcount(byte[]... keys) { + return executeCommand(commandObjects.pfcount(keys)); + } + // Hyper Log Log commands + + // Stream commands + @Override + public StreamEntryID xadd(String key, StreamEntryID id, Map hash) { + return executeCommand(commandObjects.xadd(key, id, hash)); + } + + @Override + public StreamEntryID xadd_v2(String key, XAddParams params, Map hash) { + return executeCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public long xlen(String key) { + return executeCommand(commandObjects.xlen(key)); + } + + @Override + public List xrange(String key, StreamEntryID start, StreamEntryID end) { + return executeCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public List xrange(String key, StreamEntryID start, StreamEntryID end, int count) { + return executeCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public List xrevrange(String key, StreamEntryID end, StreamEntryID start) { + return executeCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public List xrevrange(String key, StreamEntryID end, StreamEntryID start, int count) { + return executeCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public long xack(String key, String group, StreamEntryID... ids) { + return executeCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public String xgroupCreate(String key, String groupname, StreamEntryID id, boolean makeStream) { + return executeCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public String xgroupSetID(String key, String groupname, StreamEntryID id) { + return executeCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public long xgroupDestroy(String key, String groupname) { + return executeCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public long xgroupDelConsumer(String key, String groupname, String consumername) { + return executeCommand(commandObjects.xgroupDelConsumer(key, groupname, consumername)); + } + + @Override + public StreamPendingSummary xpending(String key, String groupname) { + return executeCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public List xpending(String key, String groupname, StreamEntryID start, StreamEntryID end, int count, String consumername) { + return executeCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public List xpending(String key, String groupname, XPendingParams params) { + return executeCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public long xdel(String key, StreamEntryID... ids) { + return executeCommand(commandObjects.xdel(key, ids)); + } + + @Override + public long xtrim(String key, long maxLen, boolean approximate) { + return executeCommand(commandObjects.xtrim(key, maxLen, approximate)); + } + + @Override + public long xtrim(String key, XTrimParams params) { + return executeCommand(commandObjects.xtrim(key, params)); + } + + @Override + public List xclaim(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return executeCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public List xclaimJustId(String key, String group, String consumername, long minIdleTime, XClaimParams params, StreamEntryID... ids) { + return executeCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public Map.Entry> xautoclaim(String key, String group, String consumerName, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return executeCommand(commandObjects.xautoclaim(key, group, consumerName, minIdleTime, start, params)); + } + + @Override + public Map.Entry> xautoclaimJustId(String key, String group, String consumerName, long minIdleTime, StreamEntryID start, XAutoClaimParams params) { + return executeCommand(commandObjects.xautoclaimJustId(key, group, consumerName, minIdleTime, start, params)); + } + + @Override + public StreamInfo xinfoStream(String key) { + return executeCommand(commandObjects.xinfoStream(key)); + } + + @Override + public List xinfoGroup(String key) { + return executeCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public List xinfoConsumers(String key, String group) { + return executeCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public List>> xread(XReadParams xReadParams, Map streams) { + return executeCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public List>> xreadGroup(String groupname, String consumer, + XReadGroupParams xReadGroupParams, Map streams) { + return executeCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + + @Override + public byte[] xadd(byte[] key, XAddParams params, Map hash) { + return executeCommand(commandObjects.xadd(key, params, hash)); + } + + @Override + public long xlen(byte[] key) { + return executeCommand(commandObjects.xlen(key)); + } + + @Override + public List xrange(byte[] key, byte[] start, byte[] end) { + return executeCommand(commandObjects.xrange(key, start, end)); + } + + @Override + public List xrange(byte[] key, byte[] start, byte[] end, int count) { + return executeCommand(commandObjects.xrange(key, start, end, count)); + } + + @Override + public List xrevrange(byte[] key, byte[] end, byte[] start) { + return executeCommand(commandObjects.xrevrange(key, end, start)); + } + + @Override + public List xrevrange(byte[] key, byte[] end, byte[] start, int count) { + return executeCommand(commandObjects.xrevrange(key, end, start, count)); + } + + @Override + public long xack(byte[] key, byte[] group, byte[]... ids) { + return executeCommand(commandObjects.xack(key, group, ids)); + } + + @Override + public String xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream) { + return executeCommand(commandObjects.xgroupCreate(key, groupname, id, makeStream)); + } + + @Override + public String xgroupSetID(byte[] key, byte[] groupname, byte[] id) { + return executeCommand(commandObjects.xgroupSetID(key, groupname, id)); + } + + @Override + public long xgroupDestroy(byte[] key, byte[] groupname) { + return executeCommand(commandObjects.xgroupDestroy(key, groupname)); + } + + @Override + public long xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName) { + return executeCommand(commandObjects.xgroupDelConsumer(key, groupname, consumerName)); + } + + @Override + public long xdel(byte[] key, byte[]... ids) { + return executeCommand(commandObjects.xdel(key, ids)); + } + + @Override + public long xtrim(byte[] key, long maxLen, boolean approximateLength) { + return executeCommand(commandObjects.xtrim(key, maxLen, approximateLength)); + } + + @Override + public long xtrim(byte[] key, XTrimParams params) { + return executeCommand(commandObjects.xtrim(key, params)); + } + + @Override + public Object xpending(byte[] key, byte[] groupname) { + return executeCommand(commandObjects.xpending(key, groupname)); + } + + @Override + public List xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername) { + return executeCommand(commandObjects.xpending(key, groupname, start, end, count, consumername)); + } + + @Override + public List xpending(byte[] key, byte[] groupname, XPendingParams params) { + return executeCommand(commandObjects.xpending(key, groupname, params)); + } + + @Override + public List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return executeCommand(commandObjects.xclaim(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids) { + return executeCommand(commandObjects.xclaimJustId(key, group, consumername, minIdleTime, params, ids)); + } + + @Override + public List xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return executeCommand(commandObjects.xautoclaim(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public List xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, long minIdleTime, byte[] start, XAutoClaimParams params) { + return executeCommand(commandObjects.xautoclaimJustId(key, groupName, consumerName, minIdleTime, start, params)); + } + + @Override + public Object xinfoStream(byte[] key) { + return executeCommand(commandObjects.xinfoStream(key)); + } + + @Override + public List xinfoGroup(byte[] key) { + return executeCommand(commandObjects.xinfoGroup(key)); + } + + @Override + public List xinfoConsumers(byte[] key, byte[] group) { + return executeCommand(commandObjects.xinfoConsumers(key, group)); + } + + @Override + public List xread(XReadParams xReadParams, Map.Entry... streams) { + return executeCommand(commandObjects.xread(xReadParams, streams)); + } + + @Override + public List xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, Map.Entry... streams) { + return executeCommand(commandObjects.xreadGroup(groupname, consumer, xReadGroupParams, streams)); + } + // Stream commands + + // Scripting commands + @Override + public Object eval(String script) { + return executeCommand(commandObjects.eval(script)); + } + + @Override + public Object eval(String script, int keyCount, String... params) { + return executeCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Object eval(String script, List keys, List args) { + return executeCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Object evalsha(String sha1) { + return executeCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Object evalsha(String sha1, int keyCount, String... params) { + return executeCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Object evalsha(String sha1, List keys, List args) { + return executeCommand(commandObjects.evalsha(sha1, keys, args)); + } + + @Override + public Object eval(byte[] script) { + return executeCommand(commandObjects.eval(script)); + } + + @Override + public Object eval(byte[] script, int keyCount, byte[]... params) { + return executeCommand(commandObjects.eval(script, keyCount, params)); + } + + @Override + public Object eval(byte[] script, List keys, List args) { + return executeCommand(commandObjects.eval(script, keys, args)); + } + + @Override + public Object evalsha(byte[] sha1) { + return executeCommand(commandObjects.evalsha(sha1)); + } + + @Override + public Object evalsha(byte[] sha1, int keyCount, byte[]... params) { + return executeCommand(commandObjects.evalsha(sha1, keyCount, params)); + } + + @Override + public Object evalsha(byte[] sha1, List keys, List args) { + return executeCommand(commandObjects.evalsha(sha1, keys, args)); + } + // Scripting commands + + // Other key commands + @Override + public Long objectRefcount(String key) { + return executeCommand(commandObjects.objectRefcount(key)); + } + + @Override + public String objectEncoding(String key) { + return executeCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Long objectIdletime(String key) { + return executeCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Long objectFreq(String key) { + return executeCommand(commandObjects.objectFreq(key)); + } + + @Override + public Long objectRefcount(byte[] key) { + return executeCommand(commandObjects.objectRefcount(key)); + } + + @Override + public byte[] objectEncoding(byte[] key) { + return executeCommand(commandObjects.objectEncoding(key)); + } + + @Override + public Long objectIdletime(byte[] key) { + return executeCommand(commandObjects.objectIdletime(key)); + } + + @Override + public Long objectFreq(byte[] key) { + return executeCommand(commandObjects.objectFreq(key)); + } + + @Override + public String migrate(String host, int port, String key, int timeout) { + return executeCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public String migrate(String host, int port, int timeout, MigrateParams params, String... keys) { + return executeCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + + @Override + public String migrate(String host, int port, byte[] key, int timeout) { + return executeCommand(commandObjects.migrate(host, port, key, timeout)); + } + + @Override + public String migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys) { + return executeCommand(commandObjects.migrate(host, port, timeout, params, keys)); + } + // Other key commands + + // Sample key commands + @Override + public long waitReplicas(String sampleKey, int replicas, long timeout) { + return executeCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public long waitReplicas(byte[] sampleKey, int replicas, long timeout) { + return executeCommand(commandObjects.waitReplicas(sampleKey, replicas, timeout)); + } + + @Override + public Object eval(String script, String sampleKey) { + return executeCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Object evalsha(String sha1, String sampleKey) { + return executeCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Object eval(byte[] script, byte[] sampleKey) { + return executeCommand(commandObjects.eval(script, sampleKey)); + } + + @Override + public Object evalsha(byte[] sha1, byte[] sampleKey) { + return executeCommand(commandObjects.evalsha(sha1, sampleKey)); + } + + @Override + public Boolean scriptExists(String sha1, String sampleKey) { + return scriptExists(sampleKey, new String[]{sha1}).get(0); + } + + @Override + public List scriptExists(String sampleKey, String... sha1s) { + return executeCommand(commandObjects.scriptExists(sampleKey, sha1s)); + } + + @Override + public Boolean scriptExists(byte[] sha1, byte[] sampleKey) { + return scriptExists(sampleKey, new byte[][]{sha1}).get(0); + } + + @Override + public List scriptExists(byte[] sampleKey, byte[]... sha1s) { + return executeCommand(commandObjects.scriptExists(sampleKey, sha1s)); + } + + @Override + public String scriptLoad(String script, String sampleKey) { + return executeCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public String scriptFlush(String sampleKey) { + return executeCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public String scriptFlush(String sampleKey, FlushMode flushMode) { + return executeCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public String scriptKill(String sampleKey) { + return executeCommand(commandObjects.scriptKill(sampleKey)); + } + + @Override + public byte[] scriptLoad(byte[] script, byte[] sampleKey) { + return executeCommand(commandObjects.scriptLoad(script, sampleKey)); + } + + @Override + public String scriptFlush(byte[] sampleKey) { + return executeCommand(commandObjects.scriptFlush(sampleKey)); + } + + @Override + public String scriptFlush(byte[] sampleKey, FlushMode flushMode) { + return executeCommand(commandObjects.scriptFlush(sampleKey, flushMode)); + } + + @Override + public String scriptKill(byte[] sampleKey) { + return executeCommand(commandObjects.scriptKill(sampleKey)); + } + // Sample key commands + + // Random node commands + public long publish(String channel, String message) { + return executeCommand(commandObjects.publish(channel, message)); + } + + public long publish(byte[] channel, byte[] message) { + return executeCommand(commandObjects.publish(channel, message)); + } + + public LCSMatchResult strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params) { + return executeCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + + public LCSMatchResult strAlgoLCSStrings(byte[] strA, byte[] strB, StrAlgoLCSParams params) { + return executeCommand(commandObjects.strAlgoLCSStrings(strA, strB, params)); + } + // Random node commands + + // RediSearch commands + @Override + public String ftCreate(String indexName, IndexOptions indexOptions, Schema schema) { + return executeCommand(commandObjects.ftCreate(indexName, indexOptions, schema)); + } + + @Override + public String ftAlter(String indexName, Schema schema) { + return executeCommand(commandObjects.ftAlter(indexName, schema)); + } + + @Override + public SearchResult ftSearch(String indexName, Query query) { + return executeCommand(commandObjects.ftSearch(indexName, query)); + } + + @Override + public SearchResult ftSearch(byte[] indexName, Query query) { + return executeCommand(commandObjects.ftSearch(indexName, query)); + } + + @Override + public String ftExplain(String indexName, Query query) { + return executeCommand(commandObjects.ftExplain(indexName, query)); + } + + @Override + public List ftExplainCLI(String indexName, Query query) { + return executeCommand(commandObjects.ftExplainCLI(indexName, query)); + } + + @Override + public AggregationResult ftAggregate(String indexName, AggregationBuilder aggr) { + return executeCommand(commandObjects.ftAggregate(indexName, aggr)); + } + + @Override + public AggregationResult ftCursorRead(String indexName, long cursorId, int count) { + return executeCommand(commandObjects.ftCursorRead(indexName, cursorId, count)); + } + + @Override + public String ftCursorDel(String indexName, long cursorId) { + return executeCommand(commandObjects.ftCursorDel(indexName, cursorId)); + } + + @Override + public String ftDropIndex(String indexName) { + return executeCommand(commandObjects.ftDropIndex(indexName)); + } + + @Override + public String ftDropIndexDD(String indexName) { + return executeCommand(commandObjects.ftDropIndexDD(indexName)); + } + + @Override + public String ftSynUpdate(String indexName, String synonymGroupId, String... terms) { + return executeCommand(commandObjects.ftSynUpdate(indexName, synonymGroupId, terms)); + } + + @Override + public Map> ftSynDump(String indexName) { + return executeCommand(commandObjects.ftSynDump(indexName)); + } + + @Override + public Map ftInfo(String indexName) { + return executeCommand(commandObjects.ftInfo(indexName)); + } + + @Override + public String ftAliasAdd(String aliasName, String indexName) { + return executeCommand(commandObjects.ftAliasAdd(aliasName, indexName)); + } + + @Override + public String ftAliasUpdate(String aliasName, String indexName) { + return executeCommand(commandObjects.ftAliasUpdate(aliasName, indexName)); + } + + @Override + public String ftAliasDel(String aliasName) { + return executeCommand(commandObjects.ftAliasDel(aliasName)); + } + + @Override + public Map ftConfigGet(String option) { + return executeCommand(commandObjects.ftConfigGet(option)); + } + + @Override + public Map ftConfigGet(String indexName, String option) { + return executeCommand(commandObjects.ftConfigGet(indexName, option)); + } + + @Override + public String ftConfigSet(String option, String value) { + return executeCommand(commandObjects.ftConfigSet(option, value)); + } + + @Override + public String ftConfigSet(String indexName, String option, String value) { + return executeCommand(commandObjects.ftConfigSet(indexName, option, value)); + } + // RediSearch commands + + // RedisJSON commands + @Override + public String jsonSet(String key, Path2 path, Object object) { + return executeCommand(commandObjects.jsonSet(key, path, object)); + } + + @Override + public String jsonSetWithEscape(String key, Path2 path, Object object) { + return executeCommand(commandObjects.jsonSetWithEscape(key, path, object)); + } + + @Override + public String jsonSet(String key, Path path, Object pojo) { + return executeCommand(commandObjects.jsonSet(key, path, pojo)); + } + + @Override + public String jsonSet(String key, Path2 path, Object pojo, JsonSetParams params) { + return executeCommand(commandObjects.jsonSet(key, path, pojo, params)); + } + + @Override + public String jsonSetWithEscape(String key, Path2 path, Object pojo, JsonSetParams params) { + return executeCommand(commandObjects.jsonSetWithEscape(key, path, pojo, params)); + } + + @Override + public String jsonSet(String key, Path path, Object pojo, JsonSetParams params) { + return executeCommand(commandObjects.jsonSet(key, path, pojo, params)); + } + + @Override + public Object jsonGet(String key) { + return executeCommand(commandObjects.jsonGet(key)); + } + + @Override + public T jsonGet(String key, Class clazz) { + return executeCommand(commandObjects.jsonGet(key, clazz)); + } + + @Override + public Object jsonGet(String key, Path2... paths) { + return executeCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public Object jsonGet(String key, Path... paths) { + return executeCommand(commandObjects.jsonGet(key, paths)); + } + + @Override + public T jsonGet(String key, Class clazz, Path... paths) { + return executeCommand(commandObjects.jsonGet(key, clazz, paths)); + } + + @Override + public List jsonMGet(Path2 path, String... keys) { + return executeCommand(commandObjects.jsonMGet(path, keys)); + } + + @Override + public List jsonMGet(Path path, Class clazz, String... keys) { + return executeCommand(commandObjects.jsonMGet(path, clazz, keys)); + } + + @Override + public long jsonDel(String key) { + return executeCommand(commandObjects.jsonDel(key)); + } + + @Override + public long jsonDel(String key, Path2 path) { + return executeCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public long jsonDel(String key, Path path) { + return executeCommand(commandObjects.jsonDel(key, path)); + } + + @Override + public long jsonClear(String key) { + return executeCommand(commandObjects.jsonClear(key)); + } + + @Override + public long jsonClear(String key, Path2 path) { + return executeCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public long jsonClear(String key, Path path) { + return executeCommand(commandObjects.jsonClear(key, path)); + } + + @Override + public List jsonToggle(String key, Path2 path) { + return executeCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public String jsonToggle(String key, Path path) { + return executeCommand(commandObjects.jsonToggle(key, path)); + } + + @Override + public Class jsonType(String key) { + return executeCommand(commandObjects.jsonType(key)); + } + + @Override + public List> jsonType(String key, Path2 path) { + return executeCommand(commandObjects.jsonType(key, path)); + } + + @Override + public Class jsonType(String key, Path path) { + return executeCommand(commandObjects.jsonType(key, path)); + } + + @Override + public long jsonStrAppend(String key, Object string) { + return executeCommand(commandObjects.jsonStrAppend(key, string)); + } + + @Override + public List jsonStrAppend(String key, Path2 path, Object string) { + return executeCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public long jsonStrAppend(String key, Path path, Object string) { + return executeCommand(commandObjects.jsonStrAppend(key, path, string)); + } + + @Override + public Long jsonStrLen(String key) { + return executeCommand(commandObjects.jsonStrLen(key)); + } + + @Override + public List jsonStrLen(String key, Path2 path) { + return executeCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public Long jsonStrLen(String key, Path path) { + return executeCommand(commandObjects.jsonStrLen(key, path)); + } + + @Override + public List jsonArrAppend(String key, Path2 path, Object... objects) { + return executeCommand(commandObjects.jsonArrAppend(key, path, objects)); + } + + @Override + public List jsonArrAppendWithEscape(String key, Path2 path, Object... objects) { + return executeCommand(commandObjects.jsonArrAppendWithEscape(key, path, objects)); + } + + @Override + public Long jsonArrAppend(String key, Path path, Object... pojos) { + return executeCommand(commandObjects.jsonArrAppend(key, path, pojos)); + } + + @Override + public List jsonArrIndex(String key, Path2 path, Object scalar) { + return executeCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public List jsonArrIndexWithEscape(String key, Path2 path, Object scalar) { + return executeCommand(commandObjects.jsonArrIndexWithEscape(key, path, scalar)); + } + + @Override + public long jsonArrIndex(String key, Path path, Object scalar) { + return executeCommand(commandObjects.jsonArrIndex(key, path, scalar)); + } + + @Override + public List jsonArrInsert(String key, Path2 path, int index, Object... objects) { + return executeCommand(commandObjects.jsonArrInsert(key, path, index, objects)); + } + + @Override + public List jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects) { + return executeCommand(commandObjects.jsonArrInsertWithEscape(key, path, index, objects)); + } + + @Override + public long jsonArrInsert(String key, Path path, int index, Object... pojos) { + return executeCommand(commandObjects.jsonArrInsert(key, path, index, pojos)); + } + + @Override + public Object jsonArrPop(String key) { + return executeCommand(commandObjects.jsonArrPop(key)); + } + + @Override + public T jsonArrPop(String key, Class clazz) { + return executeCommand(commandObjects.jsonArrPop(key, clazz)); + } + + @Override + public List jsonArrPop(String key, Path2 path) { + return executeCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public Object jsonArrPop(String key, Path path) { + return executeCommand(commandObjects.jsonArrPop(key, path)); + } + + @Override + public T jsonArrPop(String key, Class clazz, Path path) { + return executeCommand(commandObjects.jsonArrPop(key, clazz, path)); + } + + @Override + public List jsonArrPop(String key, Path2 path, int index) { + return executeCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public Object jsonArrPop(String key, Path path, int index) { + return executeCommand(commandObjects.jsonArrPop(key, path, index)); + } + + @Override + public T jsonArrPop(String key, Class clazz, Path path, int index) { + return executeCommand(commandObjects.jsonArrPop(key, clazz, path, index)); + } + + @Override + public Long jsonArrLen(String key) { + return executeCommand(commandObjects.jsonArrLen(key)); + } + + @Override + public List jsonArrLen(String key, Path2 path) { + return executeCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public Long jsonArrLen(String key, Path path) { + return executeCommand(commandObjects.jsonArrLen(key, path)); + } + + @Override + public List jsonArrTrim(String key, Path2 path, int start, int stop) { + return executeCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + + @Override + public Long jsonArrTrim(String key, Path path, int start, int stop) { + return executeCommand(commandObjects.jsonArrTrim(key, path, start, stop)); + } + // RedisJSON commands + + public Object sendCommand(ProtocolCommand cmd) { + return executeCommand(commandObjects.commandArguments(cmd)); + } + + public Object sendCommand(ProtocolCommand cmd, byte[]... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args)); + } + + public Object sendBlockingCommand(ProtocolCommand cmd, byte[]... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args).blocking()); + } + + public Object sendCommand(ProtocolCommand cmd, String... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args)); + } + + public Object sendBlockingCommand(ProtocolCommand cmd, String... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args).blocking()); + } + + public Object sendCommand(byte[] sampleKey, ProtocolCommand cmd, byte[]... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args).processKey(sampleKey)); + } + + public Object sendBlockingCommand(byte[] sampleKey, ProtocolCommand cmd, byte[]... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args).blocking().processKey(sampleKey)); + } + + public Object sendCommand(String sampleKey, ProtocolCommand cmd, String... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args).processKey(sampleKey)); + } + + public Object sendBlockingCommand(String sampleKey, ProtocolCommand cmd, String... args) { + return executeCommand(commandObjects.commandArguments(cmd).addObjects((Object[]) args).blocking().processKey(sampleKey)); + } + + public Object executeCommand(CommandArguments args) { + return executeCommand(new CommandObject<>(args, BuilderFactory.RAW_OBJECT)); + } +} diff --git a/src/main/java/redis/clients/jedis/args/BitOP.java b/src/main/java/redis/clients/jedis/args/BitOP.java new file mode 100644 index 0000000000..81ba6302ff --- /dev/null +++ b/src/main/java/redis/clients/jedis/args/BitOP.java @@ -0,0 +1,19 @@ +package redis.clients.jedis.args; + +import redis.clients.jedis.util.SafeEncoder; + +public enum BitOP implements Rawable { + + AND, OR, XOR, NOT; + + private final byte[] raw; + + private BitOP() { + raw = SafeEncoder.encode(name()); + } + + @Override + public byte[] getRaw() { + return raw; + } +} diff --git a/src/main/java/redis/clients/jedis/args/FlushMode.java b/src/main/java/redis/clients/jedis/args/FlushMode.java index 4be513066f..92bc3b528e 100644 --- a/src/main/java/redis/clients/jedis/args/FlushMode.java +++ b/src/main/java/redis/clients/jedis/args/FlushMode.java @@ -19,7 +19,7 @@ public enum FlushMode implements Rawable { private final byte[] raw; - FlushMode() { + private FlushMode() { raw = SafeEncoder.encode(this.name()); } diff --git a/src/main/java/redis/clients/jedis/args/GeoUnit.java b/src/main/java/redis/clients/jedis/args/GeoUnit.java new file mode 100644 index 0000000000..61dae2ac6e --- /dev/null +++ b/src/main/java/redis/clients/jedis/args/GeoUnit.java @@ -0,0 +1,20 @@ +package redis.clients.jedis.args; + +import java.util.Locale; +import redis.clients.jedis.util.SafeEncoder; + +public enum GeoUnit implements Rawable { + + M, KM, MI, FT; + + private final byte[] raw; + + private GeoUnit() { + raw = SafeEncoder.encode(name().toLowerCase(Locale.ENGLISH)); + } + + @Override + public byte[] getRaw() { + return raw; + } +} diff --git a/src/main/java/redis/clients/jedis/args/ListDirection.java b/src/main/java/redis/clients/jedis/args/ListDirection.java index 0c5d71c766..6108b6bdfb 100644 --- a/src/main/java/redis/clients/jedis/args/ListDirection.java +++ b/src/main/java/redis/clients/jedis/args/ListDirection.java @@ -6,12 +6,13 @@ * Direction for {@code LMOVE} and {@code BLMOVE} command. */ public enum ListDirection implements Rawable { + LEFT, RIGHT; private final byte[] raw; - ListDirection() { - raw = SafeEncoder.encode(this.name()); + private ListDirection() { + raw = SafeEncoder.encode(name()); } @Override diff --git a/src/main/java/redis/clients/jedis/args/ListPosition.java b/src/main/java/redis/clients/jedis/args/ListPosition.java new file mode 100644 index 0000000000..04cfdc35e9 --- /dev/null +++ b/src/main/java/redis/clients/jedis/args/ListPosition.java @@ -0,0 +1,19 @@ +package redis.clients.jedis.args; + +import redis.clients.jedis.util.SafeEncoder; + +public enum ListPosition implements Rawable { + + BEFORE, AFTER; + + private final byte[] raw; + + private ListPosition() { + raw = SafeEncoder.encode(name()); + } + + @Override + public byte[] getRaw() { + return raw; + } +} diff --git a/src/main/java/redis/clients/jedis/args/RawableFactory.java b/src/main/java/redis/clients/jedis/args/RawableFactory.java new file mode 100644 index 0000000000..ea9fd1e24e --- /dev/null +++ b/src/main/java/redis/clients/jedis/args/RawableFactory.java @@ -0,0 +1,39 @@ +package redis.clients.jedis.args; + +import redis.clients.jedis.util.SafeEncoder; + +public final class RawableFactory { + + public static Rawable from(byte[] binary) { + return new Raw(binary); + } + + public static Rawable from(String string) { + return new RawString(string); + } + + public static class Raw implements Rawable { + + private final byte[] raw; + + public Raw(byte[] raw) { + this.raw = raw; + } + + @Override + public byte[] getRaw() { + return raw; + } + } + + public static class RawString extends Raw { + + public RawString(String str) { + super(SafeEncoder.encode(str)); + } + } + + private RawableFactory() { + throw new InstantiationError(); + } +} diff --git a/src/main/java/redis/clients/jedis/args/UnblockType.java b/src/main/java/redis/clients/jedis/args/UnblockType.java index a69dd4105d..9a6217a8a4 100644 --- a/src/main/java/redis/clients/jedis/args/UnblockType.java +++ b/src/main/java/redis/clients/jedis/args/UnblockType.java @@ -6,11 +6,12 @@ * Unblock type for {@code CLIENT UNBLOCK} command. */ public enum UnblockType implements Rawable { + TIMEOUT, ERROR; private final byte[] raw; - UnblockType() { + private UnblockType() { raw = SafeEncoder.encode(this.name()); } diff --git a/src/main/java/redis/clients/jedis/args/package-info.java b/src/main/java/redis/clients/jedis/args/package-info.java index ecf8acb3a6..fb06d1bf43 100644 --- a/src/main/java/redis/clients/jedis/args/package-info.java +++ b/src/main/java/redis/clients/jedis/args/package-info.java @@ -1,4 +1,4 @@ /* - * This package contains the classes that represent different Redis command arguments. + * This package contains the classes that represent arguments of Redis commands. */ package redis.clients.jedis.args; diff --git a/src/main/java/redis/clients/jedis/commands/AccessControlLogBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/AccessControlLogBinaryCommands.java new file mode 100644 index 0000000000..cbc024b02a --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/AccessControlLogBinaryCommands.java @@ -0,0 +1,154 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.resps.AccessControlUser; + +/** + * This class provides the interfaces necessary to interact with + * Access Control Lists (ACLs) within redis. These are the interfaces + * for binary (i.e. non-decoded) interactions. + * + * @see Redis ACL Guide + */ +public interface AccessControlLogBinaryCommands { + + /** + * Returns the username used to authenticate the current connection. + * + * @see ACL WHOAMI + * @return The username used for the current connection + */ + byte[] aclWhoAmIBinary(); + + /** + * Generate a random password + * + * @see ACL GENPASS + * @return A random password + */ + byte[] aclGenPassBinary(); + + /** + * Generate a random password + * + * @param bits the number of output bits + * @return A random password + */ + byte[] aclGenPassBinary(int bits); + + /** + * Returns the currently active ACL rules on the Redis Server + * + * @see ACL LIST + * @return An array of ACL rules + */ + List aclListBinary(); + + /** + * Shows a list of all usernames currently configured with access control + * lists (ACL). + * + * @see ACL USERS + * @return list of users + */ + List aclUsersBinary(); + + AccessControlUser aclGetUser(byte[] name); + + /** + * Create an ACL for the specified user with the default rules. + * + * @param name user who receives an acl + * @see ACL SETUSER + * @return A string containing OK on success + */ + String aclSetUser(byte[] name); + + /** + * Create an ACL for the specified user, while specifying the rules. + * + * @param name user who receives an acl + * @param keys the acl rules for the specified user + * @see ACL SETUSER + * @return A string containing OK on success + */ + String aclSetUser(byte[] name, byte[]... keys); + + /** + * Delete the specified user, from the ACL. + * + * @param name The username to delete + * @see ACL DELUSER + * @return The number of users delete + */ + long aclDelUser(byte[] name); + + /** + * Delete the specified users, from the ACL. + * + * @param name The username to delete + * @param names Other usernames to delete + * @see ACL DELUSER + * @return The number of users delete + */ + long aclDelUser(byte[] name, byte[]... names); + + /** + * Show the available ACL categories. + * + * @see ACL CAT + * @return the available ACL categories + */ + List aclCatBinary(); + + /** + * Show the available ACLs for a given category. + * + * @param category The category for which to list available ACLs + * @see ACL CAT + * @return the available ACL categories + */ + List aclCat(byte[] category); + + /** + * Shows the recent ACL security events. + * + * @see ACL LOG + * @return The list of recent security events + */ + List aclLogBinary(); + + /** + * Shows the recent limit ACL security events. + * + * @param limit The number of results to return + * @see ACL LOG + * @return The list of recent security events + */ + List aclLogBinary(int limit); + + /** + * Reset the script event log + * + * @see ACL LOG + * @return The OK string + */ + String aclLogReset(); + + /** + * This function tells Redis to reload its external ACL rules, + * when Redis is configured with an external ACL file + * + * @see ACL LOAD + * @return OK or error text + */ + String aclLoad(); + + /** + * Save the currently defined in-memory ACL to disk. + * + * @see ACL SAVE + * @return OK on success + */ + String aclSave(); +} diff --git a/src/main/java/redis/clients/jedis/commands/AccessControlLogCommands.java b/src/main/java/redis/clients/jedis/commands/AccessControlLogCommands.java new file mode 100644 index 0000000000..f8c653fac4 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/AccessControlLogCommands.java @@ -0,0 +1,156 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.resps.AccessControlLogEntry; +import redis.clients.jedis.resps.AccessControlUser; + +/** + * This class provides the interfaces necessary to interact with + * Access Control Lists (ACLs) within redis. These are the interfaces + * for string-based (i.e. decoded) interactions. + * + * + * @see Redis ACL Guide + */ + +public interface AccessControlLogCommands { + + /** + * Returns the username used to authenticate the current connection. + * + * @see ACL WHOAMI + * @return The username used for the current connection + */ + String aclWhoAmI(); + + /** + * Generate a random password + * + * @return A random password + */ + String aclGenPass(); + + /** + * Generate a random password + * + * @param bits the number of output bits + * @return A random password + */ + String aclGenPass(int bits); + + /** + * Returns the currently active ACL rules on the Redis Server + * + * @see ACL LIST + * @return An array of ACL rules + */ + List aclList(); + + /** + * Shows a list of all usernames currently configured with access control + * lists (ACL). + * + * @see ACL USERS + * @return list of users + */ + List aclUsers(); + + AccessControlUser aclGetUser(String name); + + /** + * Create an ACL for the specified user with the default rules. + * + * @param name user who receives an acl + * @see ACL SETUSER + * @return A string containing OK on success + */ + String aclSetUser(String name); + + /** + * Create an ACL for the specified user, while specifying the rules. + * + * @param name user who receives an acl + * @param keys the acl rules for the specified user + * @see ACL SETUSER + * @return A string containing OK on success + */ + String aclSetUser(String name, String... keys); + + /** + * Delete the specified user, from the ACL. + * + * @param name The username to delete + * @see ACL DELUSER + * @return The number of users delete + */ + long aclDelUser(String name); + + /** + * Delete the specified users, from the ACL. + * + * @param name The username to delete + * @param names Other usernames to delete + * @see ACL DELUSER + * @return The number of users delete + */ + long aclDelUser(String name, String... names); + + /** + * Show the available ACL categories. + * + * @see ACL CAT + * @return the available ACL categories + */ + List aclCat(); + + /** + * Show the available ACLs for a given category. + * + * @param category The category for which to list available ACLs + * @see ACL CAT + * @return the available ACL categories + */ + List aclCat(String category); + + /** + * Shows the recent ACL security events. + * + * @see ACL LOG + * @return The list of recent security events + */ + List aclLog(); + + /** + * Shows the recent limit ACL security events. + * + * @param limit The number of results to return + * @see ACL LOG + * @return The list of recent security events + */ + List aclLog(int limit); + + /** + * Reset the script event log + * + * @return The OK string + */ + String aclLogReset(); + + /** + * This function tells Redis to reload its external ACL rules, + * when Redis is configured with an external ACL file + * + * @see ACL LOAD + * @return OK or error text + */ + String aclLoad(); + + /** + * Save the currently defined in-memory ACL to disk. + * + * @see ACL SAVE + * @return OK on success + */ + String aclSave(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java b/src/main/java/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java deleted file mode 100644 index 3379a8a394..0000000000 --- a/src/main/java/redis/clients/jedis/commands/AdvancedBinaryJedisCommands.java +++ /dev/null @@ -1,121 +0,0 @@ -package redis.clients.jedis.commands; - -import java.util.List; - -import redis.clients.jedis.AccessControlUser; -import redis.clients.jedis.args.ClientPauseMode; -import redis.clients.jedis.args.ClientType; -import redis.clients.jedis.args.UnblockType; -import redis.clients.jedis.params.MigrateParams; -import redis.clients.jedis.params.ClientKillParams; -import redis.clients.jedis.params.FailoverParams; - -public interface AdvancedBinaryJedisCommands { - - List roleBinary(); - - long move(byte[] key, int dbIndex); - - List configGet(byte[] pattern); - - String configSet(byte[] parameter, byte[] value); - - /** - * @deprecated Use {@link #configSet(byte[], byte[])}. - */ - @Deprecated - default String configSetBinary(byte[] parameter, byte[] value) { - return configSet(parameter, value); - } - - String slowlogReset(); - - long slowlogLen(); - - List slowlogGetBinary(); - - List slowlogGetBinary(long entries); - - Long objectRefcount(byte[] key); - - byte[] objectEncoding(byte[] key); - - Long objectIdletime(byte[] key); - - List objectHelpBinary(); - - Long objectFreq(byte[] key); - - String migrate(String host, int port, byte[] key, int destinationDB, int timeout); - - String migrate(String host, int port, int destinationDB, int timeout, MigrateParams params, - byte[]... keys); - - String clientKill(byte[] ipPort); - - String clientKill(String ip, int port); - - long clientKill(ClientKillParams params); - - byte[] clientGetnameBinary(); - - byte[] clientListBinary(); - - byte[] clientListBinary(ClientType type); - - byte[] clientListBinary(long... clientIds); - - byte[] clientInfoBinary(); - - String clientSetname(byte[] name); - - long clientId(); - - long clientUnblock(long clientId, UnblockType unblockType); - - String clientPause(long timeout); - - String clientPause(long timeout, ClientPauseMode mode); - - byte[] memoryDoctorBinary(); - - Long memoryUsage(byte[] key); - - Long memoryUsage(byte[] key, int samples); - - String failover(); - - String failover(FailoverParams failoverParams); - - String failoverAbort(); - - byte[] aclWhoAmIBinary(); - - byte[] aclGenPassBinary(); - - List aclListBinary(); - - List aclUsersBinary(); - - AccessControlUser aclGetUser(byte[] name); - - String aclSetUser(byte[] name); - - String aclSetUser(byte[] name, byte[]... keys); - - long aclDelUser(byte[] name); - - List aclCatBinary(); - - List aclCat(byte[] category); - - List aclLogBinary(); - - List aclLogBinary(int limit); - - byte[] aclLog(byte[] options); - - String aclLoad(); - - String aclSave(); -} diff --git a/src/main/java/redis/clients/jedis/commands/AdvancedJedisCommands.java b/src/main/java/redis/clients/jedis/commands/AdvancedJedisCommands.java deleted file mode 100644 index 8a8a59571f..0000000000 --- a/src/main/java/redis/clients/jedis/commands/AdvancedJedisCommands.java +++ /dev/null @@ -1,115 +0,0 @@ -package redis.clients.jedis.commands; - -import java.util.List; - -import redis.clients.jedis.AccessControlLogEntry; -import redis.clients.jedis.AccessControlUser; -import redis.clients.jedis.args.ClientPauseMode; -import redis.clients.jedis.args.ClientType; -import redis.clients.jedis.args.UnblockType; -import redis.clients.jedis.params.MigrateParams; -import redis.clients.jedis.params.ClientKillParams; -import redis.clients.jedis.params.FailoverParams; -import redis.clients.jedis.util.Slowlog; - -public interface AdvancedJedisCommands { - - List role(); - - long move(String key, int dbIndex); - - List configGet(String pattern); - - String configSet(String parameter, String value); - - String slowlogReset(); - - long slowlogLen(); - - List slowlogGet(); - - List slowlogGet(long entries); - - Long objectRefcount(String key); - - String objectEncoding(String key); - - Long objectIdletime(String key); - - List objectHelp(); - - Long objectFreq(String key); - - String migrate(String host, int port, String key, int destinationDB, int timeout); - - String migrate(String host, int port, int destinationDB, int timeout, MigrateParams params, - String... keys); - - String clientKill(String ipPort); - - String clientKill(String ip, int port); - - long clientKill(ClientKillParams params); - - String clientGetname(); - - String clientList(); - - String clientList(ClientType type); - - String clientList(long... clientIds); - - String clientInfo(); - - String clientSetname(String name); - - long clientId(); - - long clientUnblock(long clientId, UnblockType unblockType); - - String clientPause(long timeout); - - String clientPause(long timeout, ClientPauseMode mode); - - String memoryDoctor(); - - Long memoryUsage(String key); - - Long memoryUsage(String key, int samples); - - String failover(); - - String failover(FailoverParams failoverParams); - - String failoverAbort(); - - String aclWhoAmI(); - - String aclGenPass(); - - List aclList(); - - List aclUsers(); - - AccessControlUser aclGetUser(String name); - - String aclSetUser(String name); - - String aclSetUser(String name, String... keys); - - long aclDelUser(String name); - - List aclCat(); - - List aclCat(String category); - - List aclLog(); - - List aclLog(int limit); - - String aclLog(String options); - - String aclLoad(); - - String aclSave(); -} diff --git a/src/main/java/redis/clients/jedis/commands/BasicRedisPipeline.java b/src/main/java/redis/clients/jedis/commands/BasicRedisPipeline.java deleted file mode 100644 index ea397949fd..0000000000 --- a/src/main/java/redis/clients/jedis/commands/BasicRedisPipeline.java +++ /dev/null @@ -1,58 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.Module; -import redis.clients.jedis.Response; -import redis.clients.jedis.args.FlushMode; - -import java.util.List; - -/** - * Pipelined responses for all of the low level, non key related commands - */ -public interface BasicRedisPipeline { - - Response bgrewriteaof(); - - Response bgsave(); - - Response> configGet(String pattern); - - Response configSet(String parameter, String value); - - Response configResetStat(); - - Response save(); - - Response lastsave(); - - Response flushDB(); - - Response flushDB(FlushMode flushMode); - - Response flushAll(); - - Response flushAll(FlushMode flushMode); - - Response info(); - - Response> time(); - - Response dbSize(); - - Response shutdown(); - - Response ping(); - - Response select(int index); - - Response swapDB(int index1, int index2); - - Response migrate(String host, int port, String key, int destinationDB, int timeout); - - Response moduleLoad(String path); - - Response> moduleList(); - - Response moduleUnload(String name); - -} diff --git a/src/main/java/redis/clients/jedis/commands/BinaryJedisClusterCommands.java b/src/main/java/redis/clients/jedis/commands/BinaryJedisClusterCommands.java deleted file mode 100644 index bb1f1eedfa..0000000000 --- a/src/main/java/redis/clients/jedis/commands/BinaryJedisClusterCommands.java +++ /dev/null @@ -1,49 +0,0 @@ -package redis.clients.jedis.commands; - -import java.util.List; - -import redis.clients.jedis.StreamConsumersInfo; -import redis.clients.jedis.StreamGroupInfo; -import redis.clients.jedis.StreamInfo; -import redis.clients.jedis.params.RestoreParams; - -public interface BinaryJedisClusterCommands extends BinaryJedisCommands { - - /** - * @deprecated Use {@link BinaryJedisCommands#restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - @Override - default String restoreReplace(byte[] key, long ttl, byte[] serializedValue) { - return restore(key, ttl, serializedValue, RestoreParams.restoreParams().replace()); - } - - /** - * @deprecated Use {@link BinaryJedisCommands#xinfoStreamBinary(byte[])}. - */ - @Override - @Deprecated - default StreamInfo xinfoStream(byte[] key) { - throw new UnsupportedOperationException("Use other version of XINFO STREAM."); - } - - /** - * @deprecated Use {@link BinaryJedisCommands#xinfoGroupBinary(byte[])}. - */ - @Override - @Deprecated - default List xinfoGroup(byte[] key) { - throw new UnsupportedOperationException("Use other version of XINFO GROUPS."); - } - - /** - * @deprecated Use {@link BinaryJedisCommands#xinfoConsumersBinary(byte[], byte[])}. - */ - @Override - @Deprecated - default List xinfoConsumers(byte[] key, byte[] group) { - throw new UnsupportedOperationException("Use other version of XINFO CONSUMERS."); - } - - long waitReplicas(byte[] key, int replicas, long timeout); -} diff --git a/src/main/java/redis/clients/jedis/commands/BinaryJedisCommands.java b/src/main/java/redis/clients/jedis/commands/BinaryJedisCommands.java deleted file mode 100644 index 82ad7fea28..0000000000 --- a/src/main/java/redis/clients/jedis/commands/BinaryJedisCommands.java +++ /dev/null @@ -1,495 +0,0 @@ -package redis.clients.jedis.commands; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import redis.clients.jedis.*; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.LCSMatchResult; - -/** - * Common interface for sharded and non-sharded BinaryJedis - */ -public interface BinaryJedisCommands { - String set(byte[] key, byte[] value); - - String set(byte[] key, byte[] value, SetParams params); - - byte[] get(byte[] key); - - byte[] getDel(byte[] key); - - byte[] getEx(byte[] key, GetExParams params); - - boolean exists(byte[] key); - - long persist(byte[] key); - - String type(byte[] key); - - byte[] dump(byte[] key); - - /** - * @deprecated Use {@link #restore(byte[], long, byte[])}. - */ - @Deprecated - default String restore(byte[] key, int ttl, byte[] serializedValue) { - return restore(key, (long) ttl, serializedValue); - } - - String restore(byte[] key, long ttl, byte[] serializedValue); - - /** - * @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - default String restoreReplace(byte[] key, int ttl, byte[] serializedValue) { - return restoreReplace(key, (long) ttl, serializedValue); - } - - /** - * @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - String restoreReplace(byte[] key, long ttl, byte[] serializedValue); - - String restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params); - - /** - * @deprecated Use {@link #expire(byte[], long)}. - */ - @Deprecated - default Long expire(byte[] key, int seconds) { - return expire(key, (long) seconds); - } - - long expire(byte[] key, long seconds); - - long pexpire(byte[] key, long milliseconds); - - long expireAt(byte[] key, long unixTime); - - long pexpireAt(byte[] key, long millisecondsTimestamp); - - long ttl(byte[] key); - - long pttl(byte[] key); - - long touch(byte[] key); - - boolean setbit(byte[] key, long offset, boolean value); - - /** - * @deprecated Use {@link #setbit(byte[], long, boolean)}. - */ - @Deprecated - Boolean setbit(byte[] key, long offset, byte[] value); - - boolean getbit(byte[] key, long offset); - - long setrange(byte[] key, long offset, byte[] value); - - byte[] getrange(byte[] key, long startOffset, long endOffset); - - byte[] getSet(byte[] key, byte[] value); - - long setnx(byte[] key, byte[] value); - - /** - * @deprecated Use {@link #setex(byte[], long, byte[])}. - */ - @Deprecated - default String setex(byte[] key, int seconds, byte[] value) { - return setex(key, (long) seconds, value); - } - - String setex(byte[] key, long seconds, byte[] value); - - String psetex(byte[] key, long milliseconds, byte[] value); - - long decrBy(byte[] key, long decrement); - - long decr(byte[] key); - - long incrBy(byte[] key, long increment); - - double incrByFloat(byte[] key, double increment); - - long incr(byte[] key); - - long append(byte[] key, byte[] value); - - byte[] substr(byte[] key, int start, int end); - - long hset(byte[] key, byte[] field, byte[] value); - - long hset(byte[] key, Map hash); - - byte[] hget(byte[] key, byte[] field); - - long hsetnx(byte[] key, byte[] field, byte[] value); - - String hmset(byte[] key, Map hash); - - List hmget(byte[] key, byte[]... fields); - - long hincrBy(byte[] key, byte[] field, long value); - - double hincrByFloat(byte[] key, byte[] field, double value); - - boolean hexists(byte[] key, byte[] field); - - long hdel(byte[] key, byte[]... field); - - long hlen(byte[] key); - - Set hkeys(byte[] key); - - List hvals(byte[] key); - - Map hgetAll(byte[] key); - - byte[] hrandfield(byte[] key); - - List hrandfield(byte[] key, long count); - - Map hrandfieldWithValues(byte[] key, long count); - - long rpush(byte[] key, byte[]... args); - - long lpush(byte[] key, byte[]... args); - - long llen(byte[] key); - - List lrange(byte[] key, long start, long stop); - - String ltrim(byte[] key, long start, long stop); - - byte[] lindex(byte[] key, long index); - - String lset(byte[] key, long index, byte[] value); - - long lrem(byte[] key, long count, byte[] value); - - byte[] lpop(byte[] key); - - List lpop(byte[] key, int count); - - Long lpos(byte[] key, byte[] element); - - Long lpos(byte[] key, byte[] element, LPosParams params); - - List lpos(byte[] key, byte[] element, LPosParams params, long count); - - byte[] rpop(byte[] key); - - List rpop(byte[] key, int count); - - long sadd(byte[] key, byte[]... member); - - Set smembers(byte[] key); - - long srem(byte[] key, byte[]... member); - - byte[] spop(byte[] key); - - Set spop(byte[] key, long count); - - long scard(byte[] key); - - boolean sismember(byte[] key, byte[] member); - - List smismember(byte[] key, byte[]... members); - - byte[] srandmember(byte[] key); - - List srandmember(byte[] key, int count); - - long strlen(byte[] key); - - long zadd(byte[] key, double score, byte[] member); - - long zadd(byte[] key, double score, byte[] member, ZAddParams params); - - long zadd(byte[] key, Map scoreMembers); - - long zadd(byte[] key, Map scoreMembers, ZAddParams params); - - Double zaddIncr(byte[] key, double score, byte[] member, ZAddParams params); - - Set zrange(byte[] key, long start, long stop); - - long zrem(byte[] key, byte[]... members); - - double zincrby(byte[] key, double increment, byte[] member); - - Double zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params); - - Long zrank(byte[] key, byte[] member); - - Long zrevrank(byte[] key, byte[] member); - - Set zrevrange(byte[] key, long start, long stop); - - Set zrangeWithScores(byte[] key, long start, long stop); - - Set zrevrangeWithScores(byte[] key, long start, long stop); - - byte[] zrandmember(byte[] key); - - Set zrandmember(byte[] key, long count); - - Set zrandmemberWithScores(byte[] key, long count); - - long zcard(byte[] key); - - Double zscore(byte[] key, byte[] member); - - List zmscore(byte[] key, byte[]... members); - - Tuple zpopmax(byte[] key); - - Set zpopmax(byte[] key, int count); - - Tuple zpopmin(byte[] key); - - Set zpopmin(byte[] key, int count); - - List sort(byte[] key); - - List sort(byte[] key, SortingParams sortingParameters); - - long zcount(byte[] key, double min, double max); - - long zcount(byte[] key, byte[] min, byte[] max); - - Set zrangeByScore(byte[] key, double min, double max); - - Set zrangeByScore(byte[] key, byte[] min, byte[] max); - - Set zrevrangeByScore(byte[] key, double max, double min); - - Set zrangeByScore(byte[] key, double min, double max, int offset, int count); - - Set zrevrangeByScore(byte[] key, byte[] max, byte[] min); - - Set zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count); - - Set zrevrangeByScore(byte[] key, double max, double min, int offset, int count); - - Set zrangeByScoreWithScores(byte[] key, double min, double max); - - Set zrevrangeByScoreWithScores(byte[] key, double max, double min); - - Set zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count); - - Set zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count); - - Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); - - Set zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); - - Set zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count); - - Set zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count); - - Set zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count); - - long zremrangeByRank(byte[] key, long start, long stop); - - long zremrangeByScore(byte[] key, double min, double max); - - long zremrangeByScore(byte[] key, byte[] min, byte[] max); - - long zlexcount(byte[] key, byte[] min, byte[] max); - - Set zrangeByLex(byte[] key, byte[] min, byte[] max); - - Set zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count); - - Set zrevrangeByLex(byte[] key, byte[] max, byte[] min); - - Set zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count); - - long zremrangeByLex(byte[] key, byte[] min, byte[] max); - - long linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value); - - long lpushx(byte[] key, byte[]... arg); - - long rpushx(byte[] key, byte[]... arg); - - long del(byte[] key); - - long unlink(byte[] key); - - byte[] echo(byte[] arg); - - long bitcount(byte[] key); - - long bitcount(byte[] key, long start, long end); - - long pfadd(byte[] key, byte[]... elements); - - long pfcount(byte[] key); - - // Geo Commands - - long geoadd(byte[] key, double longitude, double latitude, byte[] member); - - long geoadd(byte[] key, Map memberCoordinateMap); - - long geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap); - - Double geodist(byte[] key, byte[] member1, byte[] member2); - - Double geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit); - - List geohash(byte[] key, byte[]... members); - - List geopos(byte[] key, byte[]... members); - - List georadius(byte[] key, double longitude, double latitude, double radius, - GeoUnit unit); - - List georadiusReadonly(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit); - - List georadius(byte[] key, double longitude, double latitude, double radius, - GeoUnit unit, GeoRadiusParam param); - - List georadiusReadonly(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); - - List georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit); - - List georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit); - - List georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, - GeoRadiusParam param); - - List georadiusByMemberReadonly(byte[] key, byte[] member, double radius, - GeoUnit unit, GeoRadiusParam param); - - default ScanResult> hscan(byte[] key, byte[] cursor) { - return hscan(key, cursor, new ScanParams()); - } - - ScanResult> hscan(byte[] key, byte[] cursor, ScanParams params); - - default ScanResult sscan(byte[] key, byte[] cursor) { - return sscan(key, cursor, new ScanParams()); - } - - ScanResult sscan(byte[] key, byte[] cursor, ScanParams params); - - default ScanResult zscan(byte[] key, byte[] cursor) { - return zscan(key, cursor, new ScanParams()); - } - - ScanResult zscan(byte[] key, byte[] cursor, ScanParams params); - - /** - * Executes BITFIELD Redis command - * @param key - * @param arguments - */ - List bitfield(byte[] key, byte[]... arguments); - - List bitfieldReadonly(byte[] key, byte[]... arguments); - - /** - * Used for HSTRLEN Redis command - * @param key - * @param field - * @return lenth of the value for key - */ - long hstrlen(byte[] key, byte[] field); - - byte[] xadd(byte[] key, byte[] id, Map hash, long maxLen, boolean approximateLength); - - byte[] xadd(byte[] key, Map hash, XAddParams params); - - long xlen(byte[] key); - - List xrange(byte[] key, byte[] start, byte[] end); - - /** - * @deprecated Use {@link #xrange(byte[], byte[], byte[], int)}. - */ - @Deprecated - default List xrange(byte[] key, byte[] start, byte[] end, long count) { - return xrange(key, start, end, (int) Math.min(count, (long) Integer.MAX_VALUE)); - } - - List xrange(byte[] key, byte[] start, byte[] end, int count); - - List xrevrange(byte[] key, byte[] end, byte[] start); - - List xrevrange(byte[] key, byte[] end, byte[] start, int count); - - long xack(byte[] key, byte[] group, byte[]... ids); - - String xgroupCreate(byte[] key, byte[] consumer, byte[] id, boolean makeStream); - - String xgroupSetID(byte[] key, byte[] consumer, byte[] id); - - long xgroupDestroy(byte[] key, byte[] consumer); - - long xgroupDelConsumer(byte[] key, byte[] consumer, byte[] consumerName); - - long xdel(byte[] key, byte[]... ids); - - long xtrim(byte[] key, long maxLen, boolean approximateLength); - - long xtrim(byte[] key, XTrimParams params); - - Object xpending(byte[] key, byte[] groupname); - - List xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername); - - List xpending(byte[] key, byte[] groupname, XPendingParams params); - - List xclaim(byte[] key, byte[] groupname, byte[] consumername, long minIdleTime, long newIdleTime, int retries, boolean force, byte[]... ids); - - List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids); - - List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids); - - List xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params); - - List xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params); - - /** - * @deprecated Use {@link #xinfoStreamBinary(byte[])}. - */ - @Deprecated - StreamInfo xinfoStream(byte[] key); - - Object xinfoStreamBinary(byte[] key); - - /** - * @deprecated Use {@link #xinfoGroupBinary(byte[])}. - */ - @Deprecated - List xinfoGroup(byte[] key); - - List xinfoGroupBinary(byte[] key); - - /** - * @deprecated Use {@link #xinfoConsumersBinary(byte[], byte[])}. - */ - @Deprecated - List xinfoConsumers(byte[] key, byte[] group); - - List xinfoConsumersBinary(byte[] key, byte[] group); - - Long memoryUsage(byte[] key); - - Long memoryUsage(byte[] key, int samples); - - LCSMatchResult strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/BinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/commands/BinaryRedisPipeline.java deleted file mode 100644 index 0b23be76e1..0000000000 --- a/src/main/java/redis/clients/jedis/commands/BinaryRedisPipeline.java +++ /dev/null @@ -1,456 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.*; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.LCSMatchResult; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -public interface BinaryRedisPipeline { - Response append(byte[] key, byte[] value); - - Response> blpop(byte[] arg); - - Response> brpop(byte[] arg); - - Response decr(byte[] key); - - Response decrBy(byte[] key, long decrement); - - Response del(byte[] keys); - - Response unlink(byte[] keys); - - Response echo(byte[] string); - - Response exists(byte[] key); - - /** - * @deprecated Use {@link #expire(byte[], long)}. - */ - @Deprecated - default Response expire(byte[] key, int seconds) { - return expire(key, (long) seconds); - } - - Response expire(byte[] key, long seconds); - - Response pexpire(byte[] key, long milliseconds); - - Response expireAt(byte[] key, long unixTime); - - Response pexpireAt(byte[] key, long millisecondsTimestamp); - - Response get(byte[] key); - - Response getDel(byte[] key); - - Response getEx(byte[] key, GetExParams params); - - Response getbit(byte[] key, long offset); - - Response getSet(byte[] key, byte[] value); - - Response getrange(byte[] key, long startOffset, long endOffset); - - Response hdel(byte[] key, byte[]... field); - - Response hexists(byte[] key, byte[] field); - - Response hget(byte[] key, byte[] field); - - Response> hgetAll(byte[] key); - - Response hincrBy(byte[] key, byte[] field, long value); - - Response> hkeys(byte[] key); - - Response hlen(byte[] key); - - Response> hmget(byte[] key, byte[]... fields); - - Response hmset(byte[] key, Map hash); - - Response hset(byte[] key, byte[] field, byte[] value); - - Response hset(byte[] key, Map hash); - - Response hsetnx(byte[] key, byte[] field, byte[] value); - - Response> hvals(byte[] key); - - Response hrandfield(byte[] key); - - Response> hrandfield(byte[] key, long count); - - Response> hrandfieldWithValues(byte[] key, long count); - - Response incr(byte[] key); - - Response incrBy(byte[] key, long increment); - - Response lindex(byte[] key, long index); - - Response linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value); - - Response llen(byte[] key); - - Response lpop(byte[] key); - - Response> lpop(byte[] key, int count); - - Response lpos(byte[] key, byte[] element); - - Response lpos(byte[] key, byte[] element, LPosParams params); - - Response> lpos(byte[] key, byte[] element, LPosParams params, long count); - - Response lpush(byte[] key, byte[]... string); - - Response lpushx(byte[] key, byte[]... bytes); - - Response> lrange(byte[] key, long start, long stop); - - Response lrem(byte[] key, long count, byte[] value); - - Response lset(byte[] key, long index, byte[] value); - - Response ltrim(byte[] key, long start, long stop); - - Response move(byte[] key, int dbIndex); - - Response persist(byte[] key); - - Response rpop(byte[] key); - - Response> rpop(byte[] key, int count); - - Response rpush(byte[] key, byte[]... string); - - Response rpushx(byte[] key, byte[]... string); - - Response sadd(byte[] key, byte[]... member); - - Response scard(byte[] key); - - Response set(byte[] key, byte[] value); - - Response setbit(byte[] key, long offset, byte[] value); - - Response setrange(byte[] key, long offset, byte[] value); - - /** - * @deprecated Use {@link #setex(byte[], long, byte[])}. - */ - @Deprecated - default Response setex(byte[] key, int seconds, byte[] value) { - return setex(key, (long) seconds, value); - } - - Response setex(byte[] key, long seconds, byte[] value); - - Response setnx(byte[] key, byte[] value); - - Response setrange(String key, long offset, String value); - - Response> smembers(byte[] key); - - Response sismember(byte[] key, byte[] member); - - Response> smismember(byte[] key, byte[]... members); - - Response> sort(byte[] key); - - Response> sort(byte[] key, SortingParams sortingParameters); - - Response spop(byte[] key); - - Response> spop(byte[] key, long count); - - Response srandmember(byte[] key); - - Response srem(byte[] key, byte[]... member); - - Response strlen(byte[] key); - - Response substr(byte[] key, int start, int end); - - Response touch(byte[] keys); - - Response ttl(byte[] key); - - Response pttl(byte[] key); - - Response type(byte[] key); - - Response zadd(byte[] key, double score, byte[] member); - - Response zadd(byte[] key, double score, byte[] member, ZAddParams params); - - Response zadd(byte[] key, Map scoreMembers); - - Response zadd(byte[] key, Map scoreMembers, ZAddParams params); - - Response zaddIncr(byte[] key, double score, byte[] member, ZAddParams params); - - Response zcard(byte[] key); - - Response zcount(byte[] key, double min, double max); - - Response zcount(byte[] key, byte[] min, byte[] max); - - Response zincrby(byte[] key, double increment, byte[] member); - - Response zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params); - - Response> zrange(byte[] key, long start, long stop); - - Response> zrangeByScore(byte[] key, double min, double max); - - Response> zrangeByScore(byte[] key, byte[] min, byte[] max); - - Response> zrangeByScore(byte[] key, double min, double max, int offset, int count); - - Response> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count); - - Response> zrangeByScoreWithScores(byte[] key, double min, double max); - - Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); - - Response> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count); - - Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count); - - Response> zrevrangeByScore(byte[] key, double max, double min); - - Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min); - - Response> zrevrangeByScore(byte[] key, double max, double min, int offset, int count); - - Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count); - - Response> zrevrangeByScoreWithScores(byte[] key, double max, double min); - - Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); - - Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count); - - Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count); - - Response> zrangeWithScores(byte[] key, long start, long stop); - - Response zrank(byte[] key, byte[] member); - - Response zrem(byte[] key, byte[]... members); - - Response zremrangeByRank(byte[] key, long start, long stop); - - Response zremrangeByScore(byte[] key, double min, double max); - - Response zremrangeByScore(byte[] key, byte[] min, byte[] max); - - Response> zrevrange(byte[] key, long start, long stop); - - Response> zrevrangeWithScores(byte[] key, long start, long stop); - - Response zrandmember(byte[] key); - - Response> zrandmember(byte[] key, long count); - - Response> zrandmemberWithScores(byte[] key, long count); - - Response zrevrank(byte[] key, byte[] member); - - Response zscore(byte[] key, byte[] member); - - Response> zmscore(byte[] key, byte[]... members); - - Response zpopmax(byte[] key); - - Response> zpopmax(byte[] key, int count); - - Response zpopmin(byte[] key); - - Response> zpopmin(byte[] key, int count); - - Response zlexcount(byte[] key, byte[] min, byte[] max); - - Response> zrangeByLex(byte[] key, byte[] min, byte[] max); - - Response> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count); - - Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min); - - Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count); - - Response zremrangeByLex(byte[] key, byte[] min, byte[] max); - - Response bitcount(byte[] key); - - Response bitcount(byte[] key, long start, long end); - - Response pfadd(byte[] key, byte[]... elements); - - Response pfcount(byte[] key); - - Response dump(byte[] key); - - /** - * @deprecated Use {@link #restore(byte[], long, byte[])}. - */ - @Deprecated - default Response restore(byte[] key, int ttl, byte[] serializedValue) { - return restore(key, (long) ttl, serializedValue); - } - - Response restore(byte[] key, long ttl, byte[] serializedValue); - - /** - * @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - default Response restoreReplace(byte[] key, int ttl, byte[] serializedValue) { - return restoreReplace(key, (long) ttl, serializedValue); - } - - /** - * @deprecated Use {@link #restore(byte[], long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - Response restoreReplace(byte[] key, long ttl, byte[] serializedValue); - - Response restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params); - - Response migrate(String host, int port, byte[] key, int destinationDB, int timeout); - - // Geo Commands - - Response geoadd(byte[] key, double longitude, double latitude, byte[] member); - - Response geoadd(byte[] key, Map memberCoordinateMap); - - Response geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap); - - Response geodist(byte[] key, byte[] member1, byte[] member2); - - Response geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit); - - Response> geohash(byte[] key, byte[]... members); - - Response> geopos(byte[] key, byte[]... members); - - Response> georadius(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit); - - Response> georadiusReadonly(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit); - - Response> georadius(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); - - Response> georadiusReadonly(byte[] key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); - - Response> georadiusByMember(byte[] key, byte[] member, double radius, - GeoUnit unit); - - Response> georadiusByMemberReadonly(byte[] key, byte[] member, - double radius, GeoUnit unit); - - Response> georadiusByMember(byte[] key, byte[] member, double radius, - GeoUnit unit, GeoRadiusParam param); - - Response> georadiusByMemberReadonly(byte[] key, byte[] member, - double radius, GeoUnit unit, GeoRadiusParam param); - - Response> bitfield(byte[] key, byte[]... elements); - - Response> bitfieldReadonly(byte[] key, byte[]... elements); - - Response hstrlen(byte[] key, byte[] field); - - Response xadd(byte[] key, byte[] id, Map hash); - - Response xadd(byte[] key, byte[] id, Map hash, long maxLen, boolean approximateLength); - - Response xadd(byte[] key, Map hash, XAddParams params); - - Response xlen(byte[] key); - - Response> xrange(byte[] key, byte[] start, byte[] end); - - Response> xrange(byte[] key, byte[] start, byte[] end, int count); - - Response> xrevrange(byte[] key, byte[] end, byte[] start); - - Response> xrevrange(byte[] key, byte[] end, byte[] start, int count); - - Response xack(byte[] key, byte[] group, byte[]... ids); - - Response xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream); - - Response xgroupSetID(byte[] key, byte[] groupname, byte[] id); - - Response xgroupDestroy(byte[] key, byte[] groupname); - - Response xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumername); - - Response xpending(byte[] key, byte[] groupname); - - /** - * @deprecated Use {@link #xpendingBinary(byte[], byte[], byte[], byte[], int, byte[])}. - */ - @Deprecated - Response> xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername); - - Response> xpendingBinary(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername); - - Response> xpending(byte[] key, byte[] groupname, XPendingParams params); - - Response xdel(byte[] key, byte[]... ids); - - Response xtrim(byte[] key, long maxLen, boolean approximateLength); - - Response xtrim(byte[] key, XTrimParams params); - - Response> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, byte[]... ids); - - Response> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, - XClaimParams params, byte[]... ids); - - Response> xclaimJustId(byte[] key, byte[] group, byte[] consumername, - long minIdleTime, XClaimParams params, byte[]... ids); - - Response> xautoclaim(byte[] key, byte[] group, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params); - - Response> xautoclaimJustId(byte[] key, byte[] group, byte[] consumerName, - long minIdleTime, byte[] start, XAutoClaimParams params); - - Response bitpos(byte[] key, boolean value); - - Response bitpos(byte[] key, boolean value, BitPosParams params); - - Response set(byte[] key, byte[] value, SetParams params); - - Response> srandmember(byte[] key, int count); - - Response objectRefcount(byte[] key); - - Response objectEncoding(byte[] key); - - Response objectIdletime(byte[] key); - - Response objectFreq(byte[] key); - - Response incrByFloat(byte[] key, double increment); - - Response psetex(byte[] key, long milliseconds, byte[] value); - - Response hincrByFloat(byte[] key, byte[] field, double increment); - - Response strAlgoLCSStrings(final byte[] strA, final byte[] strB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommands.java b/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommands.java deleted file mode 100644 index e81c7a43e7..0000000000 --- a/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommands.java +++ /dev/null @@ -1,37 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.args.FlushMode; - -import java.util.List; - -public interface BinaryScriptingCommands { - - /** - * @deprecated Use {@link #eval(byte..., int, byte[]...)}. - */ - @Deprecated - Object eval(byte[] script, byte[] keyCount, byte[]... params); - - Object eval(byte[] script, int keyCount, byte[]... params); - - Object eval(byte[] script, List keys, List args); - - Object eval(byte[] script); - - Object evalsha(byte[] sha1); - - Object evalsha(byte[] sha1, List keys, List args); - - Object evalsha(byte[] sha1, int keyCount, byte[]... params); - - // TODO: should be Boolean, add singular version - List scriptExists(byte[]... sha1); - - byte[] scriptLoad(byte[] script); - - String scriptFlush(); - - String scriptFlush(FlushMode flushMode); - - String scriptKill(); -} diff --git a/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommandsPipeline.java b/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommandsPipeline.java index c9788f01bf..59c9e746e3 100644 --- a/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommandsPipeline.java +++ b/src/main/java/redis/clients/jedis/commands/BinaryScriptingCommandsPipeline.java @@ -1,17 +1,10 @@ package redis.clients.jedis.commands; -import redis.clients.jedis.Response; - import java.util.List; +import redis.clients.jedis.Response; public interface BinaryScriptingCommandsPipeline { - /** - * @deprecated Use {@link #eval(byte..., int, byte[]...)}. - */ - @Deprecated - Response eval(byte[] script, byte[] keyCount, byte[]... params); - Response eval(byte[] script, int keyCount, byte[]... params); Response eval(byte[] script, List keys, List args); diff --git a/src/main/java/redis/clients/jedis/commands/ClientBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/ClientBinaryCommands.java new file mode 100644 index 0000000000..2aa82bca2d --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ClientBinaryCommands.java @@ -0,0 +1,38 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.args.ClientPauseMode; +import redis.clients.jedis.args.ClientType; +import redis.clients.jedis.args.UnblockType; +import redis.clients.jedis.params.ClientKillParams; + +public interface ClientBinaryCommands { + + String clientKill(byte[] ipPort); + + String clientKill(String ip, int port); + + long clientKill(ClientKillParams params); + + byte[] clientGetnameBinary(); + + byte[] clientListBinary(); + + byte[] clientListBinary(ClientType type); + + byte[] clientListBinary(long... clientIds); + + byte[] clientInfoBinary(); + + String clientSetname(byte[] name); + + long clientId(); + + long clientUnblock(long clientId); + + long clientUnblock(long clientId, UnblockType unblockType); + + String clientPause(long timeout); + + String clientPause(long timeout, ClientPauseMode mode); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ClientCommands.java b/src/main/java/redis/clients/jedis/commands/ClientCommands.java new file mode 100644 index 0000000000..c88013d841 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ClientCommands.java @@ -0,0 +1,38 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.args.ClientPauseMode; +import redis.clients.jedis.args.ClientType; +import redis.clients.jedis.args.UnblockType; +import redis.clients.jedis.params.ClientKillParams; + +public interface ClientCommands { + + String clientKill(String ipPort); + + String clientKill(String ip, int port); + + long clientKill(ClientKillParams params); + + String clientGetname(); + + String clientList(); + + String clientList(ClientType type); + + String clientList(long... clientIds); + + String clientInfo(); + + String clientSetname(String name); + + long clientId(); + + long clientUnblock(long clientId); + + long clientUnblock(long clientId, UnblockType unblockType); + + String clientPause(long timeout); + + String clientPause(long timeout, ClientPauseMode mode); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ClusterCommands.java b/src/main/java/redis/clients/jedis/commands/ClusterCommands.java index 5dfd1beda7..31e5e2ee81 100644 --- a/src/main/java/redis/clients/jedis/commands/ClusterCommands.java +++ b/src/main/java/redis/clients/jedis/commands/ClusterCommands.java @@ -1,13 +1,13 @@ package redis.clients.jedis.commands; import java.util.List; - -import redis.clients.jedis.ClusterReset; import redis.clients.jedis.args.ClusterResetType; import redis.clients.jedis.args.ClusterFailoverOption; public interface ClusterCommands { + String asking(); + String readonly(); String readwrite(); @@ -55,19 +55,13 @@ public interface ClusterCommands { @Deprecated List clusterSlaves(String nodeId); - default String clusterFailover() { - return clusterFailover(null); - } + String clusterFailover(); String clusterFailover(ClusterFailoverOption failoverOption); List clusterSlots(); - /** - * @deprecated Use {@link ClusterCommands#clusterReset(redis.clients.jedis.args.ClusterResetType)}. - */ - @Deprecated - String clusterReset(ClusterReset resetType); + String clusterReset(); /** * {@code resetType} can be null for default behavior. diff --git a/src/main/java/redis/clients/jedis/commands/ClusterPipeline.java b/src/main/java/redis/clients/jedis/commands/ClusterPipeline.java deleted file mode 100644 index 56bde103ec..0000000000 --- a/src/main/java/redis/clients/jedis/commands/ClusterPipeline.java +++ /dev/null @@ -1,25 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.Response; - -import java.util.List; - -public interface ClusterPipeline { - Response clusterNodes(); - - Response clusterMeet(String ip, int port); - - Response clusterAddSlots(int... slots); - - Response clusterDelSlots(int... slots); - - Response clusterInfo(); - - Response> clusterGetKeysInSlot(int slot, int count); - - Response clusterSetSlotNode(int slot, String nodeId); - - Response clusterSetSlotMigrating(int slot, String nodeId); - - Response clusterSetSlotImporting(int slot, String nodeId); -} diff --git a/src/main/java/redis/clients/jedis/commands/Commands.java b/src/main/java/redis/clients/jedis/commands/Commands.java deleted file mode 100644 index f643cc1690..0000000000 --- a/src/main/java/redis/clients/jedis/commands/Commands.java +++ /dev/null @@ -1,590 +0,0 @@ -package redis.clients.jedis.commands; - -import java.util.Map; -import java.util.Map.Entry; - -import redis.clients.jedis.BitOP; -import redis.clients.jedis.StreamEntryID; -import redis.clients.jedis.ListPosition; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.args.ListDirection; -import redis.clients.jedis.args.UnblockType; -import redis.clients.jedis.ZParams; -import redis.clients.jedis.args.ClientType; -import redis.clients.jedis.params.GetExParams; -import redis.clients.jedis.params.MigrateParams; -import redis.clients.jedis.params.ClientKillParams; -import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.params.SetParams; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.params.ZAddParams; -import redis.clients.jedis.params.ZIncrByParams; -import redis.clients.jedis.params.LPosParams; -import redis.clients.jedis.params.XReadGroupParams; -import redis.clients.jedis.params.XReadParams; - -public interface Commands { - - void copy(String srcKey, String dstKey, int db, boolean replace); - - void copy(String srcKey, String dstKey, boolean replace); - - void ping(String message); - - void set(String key, String value); - - void set(String key, String value, SetParams params); - - void get(String key); - - void getDel(String key); - - void getEx(String key, GetExParams params); - - void exists(String... keys); - - void del(String... keys); - - void unlink(String... keys); - - void type(String key); - - void keys(String pattern); - - void rename(String oldkey, String newkey); - - void renamenx(String oldkey, String newkey); - - /** - * @deprecated Use {@link #expire(java.lang.String, long)}. - */ - @Deprecated - default void expire(String key, int seconds) { - expire(key, (long) seconds); - } - - void expire(String key, long seconds); - - void expireAt(String key, long unixTime); - - void ttl(String key); - - void pttl(String key); - - void touch(String... keys); - - void setbit(String key, long offset, boolean value); - - void setbit(String key, long offset, String value); - - void getbit(String key, long offset); - - void setrange(String key, long offset, String value); - - void getrange(String key, long startOffset, long endOffset); - - void move(String key, int dbIndex); - - void getSet(String key, String value); - - void mget(String... keys); - - void setnx(String key, String value); - - /** - * @deprecated Use {@link #setex(java.lang.String, long, java.lang.String)}. - */ - @Deprecated - default void setex(String key, int seconds, String value) { - setex(key, (long) seconds, value); - } - - void setex(String key, long seconds, String value); - - void mset(String... keysvalues); - - void msetnx(String... keysvalues); - - void decrBy(String key, long decrement); - - void decr(String key); - - void incrBy(String key, long increment); - - void incrByFloat(String key, double increment); - - void incr(String key); - - void append(String key, String value); - - void substr(String key, int start, int end); - - void hset(String key, String field, String value); - - void hget(String key, String field); - - void hset(String key, Map hash); - - void hsetnx(String key, String field, String value); - - void hmset(String key, Map hash); - - void hmget(String key, String... fields); - - void hincrBy(String key, String field, long value); - - void hincrByFloat(String key, String field, double value); - - void hexists(String key, String field); - - void hdel(String key, String... fields); - - void hlen(String key); - - void hkeys(String key); - - void hvals(String key); - - void hrandfield(String key); - - void hrandfield(String key, long count); - - void hrandfieldWithValues(String key, long count); - - void hgetAll(String key); - - void rpush(String key, String... strings); - - void lpush(String key, String... strings); - - void llen(String key); - - void lrange(String key, long start, long stop); - - void ltrim(String key, long start, long stop); - - void lindex(String key, long index); - - void lset(String key, long index, String value); - - void lrem(String key, long count, String value); - - void lpop(String key); - - void lpop(String key, int count); - - void lpos(String key, String element); - - void lpos(String key, String element, LPosParams params); - - void lpos(String key, String element, LPosParams params, long count); - - void rpop(String key); - - void rpop(String key, int count); - - void rpoplpush(String srckey, String dstkey); - - void sadd(String key, String... members); - - void smembers(String key); - - void srem(String key, String... member); - - void spop(String key); - - void spop(String key, long count); - - void smove(String srckey, String dstkey, String member); - - void scard(String key); - - void sismember(String key, String member); - - void smismember(String key, String... members); - - void sinter(String... keys); - - void sinterstore(String dstkey, String... keys); - - void sunion(String... keys); - - void sunionstore(String dstkey, String... keys); - - void sdiff(String... keys); - - void sdiffstore(String dstkey, String... keys); - - void zdiff(String... keys); - - void zdiffWithScores(String... keys); - - void srandmember(String key); - - void zadd(String key, double score, String member); - - void zadd(String key, double score, String member, ZAddParams params); - - void zadd(String key, Map scoreMembers); - - void zadd(String key, Map scoreMembers, ZAddParams params); - - void zaddIncr(String key, double score, String member, ZAddParams params); - - void zdiffStore(String dstkey, String... keys); - - void zrange(String key, long start, long stop); - - void zrem(String key, String... members); - - void zincrby(String key, double increment, String member); - - void zincrby(String key, double increment, String member, ZIncrByParams params); - - void zrank(String key, String member); - - void zrevrank(String key, String member); - - void zrevrange(String key, long start, long stop); - - void zrangeWithScores(String key, long start, long stop); - - void zrevrangeWithScores(String key, long start, long stop); - - void zrandmember(String key); - - void zrandmember(String key, long count); - - void zrandmemberWithScores(String key, long count); - - void zcard(String key); - - void zscore(String key, String member); - - void zmscore(String key, String... members); - - void zpopmax(String key); - - void zpopmax(String key, int count); - - void zpopmin(String key); - - void zpopmin(String key, long count); - - void watch(String... keys); - - void sort(String key); - - void sort(String key, SortingParams sortingParameters); - - void sort(String key, SortingParams sortingParameters, String dstkey); - - void sort(String key, String dstkey); - - void lmove(String srcKey, String dstKey, ListDirection from, ListDirection to); - - void blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout); - - void blpop(String[] args); - - void blpop(int timeout, String... keys); - - void blpop(double timeout, String... keys); - - void brpop(String[] args); - - void brpop(int timeout, String... keys); - - void brpop(double timeout, String... keys); - - void brpoplpush(String source, String destination, int timeout); - - void bzpopmax(double timeout, String... keys); - - void bzpopmin(double timeout, String... keys); - - void zcount(String key, double min, double max); - - void zcount(String key, String min, String max); - - void zrangeByScore(String key, double min, double max); - - void zrangeByScore(String key, String min, String max); - - void zrangeByScore(String key, double min, double max, int offset, int count); - - void zrangeByScore(String key, String min, String max, int offset, int count); - - void zrangeByScoreWithScores(String key, double min, double max); - - void zrangeByScoreWithScores(String key, double min, double max, int offset, int count); - - void zrangeByScoreWithScores(String key, String min, String max); - - void zrangeByScoreWithScores(String key, String min, String max, int offset, int count); - - void zrevrangeByScore(String key, double max, double min); - - void zrevrangeByScore(String key, String max, String min); - - void zrevrangeByScore(String key, double max, double min, int offset, int count); - - void zrevrangeByScore(String key, String max, String min, int offset, int count); - - void zrevrangeByScoreWithScores(String key, double max, double min); - - void zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count); - - void zrevrangeByScoreWithScores(String key, String max, String min); - - void zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count); - - void zremrangeByRank(String key, long start, long stop); - - void zremrangeByScore(String key, double min, double max); - - void zremrangeByScore(String key, String min, String max); - - void zunion(ZParams params, String... keys); - - void zunionWithScores(ZParams params, String... keys); - - void zunionstore(String dstkey, String... sets); - - void zunionstore(String dstkey, ZParams params, String... sets); - - void zinter(ZParams params, String... keys); - - void zinterWithScores(ZParams params, String... keys); - - void zinterstore(String dstkey, String... sets); - - void zinterstore(String dstkey, ZParams params, String... sets); - - void strlen(String key); - - void lpushx(String key, String... string); - - void persist(String key); - - void rpushx(String key, String... string); - - void echo(String string); - - void linsert(String key, ListPosition where, String pivot, String value); - - void bgrewriteaof(); - - void bgsave(); - - void lastsave(); - - void save(); - - void configSet(String parameter, String value); - - void configGet(String pattern); - - void configResetStat(); - - void multi(); - - void exec(); - - void discard(); - - void objectRefcount(String key); - - void objectIdletime(String key); - - void objectEncoding(String key); - - void objectHelp(); - - void objectFreq(String key); - - void bitcount(String key); - - void bitcount(String key, long start, long end); - - void bitop(BitOP op, String destKey, String... srcKeys); - - void dump(String key); - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[])}. - */ - @Deprecated - default void restore(String key, int ttl, byte[] serializedValue) { - restore(key, (long) ttl, serializedValue); - } - - void restore(String key, long ttl, byte[] serializedValue); - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - default void restoreReplace(String key, int ttl, byte[] serializedValue) { - restoreReplace(key, (long) ttl, serializedValue); - } - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - void restoreReplace(String key, long ttl, byte[] serializedValue); - - void restore(String key, long ttl, byte[] serializedValue, RestoreParams params); - - void scan(String cursor, ScanParams params); - - void scan(String cursor, ScanParams params, String type); - - void hscan(String key, String cursor, ScanParams params); - - void sscan(String key, String cursor, ScanParams params); - - void zscan(String key, String cursor, ScanParams params); - - void waitReplicas(int replicas, long timeout); - - /** - * Used for BITFIELD Redis command - * @param key - * @param arguments - */ - void bitfield(String key, String... arguments); - - void bitfieldReadonly(String key, String... arguments); - - /** - * Used for HSTRLEN Redis command - * @param key - * @param field - */ - void hstrlen(String key, String field); - - void migrate(String host, int port, String key, int destinationDB, int timeout); - - void migrate(String host, int port, int destinationDB, int timeout, MigrateParams params, String... keys); - - void migrate(String host, int port, byte[] key, int destinationDB, int timeout); - - void migrate(String host, int port, int destinationDB, int timeout, MigrateParams params, byte[]... keys); - - void clientKill(String ipPort); - - void clientKill(String ip, int port); - - void clientKill(ClientKillParams params); - - void clientGetname(); - - void clientList(); - - void clientList(ClientType type); - - void clientList(long... clientIds); - - void clientInfo(); - - void clientSetname(String name); - - void clientId(); - - void clientUnblock(long clientId, UnblockType unblockType); - - void memoryDoctor(); - - void xadd(String key, StreamEntryID id, Map hash, long maxLen, boolean approximateLength); - - void xadd(String key, Map hash, XAddParams params); - - void xlen(String key); - - void xrange(String key, StreamEntryID start, StreamEntryID end); - - void xrange(String key, StreamEntryID start, StreamEntryID end, int count); - - /** - * @deprecated Use {@link #xrange(java.lang.String, redis.clients.jedis.StreamEntryID, redis.clients.jedis.StreamEntryID, int)}. - */ - @Deprecated - void xrange(String key, StreamEntryID start, StreamEntryID end, long count); - - void xrevrange(String key, StreamEntryID end, StreamEntryID start); - - void xrevrange(String key, StreamEntryID end, StreamEntryID start, int count); - - /** - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link #xread(redis.clients.jedis.params.XReadParams, java.util.Map)}. - */ - @Deprecated - void xread(int count, long block, Entry... streams); - - void xread(XReadParams params, Map streams); - - void xack(String key, String group, StreamEntryID... ids); - - void xgroupCreate(String key, String consumer, StreamEntryID id, boolean makeStream); - - void xgroupSetID(String key, String consumer, StreamEntryID id); - - void xgroupDestroy(String key, String consumer); - - void xgroupDelConsumer(String key, String consumer, String consumerName); - - void xdel(String key, StreamEntryID... ids); - - void xtrim(String key, long maxLen, boolean approximateLength); - - void xtrim(String key, XTrimParams params); - - /** - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link #xreadGroup(java.lang.String, java.lang.String, redis.clients.jedis.params.XReadGroupParams, java.util.Map)}. - */ - @Deprecated - void xreadGroup(String groupname, String consumer, int count, long block, boolean noAck, Entry... streams); - - void xreadGroup(String groupname, String consumer, XReadGroupParams params, Map streams); - - void xpending(String key, String groupname); - - void xpending(String key, String groupname, StreamEntryID start, StreamEntryID end, int count, String consumername); - - void xpending(String key, String groupname, XPendingParams params); - - void xclaim(String key, String group, String consumername, long minIdleTime, long newIdleTime, - int retries, boolean force, StreamEntryID... ids); - - void xclaim(String key, String group, String consumername, long minIdleTime, XClaimParams params, - StreamEntryID... ids); - - void xclaimJustId(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids); - - void xautoclaim(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params); - - void xautoclaimJustId(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params); - - void xinfoStream (String key); - - void xinfoGroup (String key); - - void xinfoConsumers (String key, String group); - - void strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params); - - void strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/ConfigCommands.java b/src/main/java/redis/clients/jedis/commands/ConfigCommands.java new file mode 100644 index 0000000000..e41d010879 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ConfigCommands.java @@ -0,0 +1,19 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +public interface ConfigCommands { + + List configGet(String pattern); + + List configGet(byte[] pattern); + + String configSet(String parameter, String value); + + String configSet(byte[] parameter, byte[] value); + + String configResetStat(); + + String configRewrite(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ControlBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/ControlBinaryCommands.java new file mode 100644 index 0000000000..a5389139d2 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ControlBinaryCommands.java @@ -0,0 +1,25 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +public interface ControlBinaryCommands extends AccessControlLogBinaryCommands, ClientBinaryCommands { + + List roleBinary(); + + Long objectRefcount(byte[] key); + + byte[] objectEncoding(byte[] key); + + Long objectIdletime(byte[] key); + + List objectHelpBinary(); + + Long objectFreq(byte[] key); + + byte[] memoryDoctorBinary(); + + Long memoryUsage(byte[] key); + + Long memoryUsage(byte[] key, int samples); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ControlCommands.java b/src/main/java/redis/clients/jedis/commands/ControlCommands.java new file mode 100644 index 0000000000..3e64f6b5fe --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ControlCommands.java @@ -0,0 +1,25 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +public interface ControlCommands extends AccessControlLogCommands, ClientCommands { + + List role(); + + Long objectRefcount(String key); + + String objectEncoding(String key); + + Long objectIdletime(String key); + + List objectHelp(); + + Long objectFreq(String key); + + String memoryDoctor(); + + Long memoryUsage(String key); + + Long memoryUsage(String key, int samples); + +} diff --git a/src/main/java/redis/clients/jedis/commands/DatabaseCommands.java b/src/main/java/redis/clients/jedis/commands/DatabaseCommands.java new file mode 100644 index 0000000000..6f7a3195bc --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/DatabaseCommands.java @@ -0,0 +1,56 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.args.FlushMode; +import redis.clients.jedis.params.MigrateParams; + +public interface DatabaseCommands { + + /** + * Select the DB with having the specified zero-based numeric index. + * @param index the index + * @return a simple string reply OK + */ + String select(int index); + + /** + * Return the number of keys in the currently-selected database. + * @return the number of key in the currently-selected database. + */ + long dbSize(); + + /** + * Delete all the keys of the currently selected DB. This command never fails. The time-complexity + * for this operation is O(N), N being the number of keys in the database. + * @param flushMode + * @return OK + */ + String flushDB(FlushMode flushMode); + + /** + * This command swaps two Redis databases, so that immediately all the clients connected to a + * given database will see the data of the other database, and the other way around. + * @param index1 + * @param index2 + * @return Simple string reply: OK if SWAPDB was executed correctly. + */ + String swapDB(int index1, int index2); + + long move(String key, int dbIndex); + + long move(byte[] key, int dbIndex); + + boolean copy(String srcKey, String dstKey, int db, boolean replace); + + boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace); + + String migrate(String host, int port, byte[] key, int destinationDB, int timeout); + + String migrate(String host, int port, int destinationDB, int timeout, MigrateParams params, + byte[]... keys); + + String migrate(String host, int port, String key, int destinationDB, int timeout); + + String migrate(String host, int port, int destinationDB, int timeout, MigrateParams params, + String... keys); + +} diff --git a/src/main/java/redis/clients/jedis/commands/GenericControlCommands.java b/src/main/java/redis/clients/jedis/commands/GenericControlCommands.java new file mode 100644 index 0000000000..042f2c8e8f --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/GenericControlCommands.java @@ -0,0 +1,16 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.Module; +import redis.clients.jedis.params.FailoverParams; + +public interface GenericControlCommands extends ConfigCommands, ScriptingControlCommands, SlowlogCommands { + + String failover(); + + String failover(FailoverParams failoverParams); + + String failoverAbort(); + + List moduleList(); +} diff --git a/src/main/java/redis/clients/jedis/commands/GeoBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/GeoBinaryCommands.java new file mode 100644 index 0000000000..84aa330515 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/GeoBinaryCommands.java @@ -0,0 +1,57 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.params.GeoAddParams; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.resps.GeoRadiusResponse; + +public interface GeoBinaryCommands { + + long geoadd(byte[] key, double longitude, double latitude, byte[] member); + + long geoadd(byte[] key, Map memberCoordinateMap); + + long geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap); + + Double geodist(byte[] key, byte[] member1, byte[] member2); + + Double geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit); + + List geohash(byte[] key, byte[]... members); + + List geopos(byte[] key, byte[]... members); + + List georadius(byte[] key, double longitude, double latitude, double radius, + GeoUnit unit); + + List georadiusReadonly(byte[] key, double longitude, double latitude, + double radius, GeoUnit unit); + + List georadius(byte[] key, double longitude, double latitude, double radius, + GeoUnit unit, GeoRadiusParam param); + + List georadiusReadonly(byte[] key, double longitude, double latitude, + double radius, GeoUnit unit, GeoRadiusParam param); + + List georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit); + + List georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit); + + List georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, + GeoRadiusParam param); + + List georadiusByMemberReadonly(byte[] key, byte[] member, double radius, + GeoUnit unit, GeoRadiusParam param); + + long georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + + long georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + +} diff --git a/src/main/java/redis/clients/jedis/commands/GeoCommands.java b/src/main/java/redis/clients/jedis/commands/GeoCommands.java new file mode 100644 index 0000000000..3a7e8c6f0b --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/GeoCommands.java @@ -0,0 +1,57 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.params.GeoAddParams; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.resps.GeoRadiusResponse; + +public interface GeoCommands { + + long geoadd(String key, double longitude, double latitude, String member); + + long geoadd(String key, Map memberCoordinateMap); + + long geoadd(String key, GeoAddParams params, Map memberCoordinateMap); + + Double geodist(String key, String member1, String member2); + + Double geodist(String key, String member1, String member2, GeoUnit unit); + + List geohash(String key, String... members); + + List geopos(String key, String... members); + + List georadius(String key, double longitude, double latitude, double radius, + GeoUnit unit); + + List georadiusReadonly(String key, double longitude, double latitude, + double radius, GeoUnit unit); + + List georadius(String key, double longitude, double latitude, double radius, + GeoUnit unit, GeoRadiusParam param); + + List georadiusReadonly(String key, double longitude, double latitude, + double radius, GeoUnit unit, GeoRadiusParam param); + + List georadiusByMember(String key, String member, double radius, GeoUnit unit); + + List georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit); + + List georadiusByMember(String key, String member, double radius, GeoUnit unit, + GeoRadiusParam param); + + List georadiusByMemberReadonly(String key, String member, double radius, + GeoUnit unit, GeoRadiusParam param); + + long georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + + long georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + +} diff --git a/src/main/java/redis/clients/jedis/commands/GeoPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/GeoPipelineBinaryCommands.java new file mode 100644 index 0000000000..cb690cc790 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/GeoPipelineBinaryCommands.java @@ -0,0 +1,58 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.Response; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.params.GeoAddParams; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.resps.GeoRadiusResponse; + +public interface GeoPipelineBinaryCommands { + + Response geoadd(byte[] key, double longitude, double latitude, byte[] member); + + Response geoadd(byte[] key, Map memberCoordinateMap); + + Response geoadd(byte[] key, GeoAddParams params, Map memberCoordinateMap); + + Response geodist(byte[] key, byte[] member1, byte[] member2); + + Response geodist(byte[] key, byte[] member1, byte[] member2, GeoUnit unit); + + Response> geohash(byte[] key, byte[]... members); + + Response> geopos(byte[] key, byte[]... members); + + Response> georadius(byte[] key, double longitude, double latitude, double radius, + GeoUnit unit); + + Response> georadiusReadonly(byte[] key, double longitude, double latitude, + double radius, GeoUnit unit); + + Response> georadius(byte[] key, double longitude, double latitude, double radius, + GeoUnit unit, GeoRadiusParam param); + + Response> georadiusReadonly(byte[] key, double longitude, double latitude, + double radius, GeoUnit unit, GeoRadiusParam param); + + Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit); + + Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, GeoUnit unit); + + Response> georadiusByMember(byte[] key, byte[] member, double radius, GeoUnit unit, + GeoRadiusParam param); + + Response> georadiusByMemberReadonly(byte[] key, byte[] member, double radius, + GeoUnit unit, GeoRadiusParam param); + + Response georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + + Response georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + +} diff --git a/src/main/java/redis/clients/jedis/commands/GeoPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/GeoPipelineCommands.java new file mode 100644 index 0000000000..1767c36245 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/GeoPipelineCommands.java @@ -0,0 +1,58 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.Response; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.params.GeoAddParams; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.resps.GeoRadiusResponse; + +public interface GeoPipelineCommands { + + Response geoadd(String key, double longitude, double latitude, String member); + + Response geoadd(String key, Map memberCoordinateMap); + + Response geoadd(String key, GeoAddParams params, Map memberCoordinateMap); + + Response geodist(String key, String member1, String member2); + + Response geodist(String key, String member1, String member2, GeoUnit unit); + + Response> geohash(String key, String... members); + + Response> geopos(String key, String... members); + + Response> georadius(String key, double longitude, double latitude, double radius, + GeoUnit unit); + + Response> georadiusReadonly(String key, double longitude, double latitude, + double radius, GeoUnit unit); + + Response> georadius(String key, double longitude, double latitude, double radius, + GeoUnit unit, GeoRadiusParam param); + + Response> georadiusReadonly(String key, double longitude, double latitude, + double radius, GeoUnit unit, GeoRadiusParam param); + + Response> georadiusByMember(String key, String member, double radius, GeoUnit unit); + + Response> georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit); + + Response> georadiusByMember(String key, String member, double radius, GeoUnit unit, + GeoRadiusParam param); + + Response> georadiusByMemberReadonly(String key, String member, double radius, + GeoUnit unit, GeoRadiusParam param); + + Response georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + + Response georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, + GeoRadiusParam param, GeoRadiusStoreParam storeParam); + +} diff --git a/src/main/java/redis/clients/jedis/commands/HashBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/HashBinaryCommands.java new file mode 100644 index 0000000000..2a4fabe51c --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HashBinaryCommands.java @@ -0,0 +1,54 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface HashBinaryCommands { + + long hset(byte[] key, byte[] field, byte[] value); + + long hset(byte[] key, Map hash); + + byte[] hget(byte[] key, byte[] field); + + long hsetnx(byte[] key, byte[] field, byte[] value); + + String hmset(byte[] key, Map hash); + + List hmget(byte[] key, byte[]... fields); + + long hincrBy(byte[] key, byte[] field, long value); + + double hincrByFloat(byte[] key, byte[] field, double value); + + boolean hexists(byte[] key, byte[] field); + + long hdel(byte[] key, byte[]... field); + + long hlen(byte[] key); + + Set hkeys(byte[] key); + + List hvals(byte[] key); + + Map hgetAll(byte[] key); + + byte[] hrandfield(byte[] key); + + List hrandfield(byte[] key, long count); + + Map hrandfieldWithValues(byte[] key, long count); + + default ScanResult> hscan(byte[] key, byte[] cursor) { + return hscan(key, cursor, new ScanParams()); + } + + ScanResult> hscan(byte[] key, byte[] cursor, ScanParams params); + + long hstrlen(byte[] key, byte[] field); + +} diff --git a/src/main/java/redis/clients/jedis/commands/HashCommands.java b/src/main/java/redis/clients/jedis/commands/HashCommands.java new file mode 100644 index 0000000000..84ad32c6d8 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HashCommands.java @@ -0,0 +1,53 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface HashCommands { + + long hset(String key, String field, String value); + + long hset(String key, Map hash); + + String hget(String key, String field); + + long hsetnx(String key, String field, String value); + + String hmset(String key, Map hash); + + List hmget(String key, String... fields); + + long hincrBy(String key, String field, long value); + + double hincrByFloat(String key, String field, double value); + + boolean hexists(String key, String field); + + long hdel(String key, String... field); + + long hlen(String key); + + Set hkeys(String key); + + List hvals(String key); + + Map hgetAll(String key); + + String hrandfield(String key); + + List hrandfield(String key, long count); + + Map hrandfieldWithValues(String key, long count); + + default ScanResult> hscan(String key, String cursor) { + return hscan(key, cursor, new ScanParams()); + } + + ScanResult> hscan(String key, String cursor, ScanParams params); + + long hstrlen(String key, String field); +} diff --git a/src/main/java/redis/clients/jedis/commands/HashPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/HashPipelineBinaryCommands.java new file mode 100644 index 0000000000..e7624a0ca5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HashPipelineBinaryCommands.java @@ -0,0 +1,55 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface HashPipelineBinaryCommands { + + Response hset(byte[] key, byte[] field, byte[] value); + + Response hset(byte[] key, Map hash); + + Response hget(byte[] key, byte[] field); + + Response hsetnx(byte[] key, byte[] field, byte[] value); + + Response hmset(byte[] key, Map hash); + + Response> hmget(byte[] key, byte[]... fields); + + Response hincrBy(byte[] key, byte[] field, long value); + + Response hincrByFloat(byte[] key, byte[] field, double value); + + Response hexists(byte[] key, byte[] field); + + Response hdel(byte[] key, byte[]... field); + + Response hlen(byte[] key); + + Response> hkeys(byte[] key); + + Response> hvals(byte[] key); + + Response> hgetAll(byte[] key); + + Response hrandfield(byte[] key); + + Response> hrandfield(byte[] key, long count); + + Response> hrandfieldWithValues(byte[] key, long count); + + default Response>> hscan(byte[] key, byte[] cursor) { + return hscan(key, cursor, new ScanParams()); + } + + Response>> hscan(byte[] key, byte[] cursor, ScanParams params); + + Response hstrlen(byte[] key, byte[] field); + +} diff --git a/src/main/java/redis/clients/jedis/commands/HashPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/HashPipelineCommands.java new file mode 100644 index 0000000000..ea11b0b77e --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HashPipelineCommands.java @@ -0,0 +1,54 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface HashPipelineCommands { + + Response hset(String key, String field, String value); + + Response hset(String key, Map hash); + + Response hget(String key, String field); + + Response hsetnx(String key, String field, String value); + + Response hmset(String key, Map hash); + + Response> hmget(String key, String... fields); + + Response hincrBy(String key, String field, long value); + + Response hincrByFloat(String key, String field, double value); + + Response hexists(String key, String field); + + Response hdel(String key, String... field); + + Response hlen(String key); + + Response> hkeys(String key); + + Response> hvals(String key); + + Response> hgetAll(String key); + + Response hrandfield(String key); + + Response> hrandfield(String key, long count); + + Response> hrandfieldWithValues(String key, long count); + + default Response>> hscan(String key, String cursor) { + return hscan(key, cursor, new ScanParams()); + } + + Response>> hscan(String key, String cursor, ScanParams params); + + Response hstrlen(String key, String field); +} diff --git a/src/main/java/redis/clients/jedis/commands/HyperLogLogBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/HyperLogLogBinaryCommands.java new file mode 100644 index 0000000000..7bf24cdeff --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HyperLogLogBinaryCommands.java @@ -0,0 +1,13 @@ +package redis.clients.jedis.commands; + +public interface HyperLogLogBinaryCommands { + + long pfadd(byte[] key, byte[]... elements); + + String pfmerge(byte[] destkey, byte[]... sourcekeys); + + long pfcount(byte[] key); + + long pfcount(byte[]... keys); + +} diff --git a/src/main/java/redis/clients/jedis/commands/HyperLogLogCommands.java b/src/main/java/redis/clients/jedis/commands/HyperLogLogCommands.java new file mode 100644 index 0000000000..4f99249031 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HyperLogLogCommands.java @@ -0,0 +1,13 @@ +package redis.clients.jedis.commands; + +public interface HyperLogLogCommands { + + long pfadd(String key, String... elements); + + String pfmerge(String destkey, String... sourcekeys); + + long pfcount(String key); + + long pfcount(String... keys); + +} diff --git a/src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineBinaryCommands.java new file mode 100644 index 0000000000..d890ee5877 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineBinaryCommands.java @@ -0,0 +1,15 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.Response; + +public interface HyperLogLogPipelineBinaryCommands { + + Response pfadd(byte[] key, byte[]... elements); + + Response pfmerge(byte[] destkey, byte[]... sourcekeys); + + Response pfcount(byte[] key); + + Response pfcount(byte[]... keys); + +} diff --git a/src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineCommands.java new file mode 100644 index 0000000000..6d6360a273 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/HyperLogLogPipelineCommands.java @@ -0,0 +1,15 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.Response; + +public interface HyperLogLogPipelineCommands { + + Response pfadd(String key, String... elements); + + Response pfmerge(String destkey, String... sourcekeys); + + Response pfcount(String key); + + Response pfcount(String... keys); + +} diff --git a/src/main/java/redis/clients/jedis/commands/JedisBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/JedisBinaryCommands.java new file mode 100644 index 0000000000..110045de85 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/JedisBinaryCommands.java @@ -0,0 +1,6 @@ +package redis.clients.jedis.commands; + +public interface JedisBinaryCommands extends KeyBinaryCommands, StringBinaryCommands, + ListBinaryCommands, HashBinaryCommands, SetBinaryCommands, SortedSetBinaryCommands, + GeoBinaryCommands, HyperLogLogBinaryCommands, StreamBinaryCommands, ScriptingKeyBinaryCommands { +} diff --git a/src/main/java/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java b/src/main/java/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java deleted file mode 100644 index 6634d3c420..0000000000 --- a/src/main/java/redis/clients/jedis/commands/JedisClusterBinaryScriptingCommands.java +++ /dev/null @@ -1,64 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.args.FlushMode; - -import java.util.List; - -public interface JedisClusterBinaryScriptingCommands { - Object eval(byte[] script, byte[] keyCount, byte[]... params); - - Object eval(byte[] script, int keyCount, byte[]... params); - - Object eval(byte[] script, List keys, List args); - - /** - * @param script - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - Object eval(byte[] script, byte[] sampleKey); - - /** - * @param sha1 - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - Object evalsha(byte[] sha1, byte[] sampleKey); - - Object evalsha(byte[] sha1, List keys, List args); - - Object evalsha(byte[] sha1, int keyCount, byte[]... params); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @param sha1 - */ - List scriptExists(byte[] sampleKey, byte[]... sha1); - - /** - * @param script - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - byte[] scriptLoad(byte[] script, byte[] sampleKey); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - String scriptFlush(byte[] sampleKey); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @param flushMode - */ - String scriptFlush(byte[] sampleKey, FlushMode flushMode); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - String scriptKill(byte[] sampleKey); -} diff --git a/src/main/java/redis/clients/jedis/commands/JedisClusterCommands.java b/src/main/java/redis/clients/jedis/commands/JedisClusterCommands.java deleted file mode 100644 index 5da79336f1..0000000000 --- a/src/main/java/redis/clients/jedis/commands/JedisClusterCommands.java +++ /dev/null @@ -1,16 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.params.RestoreParams; - -public interface JedisClusterCommands extends JedisCommands { - - /** - * @deprecated Use {@link JedisCommands#restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - default String restoreReplace(String key, long ttl, byte[] serializedValue) { - return restore(key, ttl, serializedValue, RestoreParams.restoreParams().replace()); - } - - long waitReplicas(String key, int replicas, long timeout); -} diff --git a/src/main/java/redis/clients/jedis/commands/JedisClusterScriptingCommands.java b/src/main/java/redis/clients/jedis/commands/JedisClusterScriptingCommands.java deleted file mode 100644 index d15c07d28a..0000000000 --- a/src/main/java/redis/clients/jedis/commands/JedisClusterScriptingCommands.java +++ /dev/null @@ -1,60 +0,0 @@ -package redis.clients.jedis.commands; - -import java.util.List; - -public interface JedisClusterScriptingCommands { - Object eval(String script, int keyCount, String... params); - - Object eval(String script, List keys, List args); - - /** - * @param script - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - Object eval(String script, String sampleKey); - - /** - * @param sha1 - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - Object evalsha(String sha1, String sampleKey); - - Object evalsha(String sha1, List keys, List args); - - Object evalsha(String sha1, int keyCount, String... params); - - /** - * @param sha1 - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - Boolean scriptExists(String sha1, String sampleKey); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - * @param sha1 - */ - List scriptExists(String sampleKey, String... sha1); - - /** - * @param script - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - String scriptLoad(String script, String sampleKey); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - String scriptFlush(String sampleKey); - - /** - * @param sampleKey Command will be executed in the node where the hash slot of this key is - * assigned to - */ - String scriptKill(String sampleKey); -} diff --git a/src/main/java/redis/clients/jedis/commands/JedisCommands.java b/src/main/java/redis/clients/jedis/commands/JedisCommands.java index b86819eed1..a00b5329f2 100644 --- a/src/main/java/redis/clients/jedis/commands/JedisCommands.java +++ b/src/main/java/redis/clients/jedis/commands/JedisCommands.java @@ -1,704 +1,6 @@ package redis.clients.jedis.commands; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import redis.clients.jedis.BitPosParams; -import redis.clients.jedis.StreamConsumersInfo; -import redis.clients.jedis.StreamEntryID; -import redis.clients.jedis.GeoCoordinate; -import redis.clients.jedis.GeoRadiusResponse; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.ListPosition; -import redis.clients.jedis.StreamGroupInfo; -import redis.clients.jedis.StreamInfo; -import redis.clients.jedis.StreamPendingEntry; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.StreamEntry; -import redis.clients.jedis.StreamPendingSummary; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.params.GeoAddParams; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GetExParams; -import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.params.SetParams; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.params.ZAddParams; -import redis.clients.jedis.params.ZIncrByParams; -import redis.clients.jedis.params.LPosParams; -import redis.clients.jedis.resps.KeyedListElement; -import redis.clients.jedis.resps.LCSMatchResult; - -/** - * Common interface for sharded and non-sharded Jedis - */ -public interface JedisCommands { - String set(String key, String value); - - String set(String key, String value, SetParams params); - - String get(String key); - - String getDel(String key); - - String getEx(String key, GetExParams params); - - boolean exists(String key); - - long persist(String key); - - String type(String key); - - byte[] dump(String key); - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[])}. - */ - @Deprecated - default String restore(String key, int ttl, byte[] serializedValue) { - return restore(key, (long) ttl, serializedValue); - } - - String restore(String key, long ttl, byte[] serializedValue); - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - default String restoreReplace(String key, int ttl, byte[] serializedValue) { - return restoreReplace(key, (long) ttl, serializedValue); - } - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - String restoreReplace(String key, long ttl, byte[] serializedValue); - - String restore(String key, long ttl, byte[] serializedValue, RestoreParams params); - - /** - * @deprecated Use {@link #expire(java.lang.String, long)}. - */ - @Deprecated - default Long expire(String key, int seconds) { - return expire(key, (long) seconds); - } - - long expire(String key, long seconds); - - long pexpire(String key, long milliseconds); - - long expireAt(String key, long unixTime); - - long pexpireAt(String key, long millisecondsTimestamp); - - long ttl(String key); - - long pttl(String key); - - long touch(String key); - - boolean setbit(String key, long offset, boolean value); - - /** - * @deprecated Use {@link #setbit(java.lang.String, long, boolean)}. - */ - @Deprecated - Boolean setbit(String key, long offset, String value); - - boolean getbit(String key, long offset); - - long setrange(String key, long offset, String value); - - String getrange(String key, long startOffset, long endOffset); - - String getSet(String key, String value); - - long setnx(String key, String value); - - /** - * @deprecated Use {@link #setex(java.lang.String, long, java.lang.String)}. - */ - @Deprecated - default String setex(String key, int seconds, String value) { - return setex(key, (long) seconds, value); - } - - String setex(String key, long seconds, String value); - - String psetex(String key, long milliseconds, String value); - - long decrBy(String key, long decrement); - - long decr(String key); - - long incrBy(String key, long increment); - - double incrByFloat(String key, double increment); - - long incr(String key); - - long append(String key, String value); - - String substr(String key, int start, int end); - - long hset(String key, String field, String value); - - long hset(String key, Map hash); - - String hget(String key, String field); - - long hsetnx(String key, String field, String value); - - String hmset(String key, Map hash); - - List hmget(String key, String... fields); - - long hincrBy(String key, String field, long value); - - double hincrByFloat(String key, String field, double value); - - boolean hexists(String key, String field); - - long hdel(String key, String... field); - - long hlen(String key); - - Set hkeys(String key); - - List hvals(String key); - - Map hgetAll(String key); - - String hrandfield(String key); - - List hrandfield(String key, long count); - - Map hrandfieldWithValues(String key, long count); - - long rpush(String key, String... string); - - long lpush(String key, String... string); - - long llen(String key); - - List lrange(String key, long start, long stop); - - String ltrim(String key, long start, long stop); - - String lindex(String key, long index); - - String lset(String key, long index, String value); - - long lrem(String key, long count, String value); - - String lpop(String key); - - List lpop(String key, int count); - - Long lpos(String key, String element); - - Long lpos(String key, String element, LPosParams params); - - List lpos(String key, String element, LPosParams params, long count); - - String rpop(String key); - - List rpop(String key, int count); - - long sadd(String key, String... member); - - Set smembers(String key); - - long srem(String key, String... member); - - String spop(String key); - - Set spop(String key, long count); - - long scard(String key); - - boolean sismember(String key, String member); - - List smismember(String key, String... members); - - String srandmember(String key); - - List srandmember(String key, int count); - - long strlen(String key); - - long zadd(String key, double score, String member); - - long zadd(String key, double score, String member, ZAddParams params); - - long zadd(String key, Map scoreMembers); - - long zadd(String key, Map scoreMembers, ZAddParams params); - - Double zaddIncr(String key, double score, String member, ZAddParams params); - - Set zrange(String key, long start, long stop); - - long zrem(String key, String... members); - - double zincrby(String key, double increment, String member); - - Double zincrby(String key, double increment, String member, ZIncrByParams params); - - Long zrank(String key, String member); - - Long zrevrank(String key, String member); - - Set zrevrange(String key, long start, long stop); - - Set zrangeWithScores(String key, long start, long stop); - - Set zrevrangeWithScores(String key, long start, long stop); - - String zrandmember(String key); - - Set zrandmember(String key, long count); - - Set zrandmemberWithScores(String key, long count); - - long zcard(String key); - - Double zscore(String key, String member); - - List zmscore(String key, String... members); - - Tuple zpopmax(String key); - - Set zpopmax(String key, int count); - - Tuple zpopmin(String key); - - Set zpopmin(String key, int count); - - List sort(String key); - - List sort(String key, SortingParams sortingParameters); - - long zcount(String key, double min, double max); - - long zcount(String key, String min, String max); - - Set zrangeByScore(String key, double min, double max); - - Set zrangeByScore(String key, String min, String max); - - Set zrevrangeByScore(String key, double max, double min); - - Set zrangeByScore(String key, double min, double max, int offset, int count); - - Set zrevrangeByScore(String key, String max, String min); - - Set zrangeByScore(String key, String min, String max, int offset, int count); - - Set zrevrangeByScore(String key, double max, double min, int offset, int count); - - Set zrangeByScoreWithScores(String key, double min, double max); - - Set zrevrangeByScoreWithScores(String key, double max, double min); - - Set zrangeByScoreWithScores(String key, double min, double max, int offset, int count); - - Set zrevrangeByScore(String key, String max, String min, int offset, int count); - - Set zrangeByScoreWithScores(String key, String min, String max); - - Set zrevrangeByScoreWithScores(String key, String max, String min); - - Set zrangeByScoreWithScores(String key, String min, String max, int offset, int count); - - Set zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count); - - Set zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count); - - long zremrangeByRank(String key, long start, long stop); - - long zremrangeByScore(String key, double min, double max); - - long zremrangeByScore(String key, String min, String max); - - long zlexcount(String key, String min, String max); - - Set zrangeByLex(String key, String min, String max); - - Set zrangeByLex(String key, String min, String max, int offset, int count); - - Set zrevrangeByLex(String key, String max, String min); - - Set zrevrangeByLex(String key, String max, String min, int offset, int count); - - long zremrangeByLex(String key, String min, String max); - - long linsert(String key, ListPosition where, String pivot, String value); - - long lpushx(String key, String... string); - - long rpushx(String key, String... string); - - List blpop(int timeout, String key); - - KeyedListElement blpop(double timeout, String key); - - List brpop(int timeout, String key); - - KeyedListElement brpop(double timeout, String key); - - long del(String key); - - long unlink(String key); - - String echo(String string); - - long bitcount(String key); - - long bitcount(String key, long start, long end); - - long bitpos(String key, boolean value); - - long bitpos(String key, boolean value, BitPosParams params); - - default ScanResult> hscan(String key, String cursor) { - return hscan(key, cursor, new ScanParams()); - } - - ScanResult> hscan(String key, String cursor, ScanParams params); - - default ScanResult sscan(String key, String cursor) { - return sscan(key, cursor, new ScanParams()); - } - - ScanResult sscan(String key, String cursor, ScanParams params); - - default ScanResult zscan(String key, String cursor) { - return zscan(key, cursor, new ScanParams()); - } - - ScanResult zscan(String key, String cursor, ScanParams params); - - long pfadd(String key, String... elements); - - long pfcount(String key); - - // Geo Commands - - long geoadd(String key, double longitude, double latitude, String member); - - long geoadd(String key, Map memberCoordinateMap); - - long geoadd(String key, GeoAddParams params, Map memberCoordinateMap); - - Double geodist(String key, String member1, String member2); - - Double geodist(String key, String member1, String member2, GeoUnit unit); - - List geohash(String key, String... members); - - List geopos(String key, String... members); - - List georadius(String key, double longitude, double latitude, double radius, - GeoUnit unit); - - List georadiusReadonly(String key, double longitude, double latitude, - double radius, GeoUnit unit); - - List georadius(String key, double longitude, double latitude, double radius, - GeoUnit unit, GeoRadiusParam param); - - List georadiusReadonly(String key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); - - List georadiusByMember(String key, String member, double radius, GeoUnit unit); - - List georadiusByMemberReadonly(String key, String member, double radius, GeoUnit unit); - - List georadiusByMember(String key, String member, double radius, GeoUnit unit, - GeoRadiusParam param); - - List georadiusByMemberReadonly(String key, String member, double radius, - GeoUnit unit, GeoRadiusParam param); - - /** - * Executes BITFIELD Redis command - * @param key - * @param arguments - */ - List bitfield(String key, String...arguments); - - List bitfieldReadonly(String key, String...arguments); - - /** - * Used for HSTRLEN Redis command - * @param key - * @param field - * @return length of the value for key - */ - long hstrlen(String key, String field); - - /** - * XADD key ID field string [field string ...] - * - * @param key - * @param id - * @param hash - * @return the ID of the added entry - */ - StreamEntryID xadd(String key, StreamEntryID id, Map hash); - - /** - * XADD key MAXLEN ~ LEN ID field string [field string ...] - * - * @param key - * @param id - * @param hash - * @param maxLen - * @param approximateLength - */ - StreamEntryID xadd(String key, StreamEntryID id, Map hash, long maxLen, boolean approximateLength); - - /** - * XADD key [NOMKSTREAM] [MAXLEN|MINID [=|~] threshold [LIMIT count]] *|ID field value [field value ...] - * - * @param key - * @param hash - * @param params - */ - StreamEntryID xadd(String key, Map hash, XAddParams params); - - /** - * XLEN key - * - * @param key - */ - long xlen(String key); - - /** - * XRANGE key start end - * - * @param key - * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream - * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream - * @return The entries with IDs matching the specified range. - */ - List xrange(String key, StreamEntryID start, StreamEntryID end); - - /** - * XRANGE key start end COUNT count - * - * @param key - * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream - * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream - * @param count maximum number of entries returned - * @return The entries with IDs matching the specified range. - */ - List xrange(String key, StreamEntryID start, StreamEntryID end, int count); - - /** - * XREVRANGE key end start - * - * @param key - * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream - * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream - * @return the entries with IDs matching the specified range, from the higher ID to the lower ID matching. - */ - List xrevrange(String key, StreamEntryID end, StreamEntryID start); - - /** - * XREVRANGE key end start COUNT count - * - * @param key - * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream - * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream - * @param count The entries with IDs matching the specified range. - * @return the entries with IDs matching the specified range, from the higher ID to the lower ID matching. - */ - List xrevrange(String key, StreamEntryID end, StreamEntryID start, int count); - - /** - * XACK key group ID [ID ...] - * - * @param key - * @param group - * @param ids - */ - long xack(String key, String group, StreamEntryID... ids); - - /** - * XGROUP CREATE - * - * @param key - * @param groupname - * @param id - * @param makeStream - */ - String xgroupCreate( String key, String groupname, StreamEntryID id, boolean makeStream); - - /** - * XGROUP SETID - * - * @param key - * @param groupname - * @param id - */ - String xgroupSetID( String key, String groupname, StreamEntryID id); - - /** - * XGROUP DESTROY - * - * @param key - * @param groupname - */ - long xgroupDestroy(String key, String groupname); - - /** - * XGROUP DELCONSUMER - * @param key - * @param groupname - * @param consumername - */ - long xgroupDelConsumer( String key, String groupname, String consumername); - - /** - * XPENDING key group - * - * @param key - * @param groupname - */ - StreamPendingSummary xpending(String key, String groupname); - - /** - * XPENDING key group [start end count] [consumer] - * - * @param key - * @param groupname - * @param start - * @param end - * @param count - * @param consumername - */ - List xpending(String key, String groupname, StreamEntryID start, - StreamEntryID end, int count, String consumername); - - /** - * XPENDING key group [[IDLE min-idle-time] start end count [consumer]] - * - * @param key - * @param groupname - * @param params - */ - List xpending(String key, String groupname, XPendingParams params); - - /** - * XDEL key ID [ID ...] - * @param key - * @param ids - */ - long xdel(String key, StreamEntryID... ids); - - /** - * XTRIM key MAXLEN [~] count - * @param key - * @param maxLen - * @param approximate - */ - long xtrim(String key, long maxLen, boolean approximate); - - /** - * XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] - * @param key - * @param params - */ - long xtrim(String key, XTrimParams params); - - /** - * XCLAIM - * [IDLE ] [TIME ] [RETRYCOUNT ] - * [FORCE] [JUSTID] - */ - List xclaim( String key, String group, String consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, StreamEntryID... ids); - - /** - * XCLAIM ... - * [IDLE ] [TIME ] [RETRYCOUNT ] - * [FORCE] - */ - List xclaim(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids); - - /** - * XCLAIM ... - * [IDLE ] [TIME ] [RETRYCOUNT ] - * [FORCE] JUSTID - */ - List xclaimJustId(String key, String group, String consumername, long minIdleTime, - XClaimParams params, StreamEntryID... ids); - - /** - * XAUTOCLAIM key group consumer min-idle-time start [COUNT count] - * - * @param key Stream Key - * @param group Consumer Group - * @param consumerName Consumer name to transfer the auto claimed entries - * @param minIdleTime Entries pending more than minIdleTime will be transferred ownership - * @param start {@link StreamEntryID} - Entries >= start will be transferred ownership, passing null will indicate '-' - * @param params {@link XAutoClaimParams} - */ - Map.Entry> xautoclaim(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params); - - /** - * XAUTOCLAIM key group consumer min-idle-time start [COUNT count] JUSTID - * - * @param key Stream Key - * @param group Consumer Group - * @param consumerName Consumer name to transfer the auto claimed entries - * @param minIdleTime Entries pending more than minIdleTime will be transferred ownership - * @param start {@link StreamEntryID} - Entries >= start will be transferred ownership, passing null will indicate '-' - * @param params {@link XAutoClaimParams} - */ - Map.Entry> xautoclaimJustId(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params); - - /** - * Introspection command used in order to retrieve different information about the stream - * @param key Stream name - * @return {@link StreamInfo} that contains information about the stream - */ - StreamInfo xinfoStream (String key); - - /** - * Introspection command used in order to retrieve different information about groups in the stream - * @param key Stream name - * @return List of {@link StreamGroupInfo} containing information about groups - */ - List xinfoGroup (String key); - - /** - * Introspection command used in order to retrieve different information about consumers in the group - * @param key Stream name - * @param group Group name - * @return List of {@link StreamConsumersInfo} containing information about consumers that belong - * to the the group - */ - List xinfoConsumers (String key, String group); - - Long memoryUsage(String key); - - Long memoryUsage(String key, int samples); - - LCSMatchResult strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params); +public interface JedisCommands extends KeyCommands, StringCommands, ListCommands, HashCommands, + SetCommands, SortedSetCommands, GeoCommands, HyperLogLogCommands, StreamCommands, + ScriptingKeyCommands { } diff --git a/src/main/java/redis/clients/jedis/commands/KeyBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/KeyBinaryCommands.java new file mode 100644 index 0000000000..d8fc628fe1 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/KeyBinaryCommands.java @@ -0,0 +1,92 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.params.MigrateParams; +import redis.clients.jedis.params.RestoreParams; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.SortingParams; +import redis.clients.jedis.resps.ScanResult; + +public interface KeyBinaryCommands { + + boolean exists(byte[] key); + + long exists(byte[]... keys); + + long persist(byte[] key); + + String type(byte[] key); + + byte[] dump(byte[] key); + + String restore(byte[] key, long ttl, byte[] serializedValue); + + String restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params); + + long expire(byte[] key, long seconds); + + long pexpire(byte[] key, long milliseconds); + + long expireAt(byte[] key, long unixTime); + + long pexpireAt(byte[] key, long millisecondsTimestamp); + + long ttl(byte[] key); + + long pttl(byte[] key); + + long touch(byte[] key); + + long touch(byte[]... keys); + + List sort(byte[] key); + + List sort(byte[] key, SortingParams sortingParameters); + + long del(byte[] key); + + long del(byte[]... keys); + + long unlink(byte[] key); + + long unlink(byte[]... keys); + + boolean copy(byte[] srcKey, byte[] dstKey, boolean replace); + + String rename(byte[] oldkey, byte[] newkey); + + long renamenx(byte[] oldkey, byte[] newkey); + + long sort(byte[] key, SortingParams sortingParameters, byte[] dstkey); + + long sort(byte[] key, byte[] dstkey); + + Long memoryUsage(byte[] key); + + Long memoryUsage(byte[] key, int samples); + + Long objectRefcount(byte[] key); + + byte[] objectEncoding(byte[] key); + + Long objectIdletime(byte[] key); + + Long objectFreq(byte[] key); + + String migrate(String host, int port, byte[] key, int timeout); + + String migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys); + + Set keys(byte[] pattern); + + ScanResult scan(byte[] cursor); + + ScanResult scan(byte[] cursor, ScanParams params); + + ScanResult scan(byte[] cursor, ScanParams params, byte[] type); + + byte[] randomBinaryKey(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/KeyCommands.java b/src/main/java/redis/clients/jedis/commands/KeyCommands.java new file mode 100644 index 0000000000..c54222b0df --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/KeyCommands.java @@ -0,0 +1,92 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.params.MigrateParams; +import redis.clients.jedis.params.RestoreParams; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.SortingParams; +import redis.clients.jedis.resps.ScanResult; + +public interface KeyCommands { + + boolean exists(String key); + + long exists(String... keys); + + long persist(String key); + + String type(String key); + + byte[] dump(String key); + + String restore(String key, long ttl, byte[] serializedValue); + + String restore(String key, long ttl, byte[] serializedValue, RestoreParams params); + + long expire(String key, long seconds); + + long pexpire(String key, long milliseconds); + + long expireAt(String key, long unixTime); + + long pexpireAt(String key, long millisecondsTimestamp); + + long ttl(String key); + + long pttl(String key); + + long touch(String key); + + long touch(String... keys); + + List sort(String key); + + long sort(String key, String dstkey); + + List sort(String key, SortingParams sortingParameters); + + long sort(String key, SortingParams sortingParameters, String dstkey); + + long del(String key); + + long del(String... keys); + + long unlink(String key); + + long unlink(String... keys); + + boolean copy(String srcKey, String dstKey, boolean replace); + + String rename(String oldkey, String newkey); + + long renamenx(String oldkey, String newkey); + + Long memoryUsage(String key); + + Long memoryUsage(String key, int samples); + + Long objectRefcount(String key); + + String objectEncoding(String key); + + Long objectIdletime(String key); + + Long objectFreq(String key); + + String migrate(String host, int port, String key, int timeout); + + String migrate(String host, int port, int timeout, MigrateParams params, String... keys); + + Set keys(String pattern); + + ScanResult scan(String cursor); + + ScanResult scan(String cursor, ScanParams params); + + ScanResult scan(String cursor, ScanParams params, String type); + + String randomKey(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/KeyPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/KeyPipelineBinaryCommands.java new file mode 100644 index 0000000000..007a79df4a --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/KeyPipelineBinaryCommands.java @@ -0,0 +1,93 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.MigrateParams; +import redis.clients.jedis.params.RestoreParams; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.SortingParams; +import redis.clients.jedis.resps.ScanResult; + +public interface KeyPipelineBinaryCommands { + + Response exists(byte[] key); + + Response exists(byte[]... keys); + + Response persist(byte[] key); + + Response type(byte[] key); + + Response dump(byte[] key); + + Response restore(byte[] key, long ttl, byte[] serializedValue); + + Response restore(byte[] key, long ttl, byte[] serializedValue, RestoreParams params); + + Response expire(byte[] key, long seconds); + + Response pexpire(byte[] key, long milliseconds); + + Response expireAt(byte[] key, long unixTime); + + Response pexpireAt(byte[] key, long millisecondsTimestamp); + + Response ttl(byte[] key); + + Response pttl(byte[] key); + + Response touch(byte[] key); + + Response touch(byte[]... keys); + + Response> sort(byte[] key); + + Response> sort(byte[] key, SortingParams sortingParameters); + + Response del(byte[] key); + + Response del(byte[]... keys); + + Response unlink(byte[] key); + + Response unlink(byte[]... keys); + + Response copy(byte[] srcKey, byte[] dstKey, boolean replace); + + Response rename(byte[] oldkey, byte[] newkey); + + Response renamenx(byte[] oldkey, byte[] newkey); + + Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey); + + Response sort(byte[] key, byte[] dstkey); + + Response memoryUsage(byte[] key); + + Response memoryUsage(byte[] key, int samples); + + Response objectRefcount(byte[] key); + + Response objectEncoding(byte[] key); + + Response objectIdletime(byte[] key); + + Response objectFreq(byte[] key); + + Response migrate(String host, int port, byte[] key, int timeout); + + Response migrate(String host, int port, int timeout, MigrateParams params, byte[]... keys); + + Response> keys(byte[] pattern); + + Response> scan(byte[] cursor); + + Response> scan(byte[] cursor, ScanParams params); + + Response> scan(byte[] cursor, ScanParams params, byte[] type); + + Response randomBinaryKey(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/KeyPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/KeyPipelineCommands.java new file mode 100644 index 0000000000..4e9a6982bd --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/KeyPipelineCommands.java @@ -0,0 +1,93 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.params.MigrateParams; +import redis.clients.jedis.params.RestoreParams; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.SortingParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.Response; + +public interface KeyPipelineCommands { + + Response exists(String key); + + Response exists(String... keys); + + Response persist(String key); + + Response type(String key); + + Response dump(String key); + + Response restore(String key, long ttl, byte[] serializedValue); + + Response restore(String key, long ttl, byte[] serializedValue, RestoreParams params); + + Response expire(String key, long seconds); + + Response pexpire(String key, long milliseconds); + + Response expireAt(String key, long unixTime); + + Response pexpireAt(String key, long millisecondsTimestamp); + + Response ttl(String key); + + Response pttl(String key); + + Response touch(String key); + + Response touch(String... keys); + + Response> sort(String key); + + Response sort(String key, String dstkey); + + Response> sort(String key, SortingParams sortingParameters); + + Response sort(String key, SortingParams sortingParameters, String dstkey); + + Response del(String key); + + Response del(String... keys); + + Response unlink(String key); + + Response unlink(String... keys); + + Response copy(String srcKey, String dstKey, boolean replace); + + Response rename(String oldkey, String newkey); + + Response renamenx(String oldkey, String newkey); + + Response memoryUsage(String key); + + Response memoryUsage(String key, int samples); + + Response objectRefcount(String key); + + Response objectEncoding(String key); + + Response objectIdletime(String key); + + Response objectFreq(String key); + + Response migrate(String host, int port, String key, int timeout); + + Response migrate(String host, int port, int timeout, MigrateParams params, String... keys); + + Response> keys(String pattern); + + Response> scan(String cursor); + + Response> scan(String cursor, ScanParams params); + + Response> scan(String cursor, ScanParams params, String type); + + Response randomKey(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ListBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/ListBinaryCommands.java new file mode 100644 index 0000000000..6052a0ee18 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ListBinaryCommands.java @@ -0,0 +1,63 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +import redis.clients.jedis.args.ListDirection; +import redis.clients.jedis.args.ListPosition; +import redis.clients.jedis.params.LPosParams; + +public interface ListBinaryCommands { + + long rpush(byte[] key, byte[]... args); + + long lpush(byte[] key, byte[]... args); + + long llen(byte[] key); + + List lrange(byte[] key, long start, long stop); + + String ltrim(byte[] key, long start, long stop); + + byte[] lindex(byte[] key, long index); + + String lset(byte[] key, long index, byte[] value); + + long lrem(byte[] key, long count, byte[] value); + + byte[] lpop(byte[] key); + + List lpop(byte[] key, int count); + + Long lpos(byte[] key, byte[] element); + + Long lpos(byte[] key, byte[] element, LPosParams params); + + List lpos(byte[] key, byte[] element, LPosParams params, long count); + + byte[] rpop(byte[] key); + + List rpop(byte[] key, int count); + + long linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value); + + long lpushx(byte[] key, byte[]... arg); + + long rpushx(byte[] key, byte[]... arg); + + List blpop(int timeout, byte[]... keys); + + List blpop(double timeout, byte[]... keys); + + List brpop(int timeout, byte[]... keys); + + List brpop(double timeout, byte[]... keys); + + byte[] rpoplpush(byte[] srckey, byte[] dstkey); + + byte[] brpoplpush(byte[] source, byte[] destination, int timeout); + + byte[] lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to); + + byte[] blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ListCommands.java b/src/main/java/redis/clients/jedis/commands/ListCommands.java new file mode 100644 index 0000000000..64273ec12c --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ListCommands.java @@ -0,0 +1,72 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +import redis.clients.jedis.args.ListDirection; +import redis.clients.jedis.args.ListPosition; +import redis.clients.jedis.params.LPosParams; +import redis.clients.jedis.resps.KeyedListElement; + +public interface ListCommands { + + long rpush(String key, String... string); + + long lpush(String key, String... string); + + long llen(String key); + + List lrange(String key, long start, long stop); + + String ltrim(String key, long start, long stop); + + String lindex(String key, long index); + + String lset(String key, long index, String value); + + long lrem(String key, long count, String value); + + String lpop(String key); + + List lpop(String key, int count); + + Long lpos(String key, String element); + + Long lpos(String key, String element, LPosParams params); + + List lpos(String key, String element, LPosParams params, long count); + + String rpop(String key); + + List rpop(String key, int count); + + long linsert(String key, ListPosition where, String pivot, String value); + + long lpushx(String key, String... string); + + long rpushx(String key, String... string); + + List blpop(int timeout, String key); + + KeyedListElement blpop(double timeout, String key); + + List brpop(int timeout, String key); + + KeyedListElement brpop(double timeout, String key); + + List blpop(int timeout, String... keys); + + KeyedListElement blpop(double timeout, String... keys); + + List brpop(int timeout, String... keys); + + KeyedListElement brpop(double timeout, String... keys); + + String rpoplpush(String srckey, String dstkey); + + String brpoplpush(String source, String destination, int timeout); + + String lmove(String srcKey, String dstKey, ListDirection from, ListDirection to); + + String blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ListPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/ListPipelineBinaryCommands.java new file mode 100644 index 0000000000..8a50313f4f --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ListPipelineBinaryCommands.java @@ -0,0 +1,64 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +import redis.clients.jedis.Response; +import redis.clients.jedis.args.ListDirection; +import redis.clients.jedis.args.ListPosition; +import redis.clients.jedis.params.LPosParams; + +public interface ListPipelineBinaryCommands { + + Response rpush(byte[] key, byte[]... args); + + Response lpush(byte[] key, byte[]... args); + + Response llen(byte[] key); + + Response> lrange(byte[] key, long start, long stop); + + Response ltrim(byte[] key, long start, long stop); + + Response lindex(byte[] key, long index); + + Response lset(byte[] key, long index, byte[] value); + + Response lrem(byte[] key, long count, byte[] value); + + Response lpop(byte[] key); + + Response> lpop(byte[] key, int count); + + Response lpos(byte[] key, byte[] element); + + Response lpos(byte[] key, byte[] element, LPosParams params); + + Response> lpos(byte[] key, byte[] element, LPosParams params, long count); + + Response rpop(byte[] key); + + Response> rpop(byte[] key, int count); + + Response linsert(byte[] key, ListPosition where, byte[] pivot, byte[] value); + + Response lpushx(byte[] key, byte[]... arg); + + Response rpushx(byte[] key, byte[]... arg); + + Response> blpop(int timeout, byte[]... keys); + + Response> blpop(double timeout, byte[]... keys); + + Response> brpop(int timeout, byte[]... keys); + + Response> brpop(double timeout, byte[]... keys); + + Response rpoplpush(byte[] srckey, byte[] dstkey); + + Response brpoplpush(byte[] source, byte[] destination, int timeout); + + Response lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to); + + Response blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ListPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/ListPipelineCommands.java new file mode 100644 index 0000000000..8853b484e7 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ListPipelineCommands.java @@ -0,0 +1,73 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +import redis.clients.jedis.Response; +import redis.clients.jedis.args.ListDirection; +import redis.clients.jedis.args.ListPosition; +import redis.clients.jedis.params.LPosParams; +import redis.clients.jedis.resps.KeyedListElement; + +public interface ListPipelineCommands { + + Response rpush(String key, String... string); + + Response lpush(String key, String... string); + + Response llen(String key); + + Response> lrange(String key, long start, long stop); + + Response ltrim(String key, long start, long stop); + + Response lindex(String key, long index); + + Response lset(String key, long index, String value); + + Response lrem(String key, long count, String value); + + Response lpop(String key); + + Response> lpop(String key, int count); + + Response lpos(String key, String element); + + Response lpos(String key, String element, LPosParams params); + + Response> lpos(String key, String element, LPosParams params, long count); + + Response rpop(String key); + + Response> rpop(String key, int count); + + Response linsert(String key, ListPosition where, String pivot, String value); + + Response lpushx(String key, String... string); + + Response rpushx(String key, String... string); + + Response> blpop(int timeout, String key); + + Response blpop(double timeout, String key); + + Response> brpop(int timeout, String key); + + Response brpop(double timeout, String key); + + Response> blpop(int timeout, String... keys); + + Response blpop(double timeout, String... keys); + + Response> brpop(int timeout, String... keys); + + Response brpop(double timeout, String... keys); + + Response rpoplpush(String srckey, String dstkey); + + Response brpoplpush(String source, String destination, int timeout); + + Response lmove(String srcKey, String dstKey, ListDirection from, ListDirection to); + + Response blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ModuleCommands.java b/src/main/java/redis/clients/jedis/commands/ModuleCommands.java index 762eee2125..82c2bb213f 100644 --- a/src/main/java/redis/clients/jedis/commands/ModuleCommands.java +++ b/src/main/java/redis/clients/jedis/commands/ModuleCommands.java @@ -1,8 +1,7 @@ package redis.clients.jedis.commands; -import redis.clients.jedis.Module; - import java.util.List; +import redis.clients.jedis.Module; public interface ModuleCommands { diff --git a/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryCommands.java deleted file mode 100644 index 72f575fec0..0000000000 --- a/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryCommands.java +++ /dev/null @@ -1,166 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.BinaryJedisPubSub; -import redis.clients.jedis.BitOP; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.Response; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.resps.LCSMatchResult; -import redis.clients.jedis.ZParams; -import redis.clients.jedis.args.*; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GeoRadiusStoreParam; -import redis.clients.jedis.params.XReadGroupParams; -import redis.clients.jedis.params.XReadParams; -import redis.clients.jedis.params.StrAlgoLCSParams; - -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -public interface MultiKeyBinaryCommands { - - boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace); - - boolean copy(byte[] srcKey, byte[] dstKey, boolean replace); - - long del(byte[]... keys); - - long unlink(byte[]... keys); - - long exists(byte[]... keys); - - byte[] lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to); - - byte[] blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout); - - List blpop(int timeout, byte[]... keys); - - List blpop(double timeout, byte[]... keys); - - List brpop(int timeout, byte[]... keys); - - List brpop(double timeout, byte[]... keys); - - List blpop(byte[]... args); - - List brpop(byte[]... args); - - List bzpopmax(double timeout, byte[]... keys); - - List bzpopmin(double timeout, byte[]... keys); - - Set keys(byte[] pattern); - - List mget(byte[]... keys); - - String mset(byte[]... keysvalues); - - long msetnx(byte[]... keysvalues); - - String rename(byte[] oldkey, byte[] newkey); - - long renamenx(byte[] oldkey, byte[] newkey); - - byte[] rpoplpush(byte[] srckey, byte[] dstkey); - - Set sdiff(byte[]... keys); - - long sdiffstore(byte[] dstkey, byte[]... keys); - - Set sinter(byte[]... keys); - - long sinterstore(byte[] dstkey, byte[]... keys); - - long smove(byte[] srckey, byte[] dstkey, byte[] member); - - long sort(byte[] key, SortingParams sortingParameters, byte[] dstkey); - - long sort(byte[] key, byte[] dstkey); - - Set sunion(byte[]... keys); - - long sunionstore(byte[] dstkey, byte[]... keys); - - String watch(byte[]... keys); - - String unwatch(); - - Set zdiff(byte[]... keys); - - Set zdiffWithScores(byte[]... keys); - - long zdiffStore(byte[] dstkey, byte[]... keys); - - Set zinter(ZParams params, byte[]... keys); - - Set zinterWithScores(ZParams params, byte[]... keys); - - long zinterstore(byte[] dstkey, byte[]... sets); - - long zinterstore(byte[] dstkey, ZParams params, byte[]... sets); - - Set zunion(ZParams params, byte[]... keys); - - Set zunionWithScores(ZParams params, byte[]... keys); - - long zunionstore(byte[] dstkey, byte[]... sets); - - long zunionstore(byte[] dstkey, ZParams params, byte[]... sets); - - byte[] brpoplpush(byte[] source, byte[] destination, int timeout); - - Long publish(byte[] channel, byte[] message); - - void subscribe(BinaryJedisPubSub jedisPubSub, byte[]... channels); - - void psubscribe(BinaryJedisPubSub jedisPubSub, byte[]... patterns); - - byte[] randomBinaryKey(); - - long bitop(BitOP op, byte[] destKey, byte[]... srcKeys); - - String pfmerge(byte[] destkey, byte[]... sourcekeys); - - long pfcount(byte[]... keys); - - long touch(byte[]... keys); - - ScanResult scan(byte[] cursor); - - ScanResult scan(byte[] cursor, ScanParams params); - - ScanResult scan(byte[] cursor, ScanParams params, byte[] type); - - /** - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link #xread(redis.clients.jedis.params.XReadParams, java.util.Map.Entry...)}. - */ - @Deprecated - List xread(int count, long block, Map streams); - - List xread(XReadParams xReadParams, Entry... streams); - - /** - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link MultiKeyBinaryCommands#xreadGroup(byte..., byte..., redis.clients.jedis.params.XReadGroupParams, java.util.Map.Entry...)}. - */ - @Deprecated - List xreadGroup(byte[] groupname, byte[] consumer, int count, long block, boolean noAck, - Map streams); - - List xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, - Entry... streams); - - long georadiusStore(byte[] key, double longitude, double latitude, double radius, GeoUnit unit, - GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - long georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, - GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - LCSMatchResult strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java b/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java deleted file mode 100644 index 77514b0112..0000000000 --- a/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryJedisClusterCommands.java +++ /dev/null @@ -1,65 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.ScanResult; - -import java.util.List; - -/** - * @deprecated This interface will be removed in future. Use {@link MultiKeyBinaryCommands}. - */ -@Deprecated -public interface MultiKeyBinaryJedisClusterCommands extends MultiKeyBinaryCommands { - - /** - * @throws UnsupportedOperationException Use {@link #copy(byte[], byte[], boolean)}. - */ - @Override - default boolean copy(byte[] srcKey, byte[] dstKey, int db, boolean replace) { - throw new UnsupportedOperationException("Cluster mode does not support databse operations."); - } - - /** - * @throws UnsupportedOperationException Use - * {@link MultiKeyBinaryCommands#blpop(double, byte[]...)} or - * {@link MultiKeyBinaryCommands#blpop(int, byte[]...)}. - */ - @Override - default List blpop(byte[]... args) { - throw new UnsupportedOperationException("Use other versions of BLPOP."); - } - - /** - * @throws UnsupportedOperationException Use - * {@link MultiKeyBinaryCommands#brpop(double, byte[]...)} or - * {@link MultiKeyBinaryCommands#brpop(int, byte[]...)}. - */ - @Override - default List brpop(byte[]... args) { - throw new UnsupportedOperationException("Use other versions of BRPOP"); - } - - /** - * @throws UnsupportedOperationException - */ - @Override - default String watch(byte[]... keys) { - throw new UnsupportedOperationException("WATCH in cluster mode is not supported yet."); - } - - /** - * @throws UnsupportedOperationException - */ - @Override - default byte[] randomBinaryKey() { - throw new UnsupportedOperationException("RANDOMKEY in cluster mode is not supproted yet."); - } - - /** - * @throws UnsupportedOperationException Use - * {@link MultiKeyBinaryCommands#scan(byte[], redis.clients.jedis.ScanParams)}. - */ - @Override - default ScanResult scan(byte[] cursor) { - throw new UnsupportedOperationException("Cluster mode only supports SCAN commands with MATCH patterns containing hash-tags"); - } -} diff --git a/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java b/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java deleted file mode 100644 index 6cd11b17c1..0000000000 --- a/src/main/java/redis/clients/jedis/commands/MultiKeyBinaryRedisPipeline.java +++ /dev/null @@ -1,146 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.BitOP; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.Response; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.resps.LCSMatchResult; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.ZParams; -import redis.clients.jedis.args.*; -import redis.clients.jedis.params.*; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Multikey related commands (these are split out because they are non-shardable) - */ -public interface MultiKeyBinaryRedisPipeline { - Response copy(byte[] srcKey, byte[] dstKey, int db, boolean replace); - - Response copy(byte[] srcKey, byte[] dstKey, boolean replace); - - Response del(byte[]... keys); - - Response unlink(byte[]... keys); - - Response exists(byte[]... keys); - - Response lmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to); - - Response blmove(byte[] srcKey, byte[] dstKey, ListDirection from, ListDirection to, double timeout); - - Response> blpop(byte[]... args); - - Response> blpop(double timeout, byte[]... args); - - Response> brpop(byte[]... args); - - Response> brpop(double timeout, byte[]... args); - - Response> bzpopmax(double timeout, byte[]... keys); - - Response> bzpopmin(double timeout, byte[]... keys); - - Response> keys(byte[] pattern); - - Response> mget(byte[]... keys); - - Response mset(byte[]... keysvalues); - - Response msetnx(byte[]... keysvalues); - - Response rename(byte[] oldkey, byte[] newkey); - - Response renamenx(byte[] oldkey, byte[] newkey); - - Response rpoplpush(byte[] srckey, byte[] dstkey); - - Response> sdiff(byte[]... keys); - - Response sdiffstore(byte[] dstkey, byte[]... keys); - - Response> sinter(byte[]... keys); - - Response sinterstore(byte[] dstkey, byte[]... keys); - - Response smove(byte[] srckey, byte[] dstkey, byte[] member); - - Response sort(byte[] key, SortingParams sortingParameters, byte[] dstkey); - - Response sort(byte[] key, byte[] dstkey); - - Response> sunion(byte[]... keys); - - Response sunionstore(byte[] dstkey, byte[]... keys); - - Response unwatch(); - - Response> zdiff(byte[]... keys); - - Response> zdiffWithScores(byte[]... keys); - - Response zdiffStore(byte[] dstkey, byte[]... keys); - - Response> zinter(ZParams params, byte[]... keys); - - Response> zinterWithScores(ZParams params, byte[]... keys); - - Response zinterstore(byte[] dstkey, byte[]... sets); - - Response zinterstore(byte[] dstkey, ZParams params, byte[]... sets); - - Response> zunion(ZParams params, byte[]... keys); - - Response> zunionWithScores(ZParams params, byte[]... keys); - - Response zunionstore(byte[] dstkey, byte[]... sets); - - Response zunionstore(byte[] dstkey, ZParams params, byte[]... sets); - - Response brpoplpush(byte[] source, byte[] destination, int timeout); - - Response publish(byte[] channel, byte[] message); - - Response randomKeyBinary(); - - Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys); - - Response pfmerge(byte[] destkey, byte[]... sourcekeys); - - Response pfcount(byte[]... keys); - - Response touch(byte[]... keys); - - Response migrate(String host, int port, int destinationDB, int timeout, - MigrateParams params, byte[]... keys); - - Response georadiusStore(byte[] key, double longitude, double latitude, double radius, - GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - Response georadiusByMemberStore(byte[] key, byte[] member, double radius, GeoUnit unit, - GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - /** - * @deprecated Use {@link #xread(redis.clients.jedis.params.XReadParams, java.util.Map.Entry...)}. - */ - @Deprecated - Response> xread(int count, long block, Map streams); - - Response> xread(XReadParams xReadParams, Map.Entry... streams); - - /** - * @deprecated Use {@link MultiKeyBinaryRedisPipeline#xreadGroup(byte..., byte..., - * redis.clients.jedis.params.XReadGroupParams, java.util.Map.Entry...)}. - */ - @Deprecated - Response> xreadGroup(byte[] groupname, byte[] consumer, int count, long block, - boolean noAck, Map streams); - - Response> xreadGroup(byte[] groupname, byte[] consumer, - XReadGroupParams xReadGroupParams, Map.Entry... streams); - - Response strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/MultiKeyCommands.java b/src/main/java/redis/clients/jedis/commands/MultiKeyCommands.java deleted file mode 100644 index 0256f36eeb..0000000000 --- a/src/main/java/redis/clients/jedis/commands/MultiKeyCommands.java +++ /dev/null @@ -1,263 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.BitOP; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.resps.KeyedZSetElement; -import redis.clients.jedis.StreamEntryID; -import redis.clients.jedis.JedisPubSub; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.StreamEntry; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.ZParams; -import redis.clients.jedis.args.*; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GeoRadiusStoreParam; -import redis.clients.jedis.params.XReadGroupParams; -import redis.clients.jedis.params.XReadParams; -import redis.clients.jedis.resps.*; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -public interface MultiKeyCommands { - - boolean copy(String srcKey, String dstKey, int db, boolean replace); - - boolean copy(String srcKey, String dstKey, boolean replace); - - long del(String... keys); - - long unlink(String... keys); - - long exists(String... keys); - - String lmove(String srcKey, String dstKey, ListDirection from, ListDirection to); - - String blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, double timeout); - - List blpop(int timeout, String... keys); - - KeyedListElement blpop(double timeout, String... keys); - - List brpop(int timeout, String... keys); - - KeyedListElement brpop(double timeout, String... keys); - - List blpop(String... args); - - List brpop(String... args); - - KeyedZSetElement bzpopmax(double timeout, String... keys); - - KeyedZSetElement bzpopmin(double timeout, String... keys); - - /** - * Returns all the keys matching the glob-style pattern. For example if you have in the database - * the keys "foo" and "foobar" the command "KEYS foo*" will return "foo foobar".
- * Warning: consider this as a command that should be used in production - * environments with extreme care. It may ruin performance when it is executed - * against large databases. This command is intended for debugging and special operations, such as - * changing your keyspace layout. Don't use it in your regular application code. - * If you're looking for a way to find keys in a subset of your keyspace, consider using - * {@link #scan(String, ScanParams)} or sets. - *

- * While the time complexity for this operation is O(N), the constant times are fairly low. For - * example, Redis running on an entry level laptop can scan a 1 million key database in 40 - * milliseconds. - *

- * Glob style patterns examples: - *

    - *
  • h?llo will match hello hallo hhllo - *
  • h*llo will match hllo heeeello - *
  • h[ae]llo will match hello and hallo, but not hillo - *
- *

- * Use \ to escape special chars if you want to match them verbatim. - *

- * Time complexity: O(n) (with n being the number of keys in the DB, and assuming keys and pattern - * of limited length) - * @param pattern - * @return Multi bulk reply - * @see Redis KEYS documentation - */ - Set keys(String pattern); - - List mget(String... keys); - - String mset(String... keysvalues); - - long msetnx(String... keysvalues); - - String rename(String oldkey, String newkey); - - long renamenx(String oldkey, String newkey); - - String rpoplpush(String srckey, String dstkey); - - Set sdiff(String... keys); - - long sdiffstore(String dstkey, String... keys); - - Set sinter(String... keys); - - long sinterstore(String dstkey, String... keys); - - long smove(String srckey, String dstkey, String member); - - long sort(String key, SortingParams sortingParameters, String dstkey); - - long sort(String key, String dstkey); - - Set sunion(String... keys); - - long sunionstore(String dstkey, String... keys); - - String watch(String... keys); - - String unwatch(); - - Set zdiff(String... keys); - - Set zdiffWithScores(String... keys); - - long zdiffStore(String dstkey, String... keys); - - long zinterstore(String dstkey, String... sets); - - long zinterstore(String dstkey, ZParams params, String... sets); - - Set zinter(ZParams params, String... keys); - - Set zinterWithScores(ZParams params, String... keys); - - Set zunion(ZParams params, String... keys); - - Set zunionWithScores(ZParams params, String... keys); - - long zunionstore(String dstkey, String... sets); - - long zunionstore(String dstkey, ZParams params, String... sets); - - String brpoplpush(String source, String destination, int timeout); - - Long publish(String channel, String message); - - void subscribe(JedisPubSub jedisPubSub, String... channels); - - void psubscribe(JedisPubSub jedisPubSub, String... patterns); - - String randomKey(); - - long bitop(BitOP op, String destKey, String... srcKeys); - - /** - * @see #scan(String, ScanParams) - * - * @param cursor - * @return result - */ - ScanResult scan(String cursor); - - /** - * Iterates the set of keys in the currently selected Redis database. - *

- * Since this command allows for incremental iteration, returning only a small number of elements - * per call, it can be used in production without the downside of commands like - * {@link #keys(String)} or {@link JedisCommands#smembers(String)} )} that may block the server - * for a long time (even several seconds) when called against big collections of keys or elements. - *

- * SCAN basic usage
- * SCAN is a cursor based iterator. This means that at every call of the command, the server - * returns an updated cursor that the user needs to use as the cursor argument in the next call. - * An iteration starts when the cursor is set to 0, and terminates when the cursor returned by the - * server is 0. - *

- * Scan guarantees
- * The SCAN command, and the other commands in the SCAN family, are able to provide to the user a - * set of guarantees associated to full iterations. - *

    - *
  • A full iteration always retrieves all the elements that were present in the collection from - * the start to the end of a full iteration. This means that if a given element is inside the - * collection when an iteration is started, and is still there when an iteration terminates, then - * at some point SCAN returned it to the user. - *
  • A full iteration never returns any element that was NOT present in the collection from the - * start to the end of a full iteration. So if an element was removed before the start of an - * iteration, and is never added back to the collection for all the time an iteration lasts, SCAN - * ensures that this element will never be returned. - *
- * However because SCAN has very little state associated (just the cursor) it has the following - * drawbacks: - *
    - *
  • A given element may be returned multiple times. It is up to the application to handle the - * case of duplicated elements, for example only using the returned elements in order to perform - * operations that are safe when re-applied multiple times. - *
  • Elements that were not constantly present in the collection during a full iteration, may be - * returned or not: it is undefined. - *
- *

- * Time complexity: O(1) for every call. O(N) for a complete iteration, including enough command - * calls for the cursor to return back to 0. N is the number of elements inside the DB. - * @param cursor The cursor. - * @param params the scan parameters. For example a glob-style match pattern - * @return the scan result with the results of this iteration and the new position of the cursor - * @see Redis SCAN documentation - */ - ScanResult scan(String cursor, ScanParams params); - - ScanResult scan(String cursor, ScanParams params, String type); - - String pfmerge(String destkey, String... sourcekeys); - - long pfcount(String... keys); - - long touch(String... keys); - - /** - * XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] - * - * @param count - * @param block - * @param streams - * @return - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link MultiKeyCommands#xread(redis.clients.jedis.params.XReadParams, java.util.Map)}. - */ - @Deprecated - List>> xread(int count, long block, - Map.Entry... streams); - - List>> xread(XReadParams xReadParams, - Map streams); - - /** - * XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] - * - * @param groupname - * @param consumer - * @param count - * @param block - * @param noAck - * @param streams - * @return - * @deprecated This method will be removed due to bug regarding {@code block} param. Use - * {@link #xreadGroup(java.lang.String, java.lang.String, redis.clients.jedis.params.XReadGroupParams, java.util.Map)}. - */ - @Deprecated - List>> xreadGroup(String groupname, String consumer, - int count, long block, boolean noAck, Map.Entry... streams); - - List>> xreadGroup(String groupname, String consumer, - XReadGroupParams xReadGroupParams, Map streams); - - long georadiusStore(String key, double longitude, double latitude, double radius, GeoUnit unit, - GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - long georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, - GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - LCSMatchResult strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java b/src/main/java/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java deleted file mode 100644 index a3039e173c..0000000000 --- a/src/main/java/redis/clients/jedis/commands/MultiKeyCommandsPipeline.java +++ /dev/null @@ -1,154 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.BitOP; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.Response; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.StreamEntry; -import redis.clients.jedis.StreamEntryID; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.ZParams; -import redis.clients.jedis.args.*; -import redis.clients.jedis.params.*; -import redis.clients.jedis.resps.*; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Multikey related commands (these are split out because they are non-shardable) - */ -public interface MultiKeyCommandsPipeline { - Response copy(String srcKey, String dstKey, int db, boolean replace); - - Response copy(String srcKey, String dstKey, boolean replace); - - Response del(String... keys); - - Response unlink(String... keys); - - Response exists(String... keys); - - Response lmove(String srcKey, String dstKey, ListDirection from, ListDirection to); - - Response blmove(String srcKey, String dstKey, ListDirection from, ListDirection to, - double timeout); - - Response> blpop(String... args); - - Response> blpop(int timeout, String... args); - - Response blpop(double timeout, String... args); - - Response> brpop(String... args); - - Response> brpop(int timeout, String... args); - - Response brpop(double timeout, String... args); - - Response bzpopmax(double timeout, String... keys); - - Response bzpopmin(double timeout, String... keys); - - Response> keys(String pattern); - - Response> mget(String... keys); - - Response mset(String... keysvalues); - - Response msetnx(String... keysvalues); - - Response rename(String oldkey, String newkey); - - Response renamenx(String oldkey, String newkey); - - Response rpoplpush(String srckey, String dstkey); - - Response> sdiff(String... keys); - - Response sdiffstore(String dstkey, String... keys); - - Response> sinter(String... keys); - - Response sinterstore(String dstkey, String... keys); - - Response smove(String srckey, String dstkey, String member); - - Response sort(String key, SortingParams sortingParameters, String dstkey); - - Response sort(String key, String dstkey); - - Response> sunion(String... keys); - - Response sunionstore(String dstkey, String... keys); - - Response unwatch(); - - Response> zdiff(String... keys); - - Response> zdiffWithScores(String... keys); - - Response zdiffStore(String dstkey, String... keys); - - Response> zinter(ZParams params, String... keys); - - Response> zinterWithScores(ZParams params, String... keys); - - Response zinterstore(String dstkey, String... sets); - - Response zinterstore(String dstkey, ZParams params, String... sets); - - Response> zunion(ZParams params, String... keys); - - Response> zunionWithScores(ZParams params, String... keys); - - Response zunionstore(String dstkey, String... sets); - - Response zunionstore(String dstkey, ZParams params, String... sets); - - Response brpoplpush(String source, String destination, int timeout); - - Response publish(String channel, String message); - - Response randomKey(); - - Response bitop(BitOP op, String destKey, String... srcKeys); - - Response pfmerge(String destkey, String... sourcekeys); - - Response pfcount(String... keys); - - Response touch(String... keys); - - Response migrate(String host, int port, int destinationDB, int timeout, - MigrateParams params, String... keys); - - Response georadiusStore(String key, double longitude, double latitude, double radius, - GeoUnit unit, GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - Response georadiusByMemberStore(String key, String member, double radius, GeoUnit unit, - GeoRadiusParam param, GeoRadiusStoreParam storeParam); - - /** - * @deprecated Use {@link #xread(redis.clients.jedis.params.XReadParams, java.util.Map)}. - */ - @Deprecated - Response>>> xread(int count, long block, - Map.Entry... streams); - - Response>>> xread(XReadParams xReadParams, - Map streams); - - /** - * @deprecated Use {@link #xreadGroup(java.lang.String, java.lang.String, redis.clients.jedis.params.XReadGroupParams, java.util.Map)}. - */ - @Deprecated - Response>>> xreadGroup(String groupname, String consumer, - int count, long block, boolean noAck, Map.Entry... streams); - - Response>>> xreadGroup(String groupname, String consumer, - XReadGroupParams xReadGroupParams, Map streams); - - Response strAlgoLCSKeys(final String keyA, final String keyB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java b/src/main/java/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java deleted file mode 100644 index 5b2639415a..0000000000 --- a/src/main/java/redis/clients/jedis/commands/MultiKeyJedisClusterCommands.java +++ /dev/null @@ -1,62 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.ScanResult; - -import java.util.List; - -/** - * @deprecated This interface will be removed in future. Use {@link MultiKeyCommands}. - */ -@Deprecated -public interface MultiKeyJedisClusterCommands extends MultiKeyCommands { - - /** - * @throws UnsupportedOperationException Use {@link #copy(java.lang.String, java.lang.String, boolean)}. - */ - @Override - default boolean copy(String srcKey, String dstKey, int db, boolean replace) { - throw new UnsupportedOperationException("Cluster mode does not support databse operations."); - } - - /** - * @throws UnsupportedOperationException Use {@link #blpop(double, java.lang.String...)} or - * {@link #blpop(int, java.lang.String...)}. - */ - @Override - default List blpop(String... args) { - throw new UnsupportedOperationException("Use other versions of BLPOP."); - } - - /** - * @throws UnsupportedOperationException Use {@link #brpop(double, java.lang.String...)} or - * {@link #brpop(int, java.lang.String...)}. - */ - @Override - default List brpop(String... args) { - throw new UnsupportedOperationException("Use other versions of BRPOP"); - } - - /** - * @throws UnsupportedOperationException - */ - @Override - default String watch(String... keys) { - throw new UnsupportedOperationException("WATCH in cluster mode is not supproted yet."); - } - - /** - * @throws UnsupportedOperationException - */ - @Override - default String randomKey() { - throw new UnsupportedOperationException("RANDOMKEY in cluster mode is not supproted yet."); - } - - /** - * @throws UnsupportedOperationException Use {@link #scan(String, redis.clients.jedis.ScanParams)}. - */ - @Override - default ScanResult scan(String cursor) { - throw new UnsupportedOperationException("Cluster mode only supports SCAN commands with MATCH patterns containing hash-tags."); - } -} diff --git a/src/main/java/redis/clients/jedis/commands/PipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/PipelineBinaryCommands.java new file mode 100644 index 0000000000..ca379d7598 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/PipelineBinaryCommands.java @@ -0,0 +1,8 @@ +package redis.clients.jedis.commands; + +public interface PipelineBinaryCommands extends KeyPipelineBinaryCommands, + StringPipelineBinaryCommands, ListPipelineBinaryCommands, HashPipelineBinaryCommands, + SetPipelineBinaryCommands, SortedSetPipelineBinaryCommands, GeoPipelineBinaryCommands, + HyperLogLogPipelineBinaryCommands, StreamPipelineBinaryCommands, + ScriptingKeyPipelineBinaryCommands, SampleBinaryKeyedPipelineCommands { +} diff --git a/src/main/java/redis/clients/jedis/commands/PipelineCommands.java b/src/main/java/redis/clients/jedis/commands/PipelineCommands.java new file mode 100644 index 0000000000..29429ff0d0 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/PipelineCommands.java @@ -0,0 +1,7 @@ +package redis.clients.jedis.commands; + +public interface PipelineCommands extends KeyPipelineCommands, StringPipelineCommands, + ListPipelineCommands, HashPipelineCommands, SetPipelineCommands, SortedSetPipelineCommands, + GeoPipelineCommands, HyperLogLogPipelineCommands, StreamPipelineCommands, + ScriptingKeyPipelineCommands, SampleKeyedPipelineCommands { +} diff --git a/src/main/java/redis/clients/jedis/commands/RedisModuleCommands.java b/src/main/java/redis/clients/jedis/commands/RedisModuleCommands.java new file mode 100644 index 0000000000..f06ba9f047 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/RedisModuleCommands.java @@ -0,0 +1,7 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.json.RedisJsonCommands; +import redis.clients.jedis.search.RediSearchCommands; + +public interface RedisModuleCommands extends RediSearchCommands, RedisJsonCommands { +} diff --git a/src/main/java/redis/clients/jedis/commands/RedisModulePipelineCommands.java b/src/main/java/redis/clients/jedis/commands/RedisModulePipelineCommands.java new file mode 100644 index 0000000000..21956fb37e --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/RedisModulePipelineCommands.java @@ -0,0 +1,7 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.json.RedisJsonPipelineCommands; +import redis.clients.jedis.search.RediSearchPipelineCommands; + +public interface RedisModulePipelineCommands extends RediSearchPipelineCommands, RedisJsonPipelineCommands { +} diff --git a/src/main/java/redis/clients/jedis/commands/RedisPipeline.java b/src/main/java/redis/clients/jedis/commands/RedisPipeline.java deleted file mode 100644 index d9cd1e87e6..0000000000 --- a/src/main/java/redis/clients/jedis/commands/RedisPipeline.java +++ /dev/null @@ -1,473 +0,0 @@ -package redis.clients.jedis.commands; - -import redis.clients.jedis.StreamEntryID; -import redis.clients.jedis.BitPosParams; -import redis.clients.jedis.GeoCoordinate; -import redis.clients.jedis.GeoRadiusResponse; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.ListPosition; -import redis.clients.jedis.StreamPendingEntry; -import redis.clients.jedis.Response; -import redis.clients.jedis.SortingParams; -import redis.clients.jedis.StreamEntry; -import redis.clients.jedis.StreamPendingSummary; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.params.GeoAddParams; -import redis.clients.jedis.params.GeoRadiusParam; -import redis.clients.jedis.params.GetExParams; -import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.params.SetParams; -import redis.clients.jedis.params.StrAlgoLCSParams; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XTrimParams; -import redis.clients.jedis.params.ZAddParams; -import redis.clients.jedis.params.ZIncrByParams; -import redis.clients.jedis.params.LPosParams; -import redis.clients.jedis.resps.LCSMatchResult; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -public interface RedisPipeline { - Response append(String key, String value); - - Response> blpop(String arg); - - Response> brpop(String arg); - - Response decr(String key); - - Response decrBy(String key, long decrement); - - Response del(String key); - - Response unlink(String key); - - Response echo(String string); - - Response exists(String key); - - /** - * @deprecated Use {@link #expire(java.lang.String, long)}. - */ - @Deprecated - default Response expire(String key, int seconds) { - return expire(key, (long) seconds); - } - - Response expire(String key, long seconds); - - Response pexpire(String key, long milliseconds); - - Response expireAt(String key, long unixTime); - - Response pexpireAt(String key, long millisecondsTimestamp); - - Response get(String key); - - Response getDel(String key); - - Response getEx(String key, GetExParams params); - - Response getbit(String key, long offset); - - Response getrange(String key, long startOffset, long endOffset); - - Response getSet(String key, String value); - - Response hdel(String key, String... field); - - Response hexists(String key, String field); - - Response hget(String key, String field); - - Response> hgetAll(String key); - - Response hincrBy(String key, String field, long value); - - Response> hkeys(String key); - - Response hlen(String key); - - Response> hmget(String key, String... fields); - - Response hmset(String key, Map hash); - - Response hset(String key, String field, String value); - - Response hset(String key, Map hash); - - Response hsetnx(String key, String field, String value); - - Response> hvals(String key); - - Response hrandfield(String key); - - Response> hrandfield(String key, long count); - - Response> hrandfieldWithValues(String key, long count); - - Response incr(String key); - - Response incrBy(String key, long increment); - - Response lindex(String key, long index); - - Response linsert(String key, ListPosition where, String pivot, String value); - - Response llen(String key); - - Response lpop(String key); - - Response> lpop(String key, int count); - - Response lpos(String key, String element); - - Response lpos(String key, String element, LPosParams params); - - Response> lpos(String key, String element, LPosParams params, long count); - - Response lpush(String key, String... string); - - Response lpushx(String key, String... string); - - Response> lrange(String key, long start, long stop); - - Response lrem(String key, long count, String value); - - Response lset(String key, long index, String value); - - Response ltrim(String key, long start, long stop); - - Response move(String key, int dbIndex); - - Response persist(String key); - - Response rpop(String key); - - Response> rpop(String key, int count); - - Response rpush(String key, String... string); - - Response rpushx(String key, String... string); - - Response sadd(String key, String... member); - - Response scard(String key); - - Response sismember(String key, String member); - - Response> smismember(String key, String... members); - - Response set(String key, String value); - - Response setbit(String key, long offset, boolean value); - - /** - * @deprecated Use {@link #setex(java.lang.String, long, java.lang.String)}. - */ - @Deprecated - default Response setex(String key, int seconds, String value) { - return setex(key, (long) seconds, value); - } - - Response setex(String key, long seconds, String value); - - Response setnx(String key, String value); - - Response setrange(String key, long offset, String value); - - Response> smembers(String key); - - Response> sort(String key); - - Response> sort(String key, SortingParams sortingParameters); - - Response spop(String key); - - Response> spop(String key, long count); - - Response srandmember(String key); - - Response srem(String key, String... member); - - Response strlen(String key); - - Response substr(String key, int start, int end); - - Response touch(String key); - - Response ttl(String key); - - Response pttl(String key); - - Response type(String key); - - Response zadd(String key, double score, String member); - - Response zadd(String key, double score, String member, ZAddParams params); - - Response zadd(String key, Map scoreMembers); - - Response zadd(String key, Map scoreMembers, ZAddParams params); - - Response zaddIncr(String key, double score, String member, ZAddParams params); - - Response zcard(String key); - - Response zcount(String key, double min, double max); - - Response zcount(String key, String min, String max); - - Response zincrby(String key, double increment, String member); - - Response zincrby(String key, double increment, String member, ZIncrByParams params); - - Response> zrange(String key, long start, long stop); - - Response> zrangeByScore(String key, double min, double max); - - Response> zrangeByScore(String key, String min, String max); - - Response> zrangeByScore(String key, double min, double max, int offset, int count); - - Response> zrangeByScore(String key, String min, String max, int offset, int count); - - Response> zrangeByScoreWithScores(String key, double min, double max); - - Response> zrangeByScoreWithScores(String key, double min, double max, int offset, int count); - - Response> zrevrangeByScore(String key, double max, double min); - - Response> zrevrangeByScore(String key, String max, String min); - - Response> zrevrangeByScore(String key, double max, double min, int offset, int count); - - Response> zrevrangeByScore(String key, String max, String min, int offset, int count); - - Response> zrevrangeByScoreWithScores(String key, double max, double min); - - Response> zrevrangeByScoreWithScores(String key, String max, String min); - - Response> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count); - - Response> zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count); - - Response> zrangeWithScores(String key, long start, long stop); - - Response zrandmember(String key); - - Response> zrandmember(String key, long count); - - Response> zrandmemberWithScores(String key, long count); - - Response zrank(String key, String member); - - Response zrem(String key, String... members); - - Response zremrangeByRank(String key, long start, long stop); - - Response zremrangeByScore(String key, double min, double max); - - Response zremrangeByScore(String key, String min, String max); - - Response> zrevrange(String key, long start, long stop); - - Response> zrevrangeWithScores(String key, long start, long stop); - - Response zrevrank(String key, String member); - - Response zscore(String key, String member); - - Response> zmscore(String key, String... members); - - Response zpopmax(String key); - - Response> zpopmax(String key, int count); - - Response zpopmin(String key); - - Response> zpopmin(String key, int count); - - Response zlexcount(String key, String min, String max); - - Response> zrangeByLex(String key, String min, String max); - - Response> zrangeByLex(String key, String min, String max, int offset, int count); - - Response> zrevrangeByLex(String key, String max, String min); - - Response> zrevrangeByLex(String key, String max, String min, int offset, int count); - - Response zremrangeByLex(String key, String min, String max); - - Response bitcount(String key); - - Response bitcount(String key, long start, long end); - - Response pfadd(String key, String... elements); - - Response pfcount(String key); - - Response> bitfield(String key, String... arguments); - - Response> bitfieldReadonly(String key, String... arguments); - - Response hstrlen(String key, String field); - - Response dump(String key); - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[])}. - */ - @Deprecated - default Response restore(String key, int ttl, byte[] serializedValue) { - return restore(key, (long) ttl, serializedValue); - } - - Response restore(String key, long ttl, byte[] serializedValue); - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - default Response restoreReplace(String key, int ttl, byte[] serializedValue) { - return restoreReplace(key, (long) ttl, serializedValue); - } - - /** - * @deprecated Use {@link #restore(java.lang.String, long, byte[], redis.clients.jedis.params.RestoreParams)}. - */ - @Deprecated - Response restoreReplace(String key, long ttl, byte[] serializedValue); - - Response restore(String key, long ttl, byte[] serializedValue, RestoreParams params); - - Response migrate(String host, int port, String key, int destinationDB, int timeout); - - // Geo Commands - - Response geoadd(String key, double longitude, double latitude, String member); - - Response geoadd(String key, Map memberCoordinateMap); - - Response geoadd(String key, GeoAddParams params, Map memberCoordinateMap); - - Response geodist(String key, String member1, String member2); - - Response geodist(String key, String member1, String member2, GeoUnit unit); - - Response> geohash(String key, String... members); - - Response> geopos(String key, String... members); - - Response> georadius(String key, double longitude, double latitude, - double radius, GeoUnit unit); - - Response> georadiusReadonly(String key, double longitude, double latitude, - double radius, GeoUnit unit); - - Response> georadius(String key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); - - Response> georadiusReadonly(String key, double longitude, double latitude, - double radius, GeoUnit unit, GeoRadiusParam param); - - Response> georadiusByMember(String key, String member, double radius, - GeoUnit unit); - - Response> georadiusByMemberReadonly(String key, String member, - double radius, GeoUnit unit); - - Response> georadiusByMember(String key, String member, double radius, - GeoUnit unit, GeoRadiusParam param); - - Response> georadiusByMemberReadonly(String key, String member, - double radius, GeoUnit unit, GeoRadiusParam param); - - Response xadd(String key, StreamEntryID id, Map hash); - - Response xadd(String key, StreamEntryID id, Map hash, long maxLen, boolean approximateLength); - - Response xadd(String key, Map hash, XAddParams params); - - Response xlen(String key); - - Response> xrange(String key, StreamEntryID start, StreamEntryID end); - - Response> xrange(String key, StreamEntryID start, StreamEntryID end, int count); - - Response> xrevrange(String key, StreamEntryID end, StreamEntryID start); - - Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count); - - Response xack(String key, String group, StreamEntryID... ids); - - Response xgroupCreate( String key, String groupname, StreamEntryID id, boolean makeStream); - - Response xgroupSetID( String key, String groupname, StreamEntryID id); - - Response xgroupDestroy( String key, String groupname); - - Response xgroupDelConsumer( String key, String groupname, String consumername); - - Response xpending(String key, String groupname); - - Response> xpending(String key, String groupname, - StreamEntryID start, StreamEntryID end, int count, String consumername); - - Response> xpending(String key, String groupname, XPendingParams params); - - Response xdel( String key, StreamEntryID... ids); - - Response xtrim( String key, long maxLen, boolean approximateLength); - - Response xtrim(String key, XTrimParams params); - - Response> xclaim( String key, String group, String consumername, long minIdleTime, - long newIdleTime, int retries, boolean force, StreamEntryID... ids); - - Response> xclaim(String key, String group, String consumername, - long minIdleTime, XClaimParams params, StreamEntryID... ids); - - Response> xclaimJustId(String key, String group, String consumername, - long minIdleTime, XClaimParams params, StreamEntryID... ids); - - Response>> xautoclaim(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params); - - Response>> xautoclaimJustId(String key, String group, String consumerName, - long minIdleTime, StreamEntryID start, XAutoClaimParams params); - - Response bitpos(String key, boolean value); - - Response bitpos(String key, boolean value, BitPosParams params); - - Response set(String key, String value, SetParams params); - - Response> srandmember(String key, int count); - - Response> zrangeByScoreWithScores(String key, String min, String max); - - Response> zrangeByScoreWithScores(String key, String min, String max, int offset, int count); - - Response objectRefcount(String key); - - Response objectEncoding(String key); - - Response objectIdletime(String key); - - Response objectFreq(String key); - - Response incrByFloat(String key, double increment); - - Response psetex(String key, long milliseconds, String value); - - Response hincrByFloat(String key, String field, double increment); - - Response strAlgoLCSStrings(final String strA, final String strB, final StrAlgoLCSParams params); -} diff --git a/src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedCommands.java b/src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedCommands.java new file mode 100644 index 0000000000..b0630cd7c5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedCommands.java @@ -0,0 +1,25 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.args.FlushMode; + +public interface SampleBinaryKeyedCommands { + + long waitReplicas(byte[] sampleKey, int replicas, long timeout); + + Object eval(byte[] script, byte[] sampleKey); + + Object evalsha(byte[] sha1, byte[] sampleKey); + + Boolean scriptExists(byte[] sha1, byte[] sampleKey); + + List scriptExists(byte[] sampleKey, byte[]... sha1s); + + byte[] scriptLoad(byte[] script, byte[] sampleKey); + + String scriptFlush(byte[] sampleKey); + + String scriptFlush(byte[] sampleKey, FlushMode flushMode); + + String scriptKill(byte[] sampleKey); +} diff --git a/src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedPipelineCommands.java new file mode 100644 index 0000000000..1ffcb123e7 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SampleBinaryKeyedPipelineCommands.java @@ -0,0 +1,26 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.Response; +import redis.clients.jedis.args.FlushMode; + +public interface SampleBinaryKeyedPipelineCommands { + + Response waitReplicas(byte[] sampleKey, int replicas, long timeout); + + Response eval(byte[] script, byte[] sampleKey); + + Response evalsha(byte[] sha1, byte[] sampleKey); +// +// Response scriptExists(byte[] sha1, byte[] sampleKey); + + Response> scriptExists(byte[] sampleKey, byte[]... sha1s); + + Response scriptLoad(byte[] script, byte[] sampleKey); + + Response scriptFlush(byte[] sampleKey); + + Response scriptFlush(byte[] sampleKey, FlushMode flushMode); + + Response scriptKill(byte[] sampleKey); +} diff --git a/src/main/java/redis/clients/jedis/commands/SampleKeyedCommands.java b/src/main/java/redis/clients/jedis/commands/SampleKeyedCommands.java new file mode 100644 index 0000000000..5a1831938b --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SampleKeyedCommands.java @@ -0,0 +1,25 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.args.FlushMode; + +public interface SampleKeyedCommands { + + long waitReplicas(String sampleKey, int replicas, long timeout); + + Object eval(String script, String sampleKey); + + Object evalsha(String sha1, String sampleKey); + + Boolean scriptExists(String sha1, String sampleKey); + + List scriptExists(String sampleKey, String... sha1s); + + String scriptLoad(String script, String sampleKey); + + String scriptFlush(String sampleKey); + + String scriptFlush(String sampleKey, FlushMode flushMode); + + String scriptKill(String sampleKey); +} diff --git a/src/main/java/redis/clients/jedis/commands/SampleKeyedPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/SampleKeyedPipelineCommands.java new file mode 100644 index 0000000000..94b89e0e96 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SampleKeyedPipelineCommands.java @@ -0,0 +1,26 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.Response; +import redis.clients.jedis.args.FlushMode; + +public interface SampleKeyedPipelineCommands { + + Response waitReplicas(String sampleKey, int replicas, long timeout); + + Response eval(String script, String sampleKey); + + Response evalsha(String sha1, String sampleKey); +// +// Response scriptExists(String sha1, String sampleKey); + + Response> scriptExists(String sampleKey, String... sha1); + + Response scriptLoad(String script, String sampleKey); + + Response scriptFlush(String sampleKey); + + Response scriptFlush(String sampleKey, FlushMode flushMode); + + Response scriptKill(String sampleKey); +} diff --git a/src/main/java/redis/clients/jedis/commands/ScriptingCommandsPipeline.java b/src/main/java/redis/clients/jedis/commands/ScriptingCommandsPipeline.java index 08f85f0336..65f4957d77 100644 --- a/src/main/java/redis/clients/jedis/commands/ScriptingCommandsPipeline.java +++ b/src/main/java/redis/clients/jedis/commands/ScriptingCommandsPipeline.java @@ -1,10 +1,10 @@ package redis.clients.jedis.commands; -import redis.clients.jedis.Response; - import java.util.List; +import redis.clients.jedis.Response; public interface ScriptingCommandsPipeline { + Response eval(String script, int keyCount, String... params); Response eval(String script, List keys, List args); diff --git a/src/main/java/redis/clients/jedis/commands/ScriptingControlCommands.java b/src/main/java/redis/clients/jedis/commands/ScriptingControlCommands.java new file mode 100644 index 0000000000..26d084782c --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ScriptingControlCommands.java @@ -0,0 +1,26 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.args.FlushMode; + +public interface ScriptingControlCommands { + + Boolean scriptExists(String sha1); + + List scriptExists(String... sha1); + + Boolean scriptExists(byte[] sha1); + + List scriptExists(byte[]... sha1); + + String scriptLoad(String script); + + byte[] scriptLoad(byte[] script); + + String scriptFlush(); + + String scriptFlush(FlushMode flushMode); + + String scriptKill(); + +} diff --git a/src/main/java/redis/clients/jedis/commands/ScriptingKeyBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/ScriptingKeyBinaryCommands.java new file mode 100644 index 0000000000..3b390e4c9c --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ScriptingKeyBinaryCommands.java @@ -0,0 +1,18 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +public interface ScriptingKeyBinaryCommands { + + Object eval(byte[] script); + + Object eval(byte[] script, int keyCount, byte[]... params); + + Object eval(byte[] script, List keys, List args); + + Object evalsha(byte[] sha1); + + Object evalsha(byte[] sha1, int keyCount, byte[]... params); + + Object evalsha(byte[] sha1, List keys, List args); +} diff --git a/src/main/java/redis/clients/jedis/commands/ScriptingCommands.java b/src/main/java/redis/clients/jedis/commands/ScriptingKeyCommands.java similarity index 71% rename from src/main/java/redis/clients/jedis/commands/ScriptingCommands.java rename to src/main/java/redis/clients/jedis/commands/ScriptingKeyCommands.java index 2a50689929..9c109842ad 100644 --- a/src/main/java/redis/clients/jedis/commands/ScriptingCommands.java +++ b/src/main/java/redis/clients/jedis/commands/ScriptingKeyCommands.java @@ -2,22 +2,17 @@ import java.util.List; -public interface ScriptingCommands { +public interface ScriptingKeyCommands { + + Object eval(String script); + Object eval(String script, int keyCount, String... params); Object eval(String script, List keys, List args); - Object eval(String script); - Object evalsha(String sha1); - Object evalsha(String sha1, List keys, List args); - Object evalsha(String sha1, int keyCount, String... params); - Boolean scriptExists(String sha1); - - List scriptExists(String... sha1); - - String scriptLoad(String script); + Object evalsha(String sha1, List keys, List args); } diff --git a/src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineBinaryCommands.java new file mode 100644 index 0000000000..9f7f42eb26 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineBinaryCommands.java @@ -0,0 +1,19 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.Response; + +public interface ScriptingKeyPipelineBinaryCommands { + + Response eval(byte[] script); + + Response eval(byte[] script, int keyCount, byte[]... params); + + Response eval(byte[] script, List keys, List args); + + Response evalsha(byte[] sha1); + + Response evalsha(byte[] sha1, int keyCount, byte[]... params); + + Response evalsha(byte[] sha1, List keys, List args); +} diff --git a/src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineCommands.java new file mode 100644 index 0000000000..01de0549f4 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/ScriptingKeyPipelineCommands.java @@ -0,0 +1,19 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.Response; + +public interface ScriptingKeyPipelineCommands { + + Response eval(String script); + + Response eval(String script, int keyCount, String... params); + + Response eval(String script, List keys, List args); + + Response evalsha(String sha1); + + Response evalsha(String sha1, int keyCount, String... params); + + Response evalsha(String sha1, List keys, List args); +} diff --git a/src/main/java/redis/clients/jedis/commands/SentinelCommands.java b/src/main/java/redis/clients/jedis/commands/SentinelCommands.java index d28ca300e0..d01a7fa37d 100644 --- a/src/main/java/redis/clients/jedis/commands/SentinelCommands.java +++ b/src/main/java/redis/clients/jedis/commands/SentinelCommands.java @@ -3,6 +3,7 @@ import java.util.List; import java.util.Map; +//Legacy public interface SentinelCommands { String sentinelMyId(); diff --git a/src/main/java/redis/clients/jedis/commands/BasicCommands.java b/src/main/java/redis/clients/jedis/commands/ServerCommands.java similarity index 85% rename from src/main/java/redis/clients/jedis/commands/BasicCommands.java rename to src/main/java/redis/clients/jedis/commands/ServerCommands.java index a6dab9d674..b97c7cc5fb 100644 --- a/src/main/java/redis/clients/jedis/commands/BasicCommands.java +++ b/src/main/java/redis/clients/jedis/commands/ServerCommands.java @@ -1,11 +1,10 @@ package redis.clients.jedis.commands; -import redis.clients.jedis.DebugParams; import redis.clients.jedis.args.FlushMode; import redis.clients.jedis.args.SaveMode; import redis.clients.jedis.exceptions.JedisException; -public interface BasicCommands { +public interface ServerCommands { /** * This command is often used to test if a connection is still alive, or to measure latency. @@ -13,6 +12,12 @@ public interface BasicCommands { */ String ping(); + String ping(String message); + + String echo(String string); + + byte[] echo(byte[] arg); + /** * Ask the server to close the connection. The connection is closed as soon as all pending replies * have been written to the client. @@ -27,36 +32,6 @@ public interface BasicCommands { */ String flushDB(); - /** - * Delete all the keys of the currently selected DB. This command never fails. The time-complexity - * for this operation is O(N), N being the number of keys in the database. - * @param flushMode - * @return OK - */ - String flushDB(FlushMode flushMode); - - /** - * Return the number of keys in the currently-selected database. - * @return the number of key in the currently-selected database. - */ - long dbSize(); - - /** - * Select the DB with having the specified zero-based numeric index. - * @param index the index - * @return a simple string reply OK - */ - String select(int index); - - /** - * This command swaps two Redis databases, so that immediately all the clients connected to a - * given database will see the data of the other database, and the other way around. - * @param index1 - * @param index2 - * @return Simple string reply: OK if SWAPDB was executed correctly. - */ - String swapDB(int index1, int index2); - /** * Delete all the keys of all the existing databases, not just the currently selected one. * @return a simple string reply (OK) @@ -134,10 +109,9 @@ public interface BasicCommands { /** * Stop all the client. Perform a SAVE (if one save point is configured). Flush the append only * file if AOF is enabled quit the server - * @return {@code null} * @throws JedisException only in case of error. */ - String shutdown() throws JedisException; + void shutdown() throws JedisException; /** * @see SaveMode @@ -188,18 +162,6 @@ public interface BasicCommands { */ String slaveofNoOne(); - /** - * Return the index of the current database - * @return the int of the index database. - */ - int getDB(); - - String debug(DebugParams params); - - String configResetStat(); - - String configRewrite(); - /** * Syncrhonous replication of Redis as described here: http://antirez.com/news/66. *

diff --git a/src/main/java/redis/clients/jedis/commands/SetBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/SetBinaryCommands.java new file mode 100644 index 0000000000..d454943d0f --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SetBinaryCommands.java @@ -0,0 +1,51 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface SetBinaryCommands { + + long sadd(byte[] key, byte[]... member); + + Set smembers(byte[] key); + + long srem(byte[] key, byte[]... member); + + byte[] spop(byte[] key); + + Set spop(byte[] key, long count); + + long scard(byte[] key); + + boolean sismember(byte[] key, byte[] member); + + List smismember(byte[] key, byte[]... members); + + byte[] srandmember(byte[] key); + + List srandmember(byte[] key, int count); + + default ScanResult sscan(byte[] key, byte[] cursor) { + return sscan(key, cursor, new ScanParams()); + } + + ScanResult sscan(byte[] key, byte[] cursor, ScanParams params); + + Set sdiff(byte[]... keys); + + long sdiffstore(byte[] dstkey, byte[]... keys); + + Set sinter(byte[]... keys); + + long sinterstore(byte[] dstkey, byte[]... keys); + + Set sunion(byte[]... keys); + + long sunionstore(byte[] dstkey, byte[]... keys); + + long smove(byte[] srckey, byte[] dstkey, byte[] member); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SetCommands.java b/src/main/java/redis/clients/jedis/commands/SetCommands.java new file mode 100644 index 0000000000..445f2f114c --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SetCommands.java @@ -0,0 +1,51 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface SetCommands { + + long sadd(String key, String... member); + + Set smembers(String key); + + long srem(String key, String... member); + + String spop(String key); + + Set spop(String key, long count); + + long scard(String key); + + boolean sismember(String key, String member); + + List smismember(String key, String... members); + + String srandmember(String key); + + List srandmember(String key, int count); + + default ScanResult sscan(String key, String cursor) { + return sscan(key, cursor, new ScanParams()); + } + + ScanResult sscan(String key, String cursor, ScanParams params); + + Set sdiff(String... keys); + + long sdiffstore(String dstkey, String... keys); + + Set sinter(String... keys); + + long sinterstore(String dstkey, String... keys); + + Set sunion(String... keys); + + long sunionstore(String dstkey, String... keys); + + long smove(String srckey, String dstkey, String member); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SetPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/SetPipelineBinaryCommands.java new file mode 100644 index 0000000000..e75fbb57ee --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SetPipelineBinaryCommands.java @@ -0,0 +1,52 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface SetPipelineBinaryCommands { + + Response sadd(byte[] key, byte[]... member); + + Response> smembers(byte[] key); + + Response srem(byte[] key, byte[]... member); + + Response spop(byte[] key); + + Response> spop(byte[] key, long count); + + Response scard(byte[] key); + + Response sismember(byte[] key, byte[] member); + + Response> smismember(byte[] key, byte[]... members); + + Response srandmember(byte[] key); + + Response> srandmember(byte[] key, int count); + + default Response> sscan(byte[] key, byte[] cursor) { + return sscan(key, cursor, new ScanParams()); + } + + Response> sscan(byte[] key, byte[] cursor, ScanParams params); + + Response> sdiff(byte[]... keys); + + Response sdiffstore(byte[] dstkey, byte[]... keys); + + Response> sinter(byte[]... keys); + + Response sinterstore(byte[] dstkey, byte[]... keys); + + Response> sunion(byte[]... keys); + + Response sunionstore(byte[] dstkey, byte[]... keys); + + Response smove(byte[] srckey, byte[] dstkey, byte[] member); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SetPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/SetPipelineCommands.java new file mode 100644 index 0000000000..210ae1798f --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SetPipelineCommands.java @@ -0,0 +1,52 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public interface SetPipelineCommands { + + Response sadd(String key, String... member); + + Response> smembers(String key); + + Response srem(String key, String... member); + + Response spop(String key); + + Response> spop(String key, long count); + + Response scard(String key); + + Response sismember(String key, String member); + + Response> smismember(String key, String... members); + + Response srandmember(String key); + + Response> srandmember(String key, int count); + + default Response> sscan(String key, String cursor) { + return sscan(key, cursor, new ScanParams()); + } + + Response> sscan(String key, String cursor, ScanParams params); + + Response> sdiff(String... keys); + + Response sdiffstore(String dstKey, String... keys); + + Response> sinter(String... keys); + + Response sinterstore(String dstKey, String... keys); + + Response> sunion(String... keys); + + Response sunionstore(String dstKey, String... keys); + + Response smove(String srckey, String dstKey, String member); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SlowlogCommands.java b/src/main/java/redis/clients/jedis/commands/SlowlogCommands.java new file mode 100644 index 0000000000..503349197f --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SlowlogCommands.java @@ -0,0 +1,20 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import redis.clients.jedis.resps.Slowlog; + +public interface SlowlogCommands { + + String slowlogReset(); + + long slowlogLen(); + + List slowlogGet(); + + List slowlogGetBinary(); + + List slowlogGet(long entries); + + List slowlogGetBinary(long entries); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SortedSetBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/SortedSetBinaryCommands.java new file mode 100644 index 0000000000..7e3aa51055 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SortedSetBinaryCommands.java @@ -0,0 +1,150 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.ZAddParams; +import redis.clients.jedis.params.ZIncrByParams; +import redis.clients.jedis.params.ZParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; + +public interface SortedSetBinaryCommands { + + long zadd(byte[] key, double score, byte[] member); + + long zadd(byte[] key, double score, byte[] member, ZAddParams params); + + long zadd(byte[] key, Map scoreMembers); + + long zadd(byte[] key, Map scoreMembers, ZAddParams params); + + Double zaddIncr(byte[] key, double score, byte[] member, ZAddParams params); + + long zrem(byte[] key, byte[]... members); + + double zincrby(byte[] key, double increment, byte[] member); + + Double zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params); + + Long zrank(byte[] key, byte[] member); + + Long zrevrank(byte[] key, byte[] member); + + List zrange(byte[] key, long start, long stop); + + List zrevrange(byte[] key, long start, long stop); + + List zrangeWithScores(byte[] key, long start, long stop); + + List zrevrangeWithScores(byte[] key, long start, long stop); + + byte[] zrandmember(byte[] key); + + List zrandmember(byte[] key, long count); + + List zrandmemberWithScores(byte[] key, long count); + + long zcard(byte[] key); + + Double zscore(byte[] key, byte[] member); + + List zmscore(byte[] key, byte[]... members); + + Tuple zpopmax(byte[] key); + + List zpopmax(byte[] key, int count); + + Tuple zpopmin(byte[] key); + + List zpopmin(byte[] key, int count); + + long zcount(byte[] key, double min, double max); + + long zcount(byte[] key, byte[] min, byte[] max); + + List zrangeByScore(byte[] key, double min, double max); + + List zrangeByScore(byte[] key, byte[] min, byte[] max); + + List zrevrangeByScore(byte[] key, double max, double min); + + List zrangeByScore(byte[] key, double min, double max, int offset, int count); + + List zrevrangeByScore(byte[] key, byte[] max, byte[] min); + + List zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count); + + List zrevrangeByScore(byte[] key, double max, double min, int offset, int count); + + List zrangeByScoreWithScores(byte[] key, double min, double max); + + List zrevrangeByScoreWithScores(byte[] key, double max, double min); + + List zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count); + + List zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count); + + List zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); + + List zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); + + List zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count); + + List zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count); + + List zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count); + + long zremrangeByRank(byte[] key, long start, long stop); + + long zremrangeByScore(byte[] key, double min, double max); + + long zremrangeByScore(byte[] key, byte[] min, byte[] max); + + long zlexcount(byte[] key, byte[] min, byte[] max); + + List zrangeByLex(byte[] key, byte[] min, byte[] max); + + List zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count); + + List zrevrangeByLex(byte[] key, byte[] max, byte[] min); + + List zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count); + + long zremrangeByLex(byte[] key, byte[] min, byte[] max); + + default ScanResult zscan(byte[] key, byte[] cursor) { + return zscan(key, cursor, new ScanParams()); + } + + ScanResult zscan(byte[] key, byte[] cursor, ScanParams params); + + List bzpopmax(double timeout, byte[]... keys); + + List bzpopmin(double timeout, byte[]... keys); + + Set zdiff(byte[]... keys); + + Set zdiffWithScores(byte[]... keys); + + long zdiffStore(byte[] dstkey, byte[]... keys); + + Set zinter(ZParams params, byte[]... keys); + + Set zinterWithScores(ZParams params, byte[]... keys); + + long zinterstore(byte[] dstkey, byte[]... sets); + + long zinterstore(byte[] dstkey, ZParams params, byte[]... sets); + + Set zunion(ZParams params, byte[]... keys); + + Set zunionWithScores(ZParams params, byte[]... keys); + + long zunionstore(byte[] dstkey, byte[]... sets); + + long zunionstore(byte[] dstkey, ZParams params, byte[]... sets); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SortedSetCommands.java b/src/main/java/redis/clients/jedis/commands/SortedSetCommands.java new file mode 100644 index 0000000000..674edcb082 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SortedSetCommands.java @@ -0,0 +1,151 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.ZAddParams; +import redis.clients.jedis.params.ZIncrByParams; +import redis.clients.jedis.params.ZParams; +import redis.clients.jedis.resps.KeyedZSetElement; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; + +public interface SortedSetCommands { + + long zadd(String key, double score, String member); + + long zadd(String key, double score, String member, ZAddParams params); + + long zadd(String key, Map scoreMembers); + + long zadd(String key, Map scoreMembers, ZAddParams params); + + Double zaddIncr(String key, double score, String member, ZAddParams params); + + long zrem(String key, String... members); + + double zincrby(String key, double increment, String member); + + Double zincrby(String key, double increment, String member, ZIncrByParams params); + + Long zrank(String key, String member); + + Long zrevrank(String key, String member); + + List zrange(String key, long start, long stop); + + List zrevrange(String key, long start, long stop); + + List zrangeWithScores(String key, long start, long stop); + + List zrevrangeWithScores(String key, long start, long stop); + + String zrandmember(String key); + + List zrandmember(String key, long count); + + List zrandmemberWithScores(String key, long count); + + long zcard(String key); + + Double zscore(String key, String member); + + List zmscore(String key, String... members); + + Tuple zpopmax(String key); + + List zpopmax(String key, int count); + + Tuple zpopmin(String key); + + List zpopmin(String key, int count); + + long zcount(String key, double min, double max); + + long zcount(String key, String min, String max); + + List zrangeByScore(String key, double min, double max); + + List zrangeByScore(String key, String min, String max); + + List zrevrangeByScore(String key, double max, double min); + + List zrangeByScore(String key, double min, double max, int offset, int count); + + List zrevrangeByScore(String key, String max, String min); + + List zrangeByScore(String key, String min, String max, int offset, int count); + + List zrevrangeByScore(String key, double max, double min, int offset, int count); + + List zrangeByScoreWithScores(String key, double min, double max); + + List zrevrangeByScoreWithScores(String key, double max, double min); + + List zrangeByScoreWithScores(String key, double min, double max, int offset, int count); + + List zrevrangeByScore(String key, String max, String min, int offset, int count); + + List zrangeByScoreWithScores(String key, String min, String max); + + List zrevrangeByScoreWithScores(String key, String max, String min); + + List zrangeByScoreWithScores(String key, String min, String max, int offset, int count); + + List zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count); + + List zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count); + + long zremrangeByRank(String key, long start, long stop); + + long zremrangeByScore(String key, double min, double max); + + long zremrangeByScore(String key, String min, String max); + + long zlexcount(String key, String min, String max); + + List zrangeByLex(String key, String min, String max); + + List zrangeByLex(String key, String min, String max, int offset, int count); + + List zrevrangeByLex(String key, String max, String min); + + List zrevrangeByLex(String key, String max, String min, int offset, int count); + + long zremrangeByLex(String key, String min, String max); + + default ScanResult zscan(String key, String cursor) { + return zscan(key, cursor, new ScanParams()); + } + + ScanResult zscan(String key, String cursor, ScanParams params); + + KeyedZSetElement bzpopmax(double timeout, String... keys); + + KeyedZSetElement bzpopmin(double timeout, String... keys); + + Set zdiff(String... keys); + + Set zdiffWithScores(String... keys); + + long zdiffStore(String dstkey, String... keys); + + long zinterstore(String dstkey, String... sets); + + long zinterstore(String dstkey, ZParams params, String... sets); + + Set zinter(ZParams params, String... keys); + + Set zinterWithScores(ZParams params, String... keys); + + Set zunion(ZParams params, String... keys); + + Set zunionWithScores(ZParams params, String... keys); + + long zunionstore(String dstkey, String... sets); + + long zunionstore(String dstkey, ZParams params, String... sets); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SortedSetPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/SortedSetPipelineBinaryCommands.java new file mode 100644 index 0000000000..cfe1d4bdfe --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SortedSetPipelineBinaryCommands.java @@ -0,0 +1,151 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.ZAddParams; +import redis.clients.jedis.params.ZIncrByParams; +import redis.clients.jedis.params.ZParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; + +public interface SortedSetPipelineBinaryCommands { + + Response zadd(byte[] key, double score, byte[] member); + + Response zadd(byte[] key, double score, byte[] member, ZAddParams params); + + Response zadd(byte[] key, Map scoreMembers); + + Response zadd(byte[] key, Map scoreMembers, ZAddParams params); + + Response zaddIncr(byte[] key, double score, byte[] member, ZAddParams params); + + Response zrem(byte[] key, byte[]... members); + + Response zincrby(byte[] key, double increment, byte[] member); + + Response zincrby(byte[] key, double increment, byte[] member, ZIncrByParams params); + + Response zrank(byte[] key, byte[] member); + + Response zrevrank(byte[] key, byte[] member); + + Response> zrange(byte[] key, long start, long stop); + + Response> zrevrange(byte[] key, long start, long stop); + + Response> zrangeWithScores(byte[] key, long start, long stop); + + Response> zrevrangeWithScores(byte[] key, long start, long stop); + + Response zrandmember(byte[] key); + + Response> zrandmember(byte[] key, long count); + + Response> zrandmemberWithScores(byte[] key, long count); + + Response zcard(byte[] key); + + Response zscore(byte[] key, byte[] member); + + Response> zmscore(byte[] key, byte[]... members); + + Response zpopmax(byte[] key); + + Response> zpopmax(byte[] key, int count); + + Response zpopmin(byte[] key); + + Response> zpopmin(byte[] key, int count); + + Response zcount(byte[] key, double min, double max); + + Response zcount(byte[] key, byte[] min, byte[] max); + + Response> zrangeByScore(byte[] key, double min, double max); + + Response> zrangeByScore(byte[] key, byte[] min, byte[] max); + + Response> zrevrangeByScore(byte[] key, double max, double min); + + Response> zrangeByScore(byte[] key, double min, double max, int offset, int count); + + Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min); + + Response> zrangeByScore(byte[] key, byte[] min, byte[] max, int offset, int count); + + Response> zrevrangeByScore(byte[] key, double max, double min, int offset, int count); + + Response> zrangeByScoreWithScores(byte[] key, double min, double max); + + Response> zrevrangeByScoreWithScores(byte[] key, double max, double min); + + Response> zrangeByScoreWithScores(byte[] key, double min, double max, int offset, int count); + + Response> zrevrangeByScore(byte[] key, byte[] max, byte[] min, int offset, int count); + + Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max); + + Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min); + + Response> zrangeByScoreWithScores(byte[] key, byte[] min, byte[] max, int offset, int count); + + Response> zrevrangeByScoreWithScores(byte[] key, double max, double min, int offset, int count); + + Response> zrevrangeByScoreWithScores(byte[] key, byte[] max, byte[] min, int offset, int count); + + Response zremrangeByRank(byte[] key, long start, long stop); + + Response zremrangeByScore(byte[] key, double min, double max); + + Response zremrangeByScore(byte[] key, byte[] min, byte[] max); + + Response zlexcount(byte[] key, byte[] min, byte[] max); + + Response> zrangeByLex(byte[] key, byte[] min, byte[] max); + + Response> zrangeByLex(byte[] key, byte[] min, byte[] max, int offset, int count); + + Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min); + + Response> zrevrangeByLex(byte[] key, byte[] max, byte[] min, int offset, int count); + + Response zremrangeByLex(byte[] key, byte[] min, byte[] max); + + default Response> zscan(byte[] key, byte[] cursor) { + return zscan(key, cursor, new ScanParams()); + } + + Response> zscan(byte[] key, byte[] cursor, ScanParams params); + + Response> bzpopmax(double timeout, byte[]... keys); + + Response> bzpopmin(double timeout, byte[]... keys); + + Response> zdiff(byte[]... keys); + + Response> zdiffWithScores(byte[]... keys); + + Response zdiffStore(byte[] dstkey, byte[]... keys); + + Response> zinter(ZParams params, byte[]... keys); + + Response> zinterWithScores(ZParams params, byte[]... keys); + + Response zinterstore(byte[] dstkey, byte[]... sets); + + Response zinterstore(byte[] dstkey, ZParams params, byte[]... sets); + + Response> zunion(ZParams params, byte[]... keys); + + Response> zunionWithScores(ZParams params, byte[]... keys); + + Response zunionstore(byte[] dstkey, byte[]... sets); + + Response zunionstore(byte[] dstkey, ZParams params, byte[]... sets); + +} diff --git a/src/main/java/redis/clients/jedis/commands/SortedSetPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/SortedSetPipelineCommands.java new file mode 100644 index 0000000000..62363d3966 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/SortedSetPipelineCommands.java @@ -0,0 +1,152 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.ZAddParams; +import redis.clients.jedis.params.ZIncrByParams; +import redis.clients.jedis.params.ZParams; +import redis.clients.jedis.resps.KeyedZSetElement; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; + +public interface SortedSetPipelineCommands { + + Response zadd(String key, double score, String member); + + Response zadd(String key, double score, String member, ZAddParams params); + + Response zadd(String key, Map scoreMembers); + + Response zadd(String key, Map scoreMembers, ZAddParams params); + + Response zaddIncr(String key, double score, String member, ZAddParams params); + + Response zrem(String key, String... members); + + Response zincrby(String key, double increment, String member); + + Response zincrby(String key, double increment, String member, ZIncrByParams params); + + Response zrank(String key, String member); + + Response zrevrank(String key, String member); + + Response> zrange(String key, long start, long stop); + + Response> zrevrange(String key, long start, long stop); + + Response> zrangeWithScores(String key, long start, long stop); + + Response> zrevrangeWithScores(String key, long start, long stop); + + Response zrandmember(String key); + + Response> zrandmember(String key, long count); + + Response> zrandmemberWithScores(String key, long count); + + Response zcard(String key); + + Response zscore(String key, String member); + + Response> zmscore(String key, String... members); + + Response zpopmax(String key); + + Response> zpopmax(String key, int count); + + Response zpopmin(String key); + + Response> zpopmin(String key, int count); + + Response zcount(String key, double min, double max); + + Response zcount(String key, String min, String max); + + Response> zrangeByScore(String key, double min, double max); + + Response> zrangeByScore(String key, String min, String max); + + Response> zrevrangeByScore(String key, double max, double min); + + Response> zrangeByScore(String key, double min, double max, int offset, int count); + + Response> zrevrangeByScore(String key, String max, String min); + + Response> zrangeByScore(String key, String min, String max, int offset, int count); + + Response> zrevrangeByScore(String key, double max, double min, int offset, int count); + + Response> zrangeByScoreWithScores(String key, double min, double max); + + Response> zrevrangeByScoreWithScores(String key, double max, double min); + + Response> zrangeByScoreWithScores(String key, double min, double max, int offset, int count); + + Response> zrevrangeByScore(String key, String max, String min, int offset, int count); + + Response> zrangeByScoreWithScores(String key, String min, String max); + + Response> zrevrangeByScoreWithScores(String key, String max, String min); + + Response> zrangeByScoreWithScores(String key, String min, String max, int offset, int count); + + Response> zrevrangeByScoreWithScores(String key, double max, double min, int offset, int count); + + Response> zrevrangeByScoreWithScores(String key, String max, String min, int offset, int count); + + Response zremrangeByRank(String key, long start, long stop); + + Response zremrangeByScore(String key, double min, double max); + + Response zremrangeByScore(String key, String min, String max); + + Response zlexcount(String key, String min, String max); + + Response> zrangeByLex(String key, String min, String max); + + Response> zrangeByLex(String key, String min, String max, int offset, int count); + + Response> zrevrangeByLex(String key, String max, String min); + + Response> zrevrangeByLex(String key, String max, String min, int offset, int count); + + Response zremrangeByLex(String key, String min, String max); + + default Response> zscan(String key, String cursor) { + return zscan(key, cursor, new ScanParams()); + } + + Response> zscan(String key, String cursor, ScanParams params); + + Response bzpopmax(double timeout, String... keys); + + Response bzpopmin(double timeout, String... keys); + + Response> zdiff(String... keys); + + Response> zdiffWithScores(String... keys); + + Response zdiffStore(String dstKey, String... keys); + + Response zinterstore(String dstKey, String... sets); + + Response zinterstore(String dstKey, ZParams params, String... sets); + + Response> zinter(ZParams params, String... keys); + + Response> zinterWithScores(ZParams params, String... keys); + + Response> zunion(ZParams params, String... keys); + + Response> zunionWithScores(ZParams params, String... keys); + + Response zunionstore(String dstKey, String... sets); + + Response zunionstore(String dstKey, ZParams params, String... sets); + +} diff --git a/src/main/java/redis/clients/jedis/commands/StreamBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/StreamBinaryCommands.java new file mode 100644 index 0000000000..13d6f6bf0b --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StreamBinaryCommands.java @@ -0,0 +1,69 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.params.*; + +public interface StreamBinaryCommands { + + default byte[] xadd(byte[] key, Map hash, XAddParams params) { + return xadd(key, params, hash); + } + + byte[] xadd(byte[] key, XAddParams params, Map hash); + + long xlen(byte[] key); + + List xrange(byte[] key, byte[] start, byte[] end); + + List xrange(byte[] key, byte[] start, byte[] end, int count); + + List xrevrange(byte[] key, byte[] end, byte[] start); + + List xrevrange(byte[] key, byte[] end, byte[] start, int count); + + long xack(byte[] key, byte[] group, byte[]... ids); + + String xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream); + + String xgroupSetID(byte[] key, byte[] groupname, byte[] id); + + long xgroupDestroy(byte[] key, byte[] groupname); + + long xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName); + + long xdel(byte[] key, byte[]... ids); + + long xtrim(byte[] key, long maxLen, boolean approximateLength); + + long xtrim(byte[] key, XTrimParams params); + + Object xpending(byte[] key, byte[] groupname); + + List xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername); + + List xpending(byte[] key, byte[] groupname, XPendingParams params); + + List xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids); + + List xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids); + + List xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, + long minIdleTime, byte[] start, XAutoClaimParams params); + + List xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, + long minIdleTime, byte[] start, XAutoClaimParams params); + + Object xinfoStream(byte[] key); + + List xinfoGroup(byte[] key); + + List xinfoConsumers(byte[] key, byte[] group); + + List xread(XReadParams xReadParams, Map.Entry... streams); + + List xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, + Map.Entry... streams); + +} diff --git a/src/main/java/redis/clients/jedis/commands/StreamCommands.java b/src/main/java/redis/clients/jedis/commands/StreamCommands.java new file mode 100644 index 0000000000..69eaeeee89 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StreamCommands.java @@ -0,0 +1,287 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.StreamEntryID; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; + +public interface StreamCommands { + + /** + * XADD key ID field string [field string ...] + * + * @param key + * @param id + * @param hash + * @return the ID of the added entry + */ + StreamEntryID xadd(String key, StreamEntryID id, Map hash); + + /** + * XADD key [NOMKSTREAM] [MAXLEN|MINID [=|~] threshold [LIMIT count]] *|ID field value [field value ...] + * + * @param key + * @param hash + * @param params + * @return the ID of the added entry + */ + default StreamEntryID xadd(String key, Map hash, XAddParams params) { + return xadd_v2(key, params, hash); + } + + StreamEntryID xadd_v2(String key, XAddParams params, Map hash); + + /** + * XLEN key + * + * @param key + * @return length of stream + */ + long xlen(String key); + + /** + * XRANGE key start end + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @return The entries with IDs matching the specified range. + */ + List xrange(String key, StreamEntryID start, StreamEntryID end); + + /** + * XRANGE key start end COUNT count + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @param count maximum number of entries returned + * @return The entries with IDs matching the specified range. + */ + List xrange(String key, StreamEntryID start, StreamEntryID end, int count); + + /** + * XREVRANGE key end start + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @return the entries with IDs matching the specified range, from the higher ID to the lower ID matching. + */ + List xrevrange(String key, StreamEntryID end, StreamEntryID start); + + /** + * XREVRANGE key end start COUNT count + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @param count The entries with IDs matching the specified range. + * @return the entries with IDs matching the specified range, from the higher ID to the lower ID matching. + */ + List xrevrange(String key, StreamEntryID end, StreamEntryID start, int count); + + /** + * XACK key group ID [ID ...] + * + * @param key + * @param group + * @param ids + */ + long xack(String key, String group, StreamEntryID... ids); + + /** + * XGROUP CREATE + * + * @param key + * @param groupname + * @param id + * @param makeStream + */ + String xgroupCreate( String key, String groupname, StreamEntryID id, boolean makeStream); + + /** + * XGROUP SETID + * + * @param key + * @param groupname + * @param id + */ + String xgroupSetID( String key, String groupname, StreamEntryID id); + + /** + * XGROUP DESTROY + * + * @param key + * @param groupname + */ + long xgroupDestroy(String key, String groupname); + + /** + * XGROUP DELCONSUMER + * @param key + * @param groupname + * @param consumername + */ + long xgroupDelConsumer( String key, String groupname, String consumername); + + /** + * XPENDING key group + * + * @param key + * @param groupname + */ + StreamPendingSummary xpending(String key, String groupname); + + /** + * XPENDING key group [start end count] [consumer] + * + * @param key + * @param groupname + * @param start + * @param end + * @param count + * @param consumername + */ + List xpending(String key, String groupname, StreamEntryID start, + StreamEntryID end, int count, String consumername); + + /** + * XPENDING key group [[IDLE min-idle-time] start end count [consumer]] + * + * @param key + * @param groupname + * @param params + */ + List xpending(String key, String groupname, XPendingParams params); + + /** + * XDEL key ID [ID ...] + * @param key + * @param ids + */ + long xdel(String key, StreamEntryID... ids); + + /** + * XTRIM key MAXLEN [~] count + * @param key + * @param maxLen + * @param approximate + */ + long xtrim(String key, long maxLen, boolean approximate); + + /** + * XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] + * @param key + * @param params + */ + long xtrim(String key, XTrimParams params); + + /** + * XCLAIM ... + * [IDLE ] [TIME ] [RETRYCOUNT ] + * [FORCE] + */ + List xclaim(String key, String group, String consumername, long minIdleTime, + XClaimParams params, StreamEntryID... ids); + + /** + * XCLAIM ... + * [IDLE ] [TIME ] [RETRYCOUNT ] + * [FORCE] JUSTID + */ + List xclaimJustId(String key, String group, String consumername, long minIdleTime, + XClaimParams params, StreamEntryID... ids); + + /** + * XAUTOCLAIM key group consumer min-idle-time start [COUNT count] + * + * @param key Stream Key + * @param group Consumer Group + * @param consumerName Consumer name to transfer the auto claimed entries + * @param minIdleTime Entries pending more than minIdleTime will be transferred ownership + * @param start {@link StreamEntryID} - Entries >= start will be transferred ownership, passing null will indicate '-' + * @param params {@link XAutoClaimParams} + */ + Map.Entry> xautoclaim(String key, String group, String consumerName, + long minIdleTime, StreamEntryID start, XAutoClaimParams params); + + /** + * XAUTOCLAIM key group consumer min-idle-time start [COUNT count] JUSTID + * + * @param key Stream Key + * @param group Consumer Group + * @param consumerName Consumer name to transfer the auto claimed entries + * @param minIdleTime Entries pending more than minIdleTime will be transferred ownership + * @param start {@link StreamEntryID} - Entries >= start will be transferred ownership, passing null will indicate '-' + * @param params {@link XAutoClaimParams} + */ + Map.Entry> xautoclaimJustId(String key, String group, String consumerName, + long minIdleTime, StreamEntryID start, XAutoClaimParams params); + + /** + * Introspection command used in order to retrieve different information about the stream + * @param key Stream name + * @return {@link StreamInfo} that contains information about the stream + */ + StreamInfo xinfoStream (String key); + + /** + * Introspection command used in order to retrieve different information about groups in the stream + * @param key Stream name + * @return List of {@link StreamGroupInfo} containing information about groups + */ + List xinfoGroup (String key); + + /** + * Introspection command used in order to retrieve different information about consumers in the group + * @param key Stream name + * @param group Group name + * @return List of {@link StreamConsumersInfo} containing information about consumers that belong + * to the the group + */ + List xinfoConsumers (String key, String group); + + /** + * XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] + * + * @param xReadParams + * @param streams + */ + List>> xread(XReadParams xReadParams, + Map streams); + + /** + * @deprecated This method will be removed due to bug regarding {@code block} param. Use + * {@link StreamCommands#xreadGroup(java.lang.String, java.lang.String, + * redis.clients.jedis.params.XReadGroupParams, java.util.Map)}. + */ + default List>> xreadGroup(final String groupname, + final String consumer, final int count, final long block, final boolean noAck, + final Map.Entry... streams) { + if (block > Integer.MAX_VALUE) throw new IllegalArgumentException(); + XReadGroupParams params = XReadGroupParams.xReadGroupParams(); + if (count > 0) params.count(count); + if (block > 0) params.block((int) block); + if (noAck) params.noAck(); + Map streamMap = new java.util.LinkedHashMap<>(streams.length); + for (Map.Entry stream : streams) { + streamMap.put(stream.getKey(), stream.getValue()); + } + return xreadGroup(groupname, consumer, params, streamMap); + } + + /** + * XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] + * + * @param groupname + * @param consumer + * @param xReadGroupParams + * @param streams + */ + List>> xreadGroup(String groupname, String consumer, + XReadGroupParams xReadGroupParams, Map streams); + +} diff --git a/src/main/java/redis/clients/jedis/commands/StreamPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/StreamPipelineBinaryCommands.java new file mode 100644 index 0000000000..2d3423f47c --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StreamPipelineBinaryCommands.java @@ -0,0 +1,72 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.Response; +import redis.clients.jedis.params.*; + +public interface StreamPipelineBinaryCommands { +// +// byte[] xadd(byte[] key, byte[] id, Map hash, long maxLen, boolean approximateLength); + + default Response xadd(byte[] key, Map hash, XAddParams params) { + return xadd(key, params, hash); + } + + Response xadd(byte[] key, XAddParams params, Map hash); + + Response xlen(byte[] key); + + Response> xrange(byte[] key, byte[] start, byte[] end); + + Response> xrange(byte[] key, byte[] start, byte[] end, int count); + + Response> xrevrange(byte[] key, byte[] end, byte[] start); + + Response> xrevrange(byte[] key, byte[] end, byte[] start, int count); + + Response xack(byte[] key, byte[] group, byte[]... ids); + + Response xgroupCreate(byte[] key, byte[] groupname, byte[] id, boolean makeStream); + + Response xgroupSetID(byte[] key, byte[] groupname, byte[] id); + + Response xgroupDestroy(byte[] key, byte[] groupname); + + Response xgroupDelConsumer(byte[] key, byte[] groupname, byte[] consumerName); + + Response xdel(byte[] key, byte[]... ids); + + Response xtrim(byte[] key, long maxLen, boolean approximateLength); + + Response xtrim(byte[] key, XTrimParams params); + + Response xpending(byte[] key, byte[] groupname); + + Response> xpending(byte[] key, byte[] groupname, byte[] start, byte[] end, int count, byte[] consumername); + + Response> xpending(byte[] key, byte[] groupname, XPendingParams params); + + Response> xclaim(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids); + + Response> xclaimJustId(byte[] key, byte[] group, byte[] consumername, long minIdleTime, XClaimParams params, byte[]... ids); + + Response> xautoclaim(byte[] key, byte[] groupName, byte[] consumerName, + long minIdleTime, byte[] start, XAutoClaimParams params); + + Response> xautoclaimJustId(byte[] key, byte[] groupName, byte[] consumerName, + long minIdleTime, byte[] start, XAutoClaimParams params); + + Response xinfoStream(byte[] key); + + Response> xinfoGroup(byte[] key); + + Response> xinfoConsumers(byte[] key, byte[] group); + + Response> xread(XReadParams xReadParams, Map.Entry... streams); + + Response> xreadGroup(byte[] groupname, byte[] consumer, XReadGroupParams xReadGroupParams, + Map.Entry... streams); + +} diff --git a/src/main/java/redis/clients/jedis/commands/StreamPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/StreamPipelineCommands.java new file mode 100644 index 0000000000..529b799421 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StreamPipelineCommands.java @@ -0,0 +1,288 @@ +package redis.clients.jedis.commands; + +import java.util.List; +import java.util.Map; + +import redis.clients.jedis.Response; +import redis.clients.jedis.StreamEntryID; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; + +public interface StreamPipelineCommands { + + /** + * XADD key ID field string [field string ...] + * + * @param key + * @param id + * @param hash + * @return the ID of the added entry + */ + Response xadd(String key, StreamEntryID id, Map hash); + + /** + * XADD key [NOMKSTREAM] [MAXLEN|MINID [=|~] threshold [LIMIT count]] *|ID field value [field value ...] + * + * @param key + * @param hash + * @param params + * @return the ID of the added entry + */ + default Response xadd(String key, Map hash, XAddParams params) { + return xadd_v2(key, params, hash); + } + + Response xadd_v2(String key, XAddParams params, Map hash); + + /** + * XLEN key + * + * @param key + * @return length of stream + */ + Response xlen(String key); + + /** + * XRANGE key start end + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @return The entries with IDs matching the specified range. + */ + Response> xrange(String key, StreamEntryID start, StreamEntryID end); + + /** + * XRANGE key start end COUNT count + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @param count maximum number of entries returned + * @return The entries with IDs matching the specified range. + */ + Response> xrange(String key, StreamEntryID start, StreamEntryID end, int count); + + /** + * XREVRANGE key end start + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @return the entries with IDs matching the specified range, from the higher ID to the lower ID matching. + */ + Response> xrevrange(String key, StreamEntryID end, StreamEntryID start); + + /** + * XREVRANGE key end start COUNT count + * + * @param key + * @param start minimum {@link StreamEntryID} for the retrieved range, passing null will indicate minimum ID possible in the stream + * @param end maximum {@link StreamEntryID} for the retrieved range, passing null will indicate maximum ID possible in the stream + * @param count The entries with IDs matching the specified range. + * @return the entries with IDs matching the specified range, from the higher ID to the lower ID matching. + */ + Response> xrevrange(String key, StreamEntryID end, StreamEntryID start, int count); + + /** + * XACK key group ID [ID ...] + * + * @param key + * @param group + * @param ids + */ + Response xack(String key, String group, StreamEntryID... ids); + + /** + * XGROUP CREATE + * + * @param key + * @param groupname + * @param id + * @param makeStream + */ + Response xgroupCreate( String key, String groupname, StreamEntryID id, boolean makeStream); + + /** + * XGROUP SETID + * + * @param key + * @param groupname + * @param id + */ + Response xgroupSetID( String key, String groupname, StreamEntryID id); + + /** + * XGROUP DESTROY + * + * @param key + * @param groupname + */ + Response xgroupDestroy(String key, String groupname); + + /** + * XGROUP DELCONSUMER + * @param key + * @param groupname + * @param consumername + */ + Response xgroupDelConsumer( String key, String groupname, String consumername); + + /** + * XPENDING key group + * + * @param key + * @param groupname + */ + Response xpending(String key, String groupname); + + /** + * XPENDING key group [start end count] [consumer] + * + * @param key + * @param groupname + * @param start + * @param end + * @param count + * @param consumername + */ + Response> xpending(String key, String groupname, StreamEntryID start, + StreamEntryID end, int count, String consumername); + + /** + * XPENDING key group [[IDLE min-idle-time] start end count [consumer]] + * + * @param key + * @param groupname + * @param params + */ + Response> xpending(String key, String groupname, XPendingParams params); + + /** + * XDEL key ID [ID ...] + * @param key + * @param ids + */ + Response xdel(String key, StreamEntryID... ids); + + /** + * XTRIM key MAXLEN [~] count + * @param key + * @param maxLen + * @param approximate + */ + Response xtrim(String key, long maxLen, boolean approximate); + + /** + * XTRIM key MAXLEN|MINID [=|~] threshold [LIMIT count] + * @param key + * @param params + */ + Response xtrim(String key, XTrimParams params); + + /** + * XCLAIM ... + * [IDLE ] [TIME ] [RETRYCOUNT ] + * [FORCE] + */ + Response> xclaim(String key, String group, String consumername, long minIdleTime, + XClaimParams params, StreamEntryID... ids); + + /** + * XCLAIM ... + * [IDLE ] [TIME ] [RETRYCOUNT ] + * [FORCE] JUSTID + */ + Response> xclaimJustId(String key, String group, String consumername, long minIdleTime, + XClaimParams params, StreamEntryID... ids); + + /** + * XAUTOCLAIM key group consumer min-idle-time start [COUNT count] + * + * @param key Stream Key + * @param group Consumer Group + * @param consumerName Consumer name to transfer the auto claimed entries + * @param minIdleTime Entries pending more than minIdleTime will be transferred ownership + * @param start {@link StreamEntryID} - Entries >= start will be transferred ownership, passing null will indicate '-' + * @param params {@link XAutoClaimParams} + */ + Response>> xautoclaim(String key, String group, String consumerName, + long minIdleTime, StreamEntryID start, XAutoClaimParams params); + + /** + * XAUTOCLAIM key group consumer min-idle-time start [COUNT count] JUSTID + * + * @param key Stream Key + * @param group Consumer Group + * @param consumerName Consumer name to transfer the auto claimed entries + * @param minIdleTime Entries pending more than minIdleTime will be transferred ownership + * @param start {@link StreamEntryID} - Entries >= start will be transferred ownership, passing null will indicate '-' + * @param params {@link XAutoClaimParams} + */ + Response>> xautoclaimJustId(String key, String group, String consumerName, + long minIdleTime, StreamEntryID start, XAutoClaimParams params); + + /** + * Introspection command used in order to retrieve different information about the stream + * @param key Stream name + * @return {@link StreamInfo} that contains information about the stream + */ + Response xinfoStream (String key); + + /** + * Introspection command used in order to retrieve different information about groups in the stream + * @param key Stream name + * @return List of {@link StreamGroupInfo} containing information about groups + */ + Response> xinfoGroup (String key); + + /** + * Introspection command used in order to retrieve different information about consumers in the group + * @param key Stream name + * @param group Group name + * @return List of {@link StreamConsumersInfo} containing information about consumers that belong + * to the the group + */ + Response> xinfoConsumers (String key, String group); + + /** + * XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] + * + * @param xReadParams + * @param streams + */ + Response>>> xread(XReadParams xReadParams, + Map streams); + + /** + * @deprecated This method will be removed due to bug regarding {@code block} param. Use + * {@link StreamPipelineCommands#xreadGroup(String, String, XReadGroupParams, Map)}. + */ + @Deprecated + default Response>>> xreadGroup(final String groupname, + final String consumer, final int count, final long block, final boolean noAck, + final Map.Entry... streams) { + if (block > Integer.MAX_VALUE) throw new IllegalArgumentException(); + XReadGroupParams params = XReadGroupParams.xReadGroupParams(); + if (count > 0) params.count(count); + if (block > 0) params.block((int) block); + if (noAck) params.noAck(); + Map streamMap = new java.util.LinkedHashMap<>(streams.length); + for (Map.Entry stream : streams) { + streamMap.put(stream.getKey(), stream.getValue()); + } + return xreadGroup(groupname, consumer, params, streamMap); + } + + /** + * XREAD [COUNT count] [BLOCK milliseconds] STREAMS key [key ...] ID [ID ...] + * + * @param groupname + * @param consumer + * @param xReadGroupParams + * @param streams + */ + Response>>> xreadGroup(String groupname, String consumer, + XReadGroupParams xReadGroupParams, Map streams); + +} diff --git a/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java new file mode 100644 index 0000000000..b733403601 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StringBinaryCommands.java @@ -0,0 +1,77 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +import redis.clients.jedis.args.BitOP; +import redis.clients.jedis.params.BitPosParams; +import redis.clients.jedis.params.GetExParams; +import redis.clients.jedis.params.SetParams; +import redis.clients.jedis.params.StrAlgoLCSParams; +import redis.clients.jedis.resps.LCSMatchResult; + +public interface StringBinaryCommands { + + String set(byte[] key, byte[] value); + + String set(byte[] key, byte[] value, SetParams params); + + byte[] get(byte[] key); + + byte[] getDel(byte[] key); + + byte[] getEx(byte[] key, GetExParams params); + + boolean setbit(byte[] key, long offset, boolean value); + + boolean getbit(byte[] key, long offset); + + long setrange(byte[] key, long offset, byte[] value); + + byte[] getrange(byte[] key, long startOffset, long endOffset); + + byte[] getSet(byte[] key, byte[] value); + + long setnx(byte[] key, byte[] value); + + String setex(byte[] key, long seconds, byte[] value); + + String psetex(byte[] key, long milliseconds, byte[] value); + + List mget(byte[]... keys); + + String mset(byte[]... keysvalues); + + long msetnx(byte[]... keysvalues); + + long incr(byte[] key); + + long incrBy(byte[] key, long increment); + + double incrByFloat(byte[] key, double increment); + + long decr(byte[] key); + + long decrBy(byte[] key, long decrement); + + long append(byte[] key, byte[] value); + + byte[] substr(byte[] key, int start, int end); + + long strlen(byte[] key); + + long bitcount(byte[] key); + + long bitcount(byte[] key, long start, long end); + + long bitpos(byte[] key, boolean value); + + long bitpos(byte[] key, boolean value, BitPosParams params); + + List bitfield(byte[] key, byte[]... arguments); + + List bitfieldReadonly(byte[] key, byte[]... arguments); + + long bitop(BitOP op, byte[] destKey, byte[]... srcKeys); + + LCSMatchResult strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params); +} diff --git a/src/main/java/redis/clients/jedis/commands/StringCommands.java b/src/main/java/redis/clients/jedis/commands/StringCommands.java new file mode 100644 index 0000000000..1c82960e73 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StringCommands.java @@ -0,0 +1,78 @@ +package redis.clients.jedis.commands; + +import java.util.List; + +import redis.clients.jedis.args.BitOP; +import redis.clients.jedis.params.BitPosParams; +import redis.clients.jedis.params.GetExParams; +import redis.clients.jedis.params.SetParams; +import redis.clients.jedis.params.StrAlgoLCSParams; +import redis.clients.jedis.resps.LCSMatchResult; + +public interface StringCommands { + + String set(String key, String value); + + String set(String key, String value, SetParams params); + + String get(String key); + + String getDel(String key); + + String getEx(String key, GetExParams params); + + boolean setbit(String key, long offset, boolean value); + + boolean getbit(String key, long offset); + + long setrange(String key, long offset, String value); + + String getrange(String key, long startOffset, long endOffset); + + String getSet(String key, String value); + + long setnx(String key, String value); + + String setex(String key, long seconds, String value); + + String psetex(String key, long milliseconds, String value); + + List mget(String... keys); + + String mset(String... keysvalues); + + long msetnx(String... keysvalues); + + long incr(String key); + + long incrBy(String key, long increment); + + double incrByFloat(String key, double increment); + + long decr(String key); + + long decrBy(String key, long decrement); + + long append(String key, String value); + + String substr(String key, int start, int end); + + long strlen(String key); + + long bitcount(String key); + + long bitcount(String key, long start, long end); + + long bitpos(String key, boolean value); + + long bitpos(String key, boolean value, BitPosParams params); + + List bitfield(String key, String...arguments); + + List bitfieldReadonly(String key, String...arguments); + + long bitop(BitOP op, String destKey, String... srcKeys); + + LCSMatchResult strAlgoLCSKeys(String keyA, String keyB, StrAlgoLCSParams params); + +} diff --git a/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java b/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java new file mode 100644 index 0000000000..667f6c94c2 --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StringPipelineBinaryCommands.java @@ -0,0 +1,78 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.Response; +import redis.clients.jedis.args.BitOP; +import redis.clients.jedis.params.BitPosParams; +import redis.clients.jedis.params.GetExParams; +import redis.clients.jedis.params.SetParams; +import redis.clients.jedis.params.StrAlgoLCSParams; +import redis.clients.jedis.resps.LCSMatchResult; + +import java.util.List; + +public interface StringPipelineBinaryCommands { + + Response set(byte[] key, byte[] value); + + Response set(byte[] key, byte[] value, SetParams params); + + Response get(byte[] key); + + Response getDel(byte[] key); + + Response getEx(byte[] key, GetExParams params); + + Response setbit(byte[] key, long offset, boolean value); + + Response getbit(byte[] key, long offset); + + Response setrange(byte[] key, long offset, byte[] value); + + Response getrange(byte[] key, long startOffset, long endOffset); + + Response getSet(byte[] key, byte[] value); + + Response setnx(byte[] key, byte[] value); + + Response setex(byte[] key, long seconds, byte[] value); + + Response psetex(byte[] key, long milliseconds, byte[] value); + + Response> mget(byte[]... keys); + + Response mset(byte[]... keysvalues); + + Response msetnx(byte[]... keysvalues); + + Response incr(byte[] key); + + Response incrBy(byte[] key, long increment); + + Response incrByFloat(byte[] key, double increment); + + Response decr(byte[] key); + + Response decrBy(byte[] key, long decrement); + + Response append(byte[] key, byte[] value); + + Response substr(byte[] key, int start, int end); + + Response strlen(byte[] key); + + Response bitcount(byte[] key); + + Response bitcount(byte[] key, long start, long end); + + Response bitpos(byte[] key, boolean value); + + Response bitpos(byte[] key, boolean value, BitPosParams params); + + Response> bitfield(byte[] key, byte[]... arguments); + + Response> bitfieldReadonly(byte[] key, byte[]... arguments); + + Response bitop(BitOP op, byte[] destKey, byte[]... srcKeys); + + Response strAlgoLCSKeys(final byte[] keyA, final byte[] keyB, final StrAlgoLCSParams params); +} diff --git a/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java b/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java new file mode 100644 index 0000000000..1243d51d4e --- /dev/null +++ b/src/main/java/redis/clients/jedis/commands/StringPipelineCommands.java @@ -0,0 +1,79 @@ +package redis.clients.jedis.commands; + +import redis.clients.jedis.Response; +import redis.clients.jedis.args.BitOP; +import redis.clients.jedis.params.BitPosParams; +import redis.clients.jedis.params.GetExParams; +import redis.clients.jedis.params.SetParams; +import redis.clients.jedis.params.StrAlgoLCSParams; +import redis.clients.jedis.resps.LCSMatchResult; + +import java.util.List; + +public interface StringPipelineCommands { + + Response set(String key, String value); + + Response set(String key, String value, SetParams params); + + Response get(String key); + + Response getDel(String key); + + Response getEx(String key, GetExParams params); + + Response setbit(String key, long offset, boolean value); + + Response getbit(String key, long offset); + + Response setrange(String key, long offset, String value); + + Response getrange(String key, long startOffset, long endOffset); + + Response getSet(String key, String value); + + Response setnx(String key, String value); + + Response setex(String key, long seconds, String value); + + Response psetex(String key, long milliseconds, String value); + + Response> mget(String... keys); + + Response mset(String... keysvalues); + + Response msetnx(String... keysvalues); + + Response incr(String key); + + Response incrBy(String key, long increment); + + Response incrByFloat(String key, double increment); + + Response decr(String key); + + Response decrBy(String key, long decrement); + + Response append(String key, String value); + + Response substr(String key, int start, int end); + + Response strlen(String key); + + Response bitcount(String key); + + Response bitcount(String key, long start, long end); + + Response bitpos(String key, boolean value); + + Response bitpos(String key, boolean value, BitPosParams params); + + Response> bitfield(String key, String...arguments); + + Response> bitfieldReadonly(String key, String...arguments); + + Response bitop(BitOP op, String destKey, String... srcKeys); + + Response strAlgoLCSKeys(String keyA, String keyB, StrAlgoLCSParams params); + +} diff --git a/src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java b/src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java index aa0e94de0d..9235e25ab3 100644 --- a/src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java +++ b/src/main/java/redis/clients/jedis/exceptions/InvalidURIException.java @@ -15,5 +15,4 @@ public InvalidURIException(Throwable cause) { public InvalidURIException(String message, Throwable cause) { super(message, cause); } - } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java index 83f72d1406..87e41fda42 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisAskDataException.java @@ -3,6 +3,7 @@ import redis.clients.jedis.HostAndPort; public class JedisAskDataException extends JedisRedirectionException { + private static final long serialVersionUID = 3878126572474819403L; public JedisAskDataException(Throwable cause, HostAndPort targetHost, int slot) { @@ -16,5 +17,4 @@ public JedisAskDataException(String message, Throwable cause, HostAndPort target public JedisAskDataException(String message, HostAndPort targetHost, int slot) { super(message, targetHost, slot); } - } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisBusyException.java b/src/main/java/redis/clients/jedis/exceptions/JedisBusyException.java index 654978723b..a7483162fb 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisBusyException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisBusyException.java @@ -15,5 +15,4 @@ public JedisBusyException(final Throwable cause) { public JedisBusyException(final String message, final Throwable cause) { super(message, cause); } - } diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java index 502489c600..a015c477d5 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterException.java @@ -1,6 +1,7 @@ package redis.clients.jedis.exceptions; public class JedisClusterException extends JedisDataException { + private static final long serialVersionUID = 3878126572474819403L; public JedisClusterException(Throwable cause) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java deleted file mode 100644 index 35c8a142ad..0000000000 --- a/src/main/java/redis/clients/jedis/exceptions/JedisClusterMaxAttemptsException.java +++ /dev/null @@ -1,23 +0,0 @@ -package redis.clients.jedis.exceptions; - -/** - * @deprecated This exception class will be removed in future. Use - * {@link JedisClusterOperationException} instead. - */ -@Deprecated -public class JedisClusterMaxAttemptsException extends JedisClusterOperationException { - - private static final long serialVersionUID = 167600616259092761L; - - public JedisClusterMaxAttemptsException(String message) { - super(message); - } - - public JedisClusterMaxAttemptsException(Throwable cause) { - super(cause); - } - - public JedisClusterMaxAttemptsException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisClusterOperationException.java b/src/main/java/redis/clients/jedis/exceptions/JedisClusterOperationException.java index aa83aac297..9efb4169f4 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisClusterOperationException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisClusterOperationException.java @@ -1,6 +1,7 @@ package redis.clients.jedis.exceptions; public class JedisClusterOperationException extends JedisException { + private static final long serialVersionUID = 8124535086306604887L; public JedisClusterOperationException(String message) { @@ -14,4 +15,4 @@ public JedisClusterOperationException(Throwable cause) { public JedisClusterOperationException(String message, Throwable cause) { super(message, cause); } -} \ No newline at end of file +} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java b/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java index 8d2d1b4565..3304aa91fe 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisConnectionException.java @@ -1,6 +1,7 @@ package redis.clients.jedis.exceptions; public class JedisConnectionException extends JedisException { + private static final long serialVersionUID = 3878126572474819403L; public JedisConnectionException(String message) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java index 4c8229cb5c..62a91c5d66 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisDataException.java @@ -1,6 +1,7 @@ package redis.clients.jedis.exceptions; public class JedisDataException extends JedisException { + private static final long serialVersionUID = 3878126572474819403L; public JedisDataException(String message) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisException.java b/src/main/java/redis/clients/jedis/exceptions/JedisException.java index 465eeb8a80..25b809370a 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisException.java @@ -1,6 +1,7 @@ package redis.clients.jedis.exceptions; public class JedisException extends RuntimeException { + private static final long serialVersionUID = -2946266495682282677L; public JedisException(String message) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java b/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java deleted file mode 100644 index e37e598653..0000000000 --- a/src/main/java/redis/clients/jedis/exceptions/JedisExhaustedPoolException.java +++ /dev/null @@ -1,20 +0,0 @@ -package redis.clients.jedis.exceptions; - -/** - * This exception will be thrown when the Jedis client isn't able to retrieve a connection from the - * pool, since all the connections are being used (a.k.a. an "exhausted" pool). - */ -public class JedisExhaustedPoolException extends JedisException { - - public JedisExhaustedPoolException(String message) { - super(message); - } - - public JedisExhaustedPoolException(Throwable e) { - super(e); - } - - public JedisExhaustedPoolException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java index 9656e3c0aa..b9e2f5a024 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisMovedDataException.java @@ -3,6 +3,7 @@ import redis.clients.jedis.HostAndPort; public class JedisMovedDataException extends JedisRedirectionException { + private static final long serialVersionUID = 3878126572474819403L; public JedisMovedDataException(String message, HostAndPort targetNode, int slot) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java b/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java deleted file mode 100644 index cc4495a44e..0000000000 --- a/src/main/java/redis/clients/jedis/exceptions/JedisNoReachableClusterNodeException.java +++ /dev/null @@ -1,22 +0,0 @@ -package redis.clients.jedis.exceptions; - -/** - * @deprecated This exception class will be removed in future. Use - * {@link JedisClusterOperationException} instead. - */ -public class JedisNoReachableClusterNodeException extends JedisClusterOperationException { - - private static final long serialVersionUID = 3878122572474110407L; - - public JedisNoReachableClusterNodeException(String message) { - super(message); - } - - public JedisNoReachableClusterNodeException(Throwable cause) { - super(cause); - } - - public JedisNoReachableClusterNodeException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisNoScriptException.java b/src/main/java/redis/clients/jedis/exceptions/JedisNoScriptException.java index 46113cf50a..4106e6ffcc 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisNoScriptException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisNoScriptException.java @@ -1,6 +1,7 @@ package redis.clients.jedis.exceptions; public class JedisNoScriptException extends JedisDataException { + private static final long serialVersionUID = 4674378093072060731L; public JedisNoScriptException(final String message) { diff --git a/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java b/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java index dc605a9fe4..40f377aaed 100644 --- a/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java +++ b/src/main/java/redis/clients/jedis/exceptions/JedisRedirectionException.java @@ -3,6 +3,7 @@ import redis.clients.jedis.HostAndPort; public class JedisRedirectionException extends JedisDataException { + private static final long serialVersionUID = 3878126572474819403L; private final HostAndPort targetNode; @@ -26,11 +27,11 @@ public JedisRedirectionException(String message, Throwable cause, HostAndPort ta this.slot = slot; } - public HostAndPort getTargetNode() { + public final HostAndPort getTargetNode() { return targetNode; } - public int getSlot() { + public final int getSlot() { return slot; } } diff --git a/src/main/java/redis/clients/jedis/executors/ClusterCommandExecutor.java b/src/main/java/redis/clients/jedis/executors/ClusterCommandExecutor.java new file mode 100644 index 0000000000..b4436b650b --- /dev/null +++ b/src/main/java/redis/clients/jedis/executors/ClusterCommandExecutor.java @@ -0,0 +1,155 @@ +package redis.clients.jedis.executors; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import redis.clients.jedis.CommandObject; +import redis.clients.jedis.Connection; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.exceptions.*; +import redis.clients.jedis.providers.ClusterConnectionProvider; + +public class ClusterCommandExecutor implements CommandExecutor { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + public final ClusterConnectionProvider provider; + protected final int maxAttempts; + protected final Duration maxTotalRetriesDuration; + + public ClusterCommandExecutor(ClusterConnectionProvider provider, int maxAttempts, + Duration maxTotalRetriesDuration) { + this.provider = provider; + this.maxAttempts = maxAttempts; + this.maxTotalRetriesDuration = maxTotalRetriesDuration; + } + + @Override + public void close() { + this.provider.close(); + } + + @Override + public final T executeCommand(CommandObject commandObject) { + Instant deadline = Instant.now().plus(maxTotalRetriesDuration); + + JedisRedirectionException redirect = null; + int consecutiveConnectionFailures = 0; + Exception lastException = null; + for (int attemptsLeft = this.maxAttempts; attemptsLeft > 0; attemptsLeft--) { + Connection connection = null; + try { + if (redirect != null) { + connection = provider.getConnection(redirect.getTargetNode()); + if (redirect instanceof JedisAskDataException) { + // TODO: Pipeline asking with the original command to make it faster.... + connection.executeCommand(Protocol.Command.ASKING); + } + } else { + connection = provider.getConnection(commandObject.getArguments()); + } + + return connection.executeCommand(commandObject); + + } catch (JedisClusterOperationException jnrcne) { + throw jnrcne; + } catch (JedisConnectionException jce) { + lastException = jce; + ++consecutiveConnectionFailures; + log.debug("Failed connecting to Redis: {}", connection, jce); + // "- 1" because we just did one, but the attemptsLeft counter hasn't been decremented yet + boolean reset = handleConnectionProblem(attemptsLeft - 1, consecutiveConnectionFailures, deadline); + if (reset) { + consecutiveConnectionFailures = 0; + redirect = null; + } + } catch (JedisRedirectionException jre) { + // avoid updating lastException if it is a connection exception + if (lastException == null || lastException instanceof JedisRedirectionException) { + lastException = jre; + } + log.debug("Redirected by server to {}", jre.getTargetNode()); + consecutiveConnectionFailures = 0; + redirect = jre; + // if MOVED redirection occurred, + if (jre instanceof JedisMovedDataException) { + // it rebuilds cluster's slot cache recommended by Redis cluster specification + provider.renewSlotCache(connection); + } + } finally { + if (connection != null) { + connection.close(); + } + } + if (Instant.now().isAfter(deadline)) { + throw new JedisClusterOperationException("Cluster retry deadline exceeded."); + } + } + + JedisClusterOperationException maxAttemptsException + = new JedisClusterOperationException("No more cluster attempts left."); + maxAttemptsException.addSuppressed(lastException); + throw maxAttemptsException; + } + + /** + * Related values should be reset if TRUE is returned. + * + * @param attemptsLeft + * @param consecutiveConnectionFailures + * @param doneDeadline + * @return true - if some actions are taken + *
false - if no actions are taken + */ + private boolean handleConnectionProblem(int attemptsLeft, int consecutiveConnectionFailures, Instant doneDeadline) { + if (this.maxAttempts < 3) { + // Since we only renew the slots cache after two consecutive connection + // failures (see consecutiveConnectionFailures above), we need to special + // case the situation where we max out after two or fewer attempts. + // Otherwise, on two or fewer max attempts, the slots cache would never be + // renewed. + if (attemptsLeft == 0) { + provider.renewSlotCache(); + return true; + } + return false; + } + + if (consecutiveConnectionFailures < 2) { + return false; + } + + sleep(getBackoffSleepMillis(attemptsLeft, doneDeadline)); + //We need this because if node is not reachable anymore - we need to finally initiate slots + //renewing, or we can stuck with cluster state without one node in opposite case. + //TODO make tracking of successful/unsuccessful operations for node - do renewing only + //if there were no successful responses from this node last few seconds + provider.renewSlotCache(); + return true; + } + + private static long getBackoffSleepMillis(int attemptsLeft, Instant deadline) { + if (attemptsLeft <= 0) { + return 0; + } + + long millisLeft = Duration.between(Instant.now(), deadline).toMillis(); + if (millisLeft < 0) { + throw new JedisClusterOperationException("Cluster retry deadline exceeded."); + } + + return millisLeft / (attemptsLeft * (attemptsLeft + 1)); + } + + protected void sleep(long sleepMillis) { + try { + TimeUnit.MILLISECONDS.sleep(sleepMillis); + } catch (InterruptedException e) { + throw new JedisClusterOperationException(e); + } + } +} diff --git a/src/main/java/redis/clients/jedis/executors/CommandExecutor.java b/src/main/java/redis/clients/jedis/executors/CommandExecutor.java new file mode 100644 index 0000000000..374c63a7dc --- /dev/null +++ b/src/main/java/redis/clients/jedis/executors/CommandExecutor.java @@ -0,0 +1,8 @@ +package redis.clients.jedis.executors; + +import redis.clients.jedis.CommandObject; + +public interface CommandExecutor extends AutoCloseable { + + T executeCommand(CommandObject commandObject); +} diff --git a/src/main/java/redis/clients/jedis/executors/DefaultCommandExecutor.java b/src/main/java/redis/clients/jedis/executors/DefaultCommandExecutor.java new file mode 100644 index 0000000000..7b64bb399f --- /dev/null +++ b/src/main/java/redis/clients/jedis/executors/DefaultCommandExecutor.java @@ -0,0 +1,27 @@ +package redis.clients.jedis.executors; + +import redis.clients.jedis.CommandObject; +import redis.clients.jedis.Connection; +import redis.clients.jedis.util.IOUtils; +import redis.clients.jedis.providers.ConnectionProvider; + +public class DefaultCommandExecutor implements CommandExecutor { + + protected final ConnectionProvider provider; + + public DefaultCommandExecutor(ConnectionProvider provider) { + this.provider = provider; + } + + @Override + public void close() { + IOUtils.closeQuietly(this.provider); + } + + @Override + public final T executeCommand(CommandObject commandObject) { + try (Connection connection = provider.getConnection(commandObject.getArguments())) { + return connection.executeCommand(commandObject); + } + } +} diff --git a/src/main/java/redis/clients/jedis/executors/RetryableCommandExecutor.java b/src/main/java/redis/clients/jedis/executors/RetryableCommandExecutor.java new file mode 100644 index 0000000000..c271ee9a9a --- /dev/null +++ b/src/main/java/redis/clients/jedis/executors/RetryableCommandExecutor.java @@ -0,0 +1,113 @@ +package redis.clients.jedis.executors; + +import java.time.Duration; +import java.time.Instant; +import java.util.concurrent.TimeUnit; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import redis.clients.jedis.CommandObject; +import redis.clients.jedis.Connection; + +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.util.IOUtils; +import redis.clients.jedis.providers.ConnectionProvider; + +public class RetryableCommandExecutor implements CommandExecutor { + + private final Logger log = LoggerFactory.getLogger(getClass()); + + protected final ConnectionProvider provider; + protected final int maxAttempts; + protected final Duration maxTotalRetriesDuration; + + public RetryableCommandExecutor(ConnectionProvider provider, int maxAttempts, + Duration maxTotalRetriesDuration) { + this.provider = provider; + this.maxAttempts = maxAttempts; + this.maxTotalRetriesDuration = maxTotalRetriesDuration; + } + + @Override + public void close() { + IOUtils.closeQuietly(this.provider); + } + + @Override + public final T executeCommand(CommandObject commandObject) { + + Instant deadline = Instant.now().plus(maxTotalRetriesDuration); + + int consecutiveConnectionFailures = 0; + JedisException lastException = null; + for (int attemptsLeft = this.maxAttempts; attemptsLeft > 0; attemptsLeft--) { + Connection connection = null; + try { + connection = provider.getConnection(commandObject.getArguments()); + + return connection.executeCommand(commandObject); + + } catch (JedisConnectionException jce) { + lastException = jce; + ++consecutiveConnectionFailures; + log.debug("Failed connecting to Redis: {}", connection, jce); + // "- 1" because we just did one, but the attemptsLeft counter hasn't been decremented yet + boolean reset = handleConnectionProblem(attemptsLeft - 1, consecutiveConnectionFailures, deadline); + if (reset) { + consecutiveConnectionFailures = 0; + } + } finally { + if (connection != null) { + connection.close(); + } + } + if (Instant.now().isAfter(deadline)) { + throw new JedisException("Cluster retry deadline exceeded."); + } + } + + JedisException maxAttemptsException = new JedisException("No more cluster attempts left."); + maxAttemptsException.addSuppressed(lastException); + throw maxAttemptsException; + } + + /** + * Related values should be reset if TRUE is returned. + * + * @param attemptsLeft + * @param consecutiveConnectionFailures + * @param doneDeadline + * @return true - if some actions are taken + *
false - if no actions are taken + */ + private boolean handleConnectionProblem(int attemptsLeft, int consecutiveConnectionFailures, Instant doneDeadline) { + + if (consecutiveConnectionFailures < 2) { + return false; + } + + sleep(getBackoffSleepMillis(attemptsLeft, doneDeadline)); + return true; + } + + private static long getBackoffSleepMillis(int attemptsLeft, Instant deadline) { + if (attemptsLeft <= 0) { + return 0; + } + + long millisLeft = Duration.between(Instant.now(), deadline).toMillis(); + if (millisLeft < 0) { + throw new JedisException("Cluster retry deadline exceeded."); + } + + return millisLeft / (attemptsLeft * (attemptsLeft + 1)); + } + + protected void sleep(long sleepMillis) { + try { + TimeUnit.MILLISECONDS.sleep(sleepMillis); + } catch (InterruptedException e) { + throw new JedisException(e); + } + } +} diff --git a/src/main/java/redis/clients/jedis/executors/SimpleCommandExecutor.java b/src/main/java/redis/clients/jedis/executors/SimpleCommandExecutor.java new file mode 100644 index 0000000000..1390c8cb75 --- /dev/null +++ b/src/main/java/redis/clients/jedis/executors/SimpleCommandExecutor.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.executors; + +import redis.clients.jedis.CommandObject; +import redis.clients.jedis.Connection; +import redis.clients.jedis.util.IOUtils; + +public class SimpleCommandExecutor implements CommandExecutor { + + protected final Connection connection; + + public SimpleCommandExecutor(Connection connection) { + this.connection = connection; + } + + @Override + public void close() { + IOUtils.closeQuietly(connection); + } + + @Override + public final T executeCommand(CommandObject commandObject) { + return connection.executeCommand(commandObject); + } +} diff --git a/src/main/java/redis/clients/jedis/json/JsonProtocol.java b/src/main/java/redis/clients/jedis/json/JsonProtocol.java new file mode 100644 index 0000000000..c674b5a361 --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/JsonProtocol.java @@ -0,0 +1,36 @@ +package redis.clients.jedis.json; + +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.util.SafeEncoder; + +public class JsonProtocol { + + public enum JsonCommand implements ProtocolCommand { + DEL("JSON.DEL"), + GET("JSON.GET"), + MGET("JSON.MGET"), + SET("JSON.SET"), + TYPE("JSON.TYPE"), + STRAPPEND("JSON.STRAPPEND"), + STRLEN("JSON.STRLEN"), + ARRAPPEND("JSON.ARRAPPEND"), + ARRINDEX("JSON.ARRINDEX"), + ARRINSERT("JSON.ARRINSERT"), + ARRLEN("JSON.ARRLEN"), + ARRPOP("JSON.ARRPOP"), + ARRTRIM("JSON.ARRTRIM"), + CLEAR("JSON.CLEAR"), + TOGGLE("JSON.TOGGLE"); + + private final byte[] raw; + + private JsonCommand(String alt) { + raw = SafeEncoder.encode(alt); + } + + @Override + public byte[] getRaw() { + return raw; + } + } +} diff --git a/src/main/java/redis/clients/jedis/json/JsonSetParams.java b/src/main/java/redis/clients/jedis/json/JsonSetParams.java new file mode 100644 index 0000000000..ed666c7dcc --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/JsonSetParams.java @@ -0,0 +1,39 @@ +package redis.clients.jedis.json; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.params.IParams; + +public class JsonSetParams implements IParams { + + private boolean nx = false; + private boolean xx = false; + + public JsonSetParams() { + } + + public static JsonSetParams jsonSetParams() { + return new JsonSetParams(); + } + + public JsonSetParams nx() { + this.nx = true; + this.xx = false; + return this; + } + + public JsonSetParams xx() { + this.nx = false; + this.xx = true; + return this; + } + + @Override + public void addParams(CommandArguments args) { + if (nx) { + args.add("NX"); + } + if (xx) { + args.add("XX"); + } + } +} diff --git a/src/main/java/redis/clients/jedis/json/Path.java b/src/main/java/redis/clients/jedis/json/Path.java new file mode 100644 index 0000000000..e361cab2ea --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/Path.java @@ -0,0 +1,43 @@ +package redis.clients.jedis.json; + +/** + * Path is a ReJSON path, representing a valid path into an object + */ +public class Path { + + public static final Path ROOT_PATH = new Path("."); + + private final String strPath; + + public Path(final String strPath) { + this.strPath = strPath; + } + + @Override + public String toString() { + return strPath; + } + + public static Path of(final String strPath) { + return new Path(strPath); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Path)) { + return false; + } + if (obj == this) { + return true; + } + return this.toString().equals(((Path) obj).toString()); + } + + @Override + public int hashCode() { + return strPath.hashCode(); + } +} diff --git a/src/main/java/redis/clients/jedis/json/Path2.java b/src/main/java/redis/clients/jedis/json/Path2.java new file mode 100644 index 0000000000..28211bb470 --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/Path2.java @@ -0,0 +1,55 @@ +package redis.clients.jedis.json; + +/** + * Path is a ReJSON path, representing a valid path into an object + */ +public class Path2 { + + public static final Path2 ROOT_PATH = new Path2("$"); + + private final String str; + + public Path2(final String str) { + if (str == null) { + throw new NullPointerException("Path cannot be null."); + } + if (str.isEmpty()) { + throw new IllegalArgumentException("Path cannot be empty."); + } + if (str.charAt(0) == '$') { + this.str = str; + } else if (str.charAt(0) == '.') { + this.str = '$' + str; + } else { + this.str = "$." + str; + } + } + + @Override + public String toString() { + return str; + } + + public static Path2 of(final String path) { + return new Path2(path); + } + + @Override + public boolean equals(Object obj) { + if (obj == null) { + return false; + } + if (!(obj instanceof Path2)) { + return false; + } + if (obj == this) { + return true; + } + return this.toString().equals(((Path2) obj).toString()); + } + + @Override + public int hashCode() { + return str.hashCode(); + } +} diff --git a/src/main/java/redis/clients/jedis/json/RedisJsonCommands.java b/src/main/java/redis/clients/jedis/json/RedisJsonCommands.java new file mode 100644 index 0000000000..91e0fafbf2 --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/RedisJsonCommands.java @@ -0,0 +1,144 @@ +package redis.clients.jedis.json; + +import java.util.List; +import org.json.JSONArray; +import org.json.JSONObject; + +public interface RedisJsonCommands { + + default String jsonSet(String key, Object object) { + return RedisJsonCommands.this.jsonSet(key, Path2.ROOT_PATH, object); + } + + default String jsonSetWithEscape(String key, Object object) { + return jsonSetWithEscape(key, Path2.ROOT_PATH, object); + } + + default String jsonSetLegacy(String key, Object pojo) { + return jsonSet(key, Path.ROOT_PATH, pojo); + } + + default String jsonSet(String key, Object object, JsonSetParams params) { + return jsonSet(key, Path2.ROOT_PATH, object, params); + } + + default String jsonSetWithEscape(String key, Object object, JsonSetParams params) { + return jsonSetWithEscape(key, Path2.ROOT_PATH, object, params); + } + + default String jsonSetLegacy(String key, Object pojo, JsonSetParams params) { + return jsonSet(key, Path.ROOT_PATH, pojo, params); + } + + String jsonSet(String key, Path2 path, Object object); + + String jsonSetWithEscape(String key, Path2 path, Object object); + + String jsonSet(String key, Path path, Object pojo); + + String jsonSet(String key, Path2 path, Object object, JsonSetParams params); + + String jsonSetWithEscape(String key, Path2 path, Object object, JsonSetParams params); + + String jsonSet(String key, Path path, Object pojo, JsonSetParams params); + + Object jsonGet(String key); + + T jsonGet(String key, Class clazz); + + Object jsonGet(String key, Path2... paths); + + Object jsonGet(String key, Path... paths); + + T jsonGet(String key, Class clazz, Path... paths); + + default List jsonMGet(String... keys) { + return jsonMGet(Path2.ROOT_PATH, keys); + } + + default List jsonMGet(Class clazz, String... keys) { + return jsonMGet(Path.ROOT_PATH, clazz, keys); + } + + List jsonMGet(Path2 path, String... keys); + + List jsonMGet(Path path, Class clazz, String... keys); + + long jsonDel(String key); + + long jsonDel(String key, Path2 path); + + long jsonDel(String key, Path path); + + long jsonClear(String key); + + long jsonClear(String key, Path2 path); + + long jsonClear(String key, Path path); + + List jsonToggle(String key, Path2 path); + + String jsonToggle(String key, Path path); + + Class jsonType(String key); + + List> jsonType(String key, Path2 path); + + Class jsonType(String key, Path path); + + long jsonStrAppend(String key, Object string); + + List jsonStrAppend(String key, Path2 path, Object string); + + long jsonStrAppend(String key, Path path, Object string); + + Long jsonStrLen(String key); + + List jsonStrLen(String key, Path2 path); + + Long jsonStrLen(String key, Path path); + + List jsonArrAppend(String key, Path2 path, Object... objects); + + List jsonArrAppendWithEscape(String key, Path2 path, Object... objects); + + Long jsonArrAppend(String key, Path path, Object... pojos); + + List jsonArrIndex(String key, Path2 path, Object scalar); + + List jsonArrIndexWithEscape(String key, Path2 path, Object scalar); + + long jsonArrIndex(String key, Path path, Object scalar); + + List jsonArrInsert(String key, Path2 path, int index, Object... objects); + + List jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects); + + long jsonArrInsert(String key, Path path, int index, Object... pojos); + + Object jsonArrPop(String key); + + T jsonArrPop(String key, Class clazz); + + List jsonArrPop(String key, Path2 path); + + Object jsonArrPop(String key, Path path); + + T jsonArrPop(String key, Class clazz, Path path); + + List jsonArrPop(String key, Path2 path, int index); + + Object jsonArrPop(String key, Path path, int index); + + T jsonArrPop(String key, Class clazz, Path path, int index); + + Long jsonArrLen(String key); + + List jsonArrLen(String key, Path2 path); + + Long jsonArrLen(String key, Path path); + + List jsonArrTrim(String key, Path2 path, int start, int stop); + + Long jsonArrTrim(String key, Path path, int start, int stop); +} diff --git a/src/main/java/redis/clients/jedis/json/RedisJsonPipelineCommands.java b/src/main/java/redis/clients/jedis/json/RedisJsonPipelineCommands.java new file mode 100644 index 0000000000..e65f914761 --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/RedisJsonPipelineCommands.java @@ -0,0 +1,149 @@ +package redis.clients.jedis.json; + +import org.json.JSONArray; +import redis.clients.jedis.Response; + +import java.util.List; + +public interface RedisJsonPipelineCommands { + + default Response jsonSet(String key, Object object) { + return RedisJsonPipelineCommands.this.jsonSet(key, Path2.ROOT_PATH, object); + } + + default Response jsonSetWithEscape(String key, Object object) { + return jsonSetWithEscape(key, Path2.ROOT_PATH, object); + } + + default Response jsonSetLegacy(String key, Object pojo) { + return jsonSet(key, Path.ROOT_PATH, pojo); + } + + default Response jsonSet(String key, Object object, JsonSetParams params) { + return jsonSet(key, Path2.ROOT_PATH, object, params); + } + + default Response jsonSetWithEscape(String key, Object object, JsonSetParams params) { + return jsonSetWithEscape(key, Path2.ROOT_PATH, object, params); + } + + default Response jsonSetLegacy(String key, Object pojo, JsonSetParams params) { + return jsonSet(key, Path.ROOT_PATH, pojo, params); + } + + // Response jsonGet(String key); + + // Response jsonGet(String key, Path... paths); + + Response jsonSet(String key, Path2 path, Object object); + + Response jsonSetWithEscape(String key, Path2 path, Object object); + + Response jsonSet(String key, Path path, Object pojo); + + Response jsonSet(String key, Path2 path, Object object, JsonSetParams params); + + Response jsonSetWithEscape(String key, Path2 path, Object object, JsonSetParams params); + + Response jsonSet(String key, Path path, Object pojo, JsonSetParams params); + + Response jsonGet(String key); + + Response jsonGet(String key, Class clazz); + + Response jsonGet(String key, Path2... paths); + + Response jsonGet(String key, Path... paths); + + Response jsonGet(String key, Class clazz, Path... paths); + + default Response> jsonMGet(String... keys) { + return jsonMGet(Path2.ROOT_PATH, keys); + } + + default Response> jsonMGet(Class clazz, String... keys) { + return jsonMGet(Path.ROOT_PATH, clazz, keys); + } + + Response> jsonMGet(Path2 path, String... keys); + + Response> jsonMGet(Path path, Class clazz, String... keys); + + Response jsonDel(String key); + + Response jsonDel(String key, Path2 path); + + Response jsonDel(String key, Path path); + + Response jsonClear(String key); + + Response jsonClear(String key, Path2 path); + + Response jsonClear(String key, Path path); + + Response> jsonToggle(String key, Path2 path); + + Response jsonToggle(String key, Path path); + + Response> jsonType(String key); + + Response>> jsonType(String key, Path2 path); + + Response> jsonType(String key, Path path); + + Response jsonStrAppend(String key, Object string); + + Response> jsonStrAppend(String key, Path2 path, Object string); + + Response jsonStrAppend(String key, Path path, Object string); + + Response jsonStrLen(String key); + + Response> jsonStrLen(String key, Path2 path); + + Response jsonStrLen(String key, Path path); + + Response> jsonArrAppend(String key, Path2 path, Object... objects); + + Response> jsonArrAppendWithEscape(String key, Path2 path, Object... objects); + + Response jsonArrAppend(String key, Path path, Object... pojos); + + Response> jsonArrIndex(String key, Path2 path, Object scalar); + + Response> jsonArrIndexWithEscape(String key, Path2 path, Object scalar); + + Response jsonArrIndex(String key, Path path, Object scalar); + + Response> jsonArrInsert(String key, Path2 path, int index, Object... objects); + + Response> jsonArrInsertWithEscape(String key, Path2 path, int index, Object... objects); + + Response jsonArrInsert(String key, Path path, int index, Object... pojos); + + Response jsonArrPop(String key); + + Response jsonArrPop(String key, Class clazz); + + Response> jsonArrPop(String key, Path2 path); + + Response jsonArrPop(String key, Path path); + + Response jsonArrPop(String key, Class clazz, Path path); + + Response> jsonArrPop(String key, Path2 path, int index); + + Response jsonArrPop(String key, Path path, int index); + + Response jsonArrPop(String key, Class clazz, Path path, int index); + + Response jsonArrLen(String key); + + Response> jsonArrLen(String key, Path2 path); + + Response jsonArrLen(String key, Path path); + + Response> jsonArrTrim(String key, Path2 path, int start, int stop); + + Response jsonArrTrim(String key, Path path, int start, int stop); +} diff --git a/src/main/java/redis/clients/jedis/json/package-info.java b/src/main/java/redis/clients/jedis/json/package-info.java new file mode 100644 index 0000000000..7b19d4b471 --- /dev/null +++ b/src/main/java/redis/clients/jedis/json/package-info.java @@ -0,0 +1,4 @@ +/* + * This package contains the classes related to RedisJSON module. + */ +package redis.clients.jedis.json; diff --git a/src/main/java/redis/clients/jedis/params/BitPosParams.java b/src/main/java/redis/clients/jedis/params/BitPosParams.java new file mode 100644 index 0000000000..920eaa1562 --- /dev/null +++ b/src/main/java/redis/clients/jedis/params/BitPosParams.java @@ -0,0 +1,30 @@ +package redis.clients.jedis.params; + +import java.util.ArrayList; +import java.util.List; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol; + +public class BitPosParams implements IParams { + private List params = new ArrayList<>(); + + public BitPosParams() { + } + + public BitPosParams(long start) { + params.add(Protocol.toByteArray(start)); + } + + public BitPosParams(long start, long end) { + this(start); + + params.add(Protocol.toByteArray(end)); + } + + @Override + public void addParams(CommandArguments args) { + for (byte[] param : params) { + args.add(param); + } + } +} diff --git a/src/main/java/redis/clients/jedis/params/FailoverParams.java b/src/main/java/redis/clients/jedis/params/FailoverParams.java index 9f2dc90d56..ba956d38a5 100644 --- a/src/main/java/redis/clients/jedis/params/FailoverParams.java +++ b/src/main/java/redis/clients/jedis/params/FailoverParams.java @@ -1,13 +1,12 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.List; +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Protocol; import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.util.SafeEncoder; -public class FailoverParams { +public class FailoverParams implements IParams { private HostAndPort to; @@ -41,13 +40,13 @@ public FailoverParams timeout(long timeout) { return this; } - public byte[][] getByteParams() { - List params = new ArrayList<>(); + @Override + public void addParams(CommandArguments args) { if (to != null) { - params.add(Keyword.TO.getRaw()); - params.add(SafeEncoder.encode(to.getHost())); - params.add(Protocol.toByteArray(to.getPort())); + args.add(Keyword.TO.getRaw()); + args.add(SafeEncoder.encode(to.getHost())); + args.add(Protocol.toByteArray(to.getPort())); } @@ -55,14 +54,13 @@ public byte[][] getByteParams() { if (to == null || timeout == null) { throw new IllegalStateException("ERR FAILOVER with force option requires both a timeout and target HOST and IP."); } - params.add(Keyword.FORCE.getRaw()); + args.add(Keyword.FORCE.getRaw()); } if (timeout != null) { - params.add(Keyword.TIMEOUT.getRaw()); - params.add(Protocol.toByteArray(timeout)); + args.add(Keyword.TIMEOUT.getRaw()); + args.add(Protocol.toByteArray(timeout)); } - return params.toArray(new byte[params.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/GeoAddParams.java b/src/main/java/redis/clients/jedis/params/GeoAddParams.java index c9290a14dc..920d986d26 100644 --- a/src/main/java/redis/clients/jedis/params/GeoAddParams.java +++ b/src/main/java/redis/clients/jedis/params/GeoAddParams.java @@ -1,16 +1,16 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; +import static redis.clients.jedis.Protocol.Keyword.CH; +import static redis.clients.jedis.Protocol.Keyword.NX; +import static redis.clients.jedis.Protocol.Keyword.XX; -import redis.clients.jedis.util.SafeEncoder; +import redis.clients.jedis.CommandArguments; -public class GeoAddParams extends Params { +public class GeoAddParams implements IParams { - private static final String NX = "nx"; - private static final String XX = "xx"; - private static final String CH = "ch"; + private boolean nx = false; + private boolean xx = false; + private boolean ch = false; public GeoAddParams() { } @@ -24,7 +24,7 @@ public static GeoAddParams geoAddParams() { * @return GetExParams */ public GeoAddParams nx() { - addParam(NX); + this.nx = true; return this; } @@ -33,7 +33,7 @@ public GeoAddParams nx() { * @return GetExParams */ public GeoAddParams xx() { - addParam(XX); + this.xx = true; return this; } @@ -43,27 +43,21 @@ public GeoAddParams xx() { * @return GetExParams */ public GeoAddParams ch() { - addParam(CH); + this.ch = true; return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - - if (contains(NX)) { - byteParams.add(SafeEncoder.encode(NX)); - } else if (contains(XX)) { - byteParams.add(SafeEncoder.encode(XX)); + @Override + public void addParams(CommandArguments args) { + if (nx) { + args.add(NX); + } else if (xx) { + args.add(XX); } - if (contains(CH)) { - byteParams.add(SafeEncoder.encode(CH)); + if (ch) { + args.add(CH); } - - Collections.addAll(byteParams, args); - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/GeoRadiusParam.java b/src/main/java/redis/clients/jedis/params/GeoRadiusParam.java index 29ab4b0950..cd20707531 100644 --- a/src/main/java/redis/clients/jedis/params/GeoRadiusParam.java +++ b/src/main/java/redis/clients/jedis/params/GeoRadiusParam.java @@ -1,19 +1,23 @@ package redis.clients.jedis.params; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.util.SafeEncoder; +import static redis.clients.jedis.Protocol.Keyword.ASC; +import static redis.clients.jedis.Protocol.Keyword.COUNT; +import static redis.clients.jedis.Protocol.Keyword.DESC; +import static redis.clients.jedis.Protocol.Keyword.WITHCOORD; +import static redis.clients.jedis.Protocol.Keyword.WITHDIST; +import static redis.clients.jedis.Protocol.Keyword.WITHHASH; -import java.util.ArrayList; -import java.util.Collections; +import redis.clients.jedis.CommandArguments; -public class GeoRadiusParam extends Params { - private static final String WITHCOORD = "withcoord"; - private static final String WITHDIST = "withdist"; - private static final String WITHHASH = "withhash"; +public class GeoRadiusParam implements IParams { - private static final String ASC = "asc"; - private static final String DESC = "desc"; - private static final String COUNT = "count"; + private boolean withCoord = false; + private boolean withDist = false; + private boolean withHash = false; + + private Integer count = null; + private boolean asc = false; + private boolean desc = false; public GeoRadiusParam() { } @@ -23,62 +27,58 @@ public static GeoRadiusParam geoRadiusParam() { } public GeoRadiusParam withCoord() { - addParam(WITHCOORD); + withCoord = true; return this; } public GeoRadiusParam withDist() { - addParam(WITHDIST); + withDist = true; return this; } public GeoRadiusParam withHash() { - addParam(WITHHASH); + withHash = true; return this; } public GeoRadiusParam sortAscending() { - addParam(ASC); + asc = true; return this; } public GeoRadiusParam sortDescending() { - addParam(DESC); + desc = true; return this; } public GeoRadiusParam count(int count) { if (count > 0) { - addParam(COUNT, count); + this.count = count; } return this; } - public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); + @Override + public void addParams(CommandArguments args) { - if (contains(WITHCOORD)) { - byteParams.add(SafeEncoder.encode(WITHCOORD)); + if (withCoord) { + args.add(WITHCOORD); } - if (contains(WITHDIST)) { - byteParams.add(SafeEncoder.encode(WITHDIST)); + if (withDist) { + args.add(WITHDIST); } - if (contains(WITHHASH)) { - byteParams.add(SafeEncoder.encode(WITHHASH)); + if (withHash) { + args.add(WITHHASH); } - if (contains(COUNT)) { - byteParams.add(SafeEncoder.encode(COUNT)); - byteParams.add(Protocol.toByteArray((int) getParam(COUNT))); + if (count != null) { + args.add(COUNT).add(count); } - if (contains(ASC)) { - byteParams.add(SafeEncoder.encode(ASC)); - } else if (contains(DESC)) { - byteParams.add(SafeEncoder.encode(DESC)); + if (asc) { + args.add(ASC); + } else if (desc) { + args.add(DESC); } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/GeoRadiusStoreParam.java b/src/main/java/redis/clients/jedis/params/GeoRadiusStoreParam.java index 789bb924a3..fd1cec0681 100644 --- a/src/main/java/redis/clients/jedis/params/GeoRadiusStoreParam.java +++ b/src/main/java/redis/clients/jedis/params/GeoRadiusStoreParam.java @@ -1,15 +1,14 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; +import redis.clients.jedis.CommandArguments; +import static redis.clients.jedis.Protocol.Keyword.STORE; +import static redis.clients.jedis.Protocol.Keyword.STOREDIST; -import redis.clients.jedis.util.SafeEncoder; +public class GeoRadiusStoreParam implements IParams { -public class GeoRadiusStoreParam extends Params { - private static final String STORE = "store"; - private static final String STOREDIST = "storedist"; + private boolean store = false; + private boolean storeDist = false; + private String key; public GeoRadiusStoreParam() { } @@ -20,14 +19,16 @@ public static GeoRadiusStoreParam geoRadiusStoreParam() { public GeoRadiusStoreParam store(String key) { if (key != null) { - addParam(STORE, key); + this.store = true; + this.key = key; } return this; } public GeoRadiusStoreParam storeDist(String key) { if (key != null) { - addParam(STOREDIST, key); + this.storeDist = true; + this.key = key; } return this; } @@ -37,76 +38,17 @@ public GeoRadiusStoreParam storeDist(String key) { *

* Refer: https://github.com/antirez/redis/blob/6.0/src/geo.c#L649 * - * @return STORE or STOREDIST + * @param args */ - public byte[] getOption() { - if (contains(STOREDIST)) { - return SafeEncoder.encode(STOREDIST); + @Override + public void addParams(CommandArguments args) { + if (storeDist) { + args.add(STOREDIST).key(key); + } else if (store) { + args.add(STORE).key(key); + } else { + throw new IllegalArgumentException(this.getClass().getSimpleName() + + " must has store or storedist option"); } - - if (contains(STORE)) { - return SafeEncoder.encode(STORE); - } - - throw new IllegalArgumentException(this.getClass().getSimpleName() - + " must has store or storedist option"); - } - - public byte[] getKey() { - if (contains(STOREDIST)) { - return SafeEncoder.encode((String) getParam(STOREDIST)); - } - - if (contains(STORE)) { - return SafeEncoder.encode((String) getParam(STORE)); - } - - throw new IllegalArgumentException(this.getClass().getSimpleName() - + " must has store or storedist key"); - } - - public String[] getStringKeys(String key) { - List keys = new LinkedList<>(); - keys.add(key); - - if (contains(STORE)) { - keys.add((String) getParam(STORE)); - } - - if (contains(STOREDIST)) { - keys.add((String) getParam(STOREDIST)); - } - return keys.toArray(new String[keys.size()]); - } - - public byte[][] getByteKeys(byte[] key) { - List keys = new LinkedList<>(); - keys.add(key); - - if (contains(STORE)) { - keys.add(SafeEncoder.encode((String) getParam(STORE))); - } - - if (contains(STOREDIST)) { - keys.add(SafeEncoder.encode((String) getParam(STOREDIST))); - } - return keys.toArray(new byte[keys.size()][]); - } - - public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); - - if (contains(STORE)) { - byteParams.add(SafeEncoder.encode(STORE)); - byteParams.add(SafeEncoder.encode((String) getParam(STORE))); - } - - if (contains(STOREDIST)) { - byteParams.add(SafeEncoder.encode(STOREDIST)); - byteParams.add(SafeEncoder.encode((String) getParam(STOREDIST))); - } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/GetExParams.java b/src/main/java/redis/clients/jedis/params/GetExParams.java index 70f51ac382..c985ff0a54 100644 --- a/src/main/java/redis/clients/jedis/params/GetExParams.java +++ b/src/main/java/redis/clients/jedis/params/GetExParams.java @@ -1,12 +1,10 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; import redis.clients.jedis.util.SafeEncoder; -public class GetExParams extends Params { +public class GetExParams extends Params implements IParams { private static final String PX = "px"; private static final String EX = "ex"; @@ -68,29 +66,23 @@ public GetExParams persist() { return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - byteParams.add(key); - + @Override + public void addParams(CommandArguments args) { if (contains(EX)) { - byteParams.add(SafeEncoder.encode(EX)); - byteParams.add(Protocol.toByteArray((long) getParam(EX))); + args.add(SafeEncoder.encode(EX)); + args.add(Protocol.toByteArray((long) getParam(EX))); } else if (contains(PX)) { - byteParams.add(SafeEncoder.encode(PX)); - byteParams.add(Protocol.toByteArray((long) getParam(PX))); + args.add(SafeEncoder.encode(PX)); + args.add(Protocol.toByteArray((long) getParam(PX))); } else if (contains(EXAT)) { - byteParams.add(SafeEncoder.encode(EXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(EXAT))); + args.add(SafeEncoder.encode(EXAT)); + args.add(Protocol.toByteArray((long) getParam(EXAT))); } else if (contains(PXAT)) { - byteParams.add(SafeEncoder.encode(PXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(PXAT))); + args.add(SafeEncoder.encode(PXAT)); + args.add(Protocol.toByteArray((long) getParam(PXAT))); } else if (contains(PERSIST)) { - byteParams.add(SafeEncoder.encode(PERSIST)); + args.add(SafeEncoder.encode(PERSIST)); } - - Collections.addAll(byteParams, args); - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/IParams.java b/src/main/java/redis/clients/jedis/params/IParams.java new file mode 100644 index 0000000000..57a0c7eca3 --- /dev/null +++ b/src/main/java/redis/clients/jedis/params/IParams.java @@ -0,0 +1,8 @@ +package redis.clients.jedis.params; + +import redis.clients.jedis.CommandArguments; + +public interface IParams { + + void addParams(CommandArguments args); +} diff --git a/src/main/java/redis/clients/jedis/params/LPosParams.java b/src/main/java/redis/clients/jedis/params/LPosParams.java index 5f814770d6..f1291a5781 100644 --- a/src/main/java/redis/clients/jedis/params/LPosParams.java +++ b/src/main/java/redis/clients/jedis/params/LPosParams.java @@ -1,12 +1,9 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; -import redis.clients.jedis.util.SafeEncoder; -public class LPosParams extends Params { +public class LPosParams extends Params implements IParams { private static final String RANK = "RANK"; private static final String MAXLEN = "MAXLEN"; @@ -25,21 +22,17 @@ public LPosParams maxlen(int maxLen) { return this; } - public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); - + @Override + public void addParams(CommandArguments args) { if (contains(RANK)) { - byteParams.add(SafeEncoder.encode(RANK)); - byteParams.add(Protocol.toByteArray((int) getParam(RANK))); + args.add(RANK); + args.add(Protocol.toByteArray((int) getParam(RANK))); } if (contains(MAXLEN)) { - byteParams.add(SafeEncoder.encode(MAXLEN)); - byteParams.add(Protocol.toByteArray((int) getParam(MAXLEN))); + args.add(MAXLEN); + args.add(Protocol.toByteArray((int) getParam(MAXLEN))); } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/MigrateParams.java b/src/main/java/redis/clients/jedis/params/MigrateParams.java index 63fe04b6df..b2f872c1f9 100644 --- a/src/main/java/redis/clients/jedis/params/MigrateParams.java +++ b/src/main/java/redis/clients/jedis/params/MigrateParams.java @@ -1,16 +1,18 @@ package redis.clients.jedis.params; -import redis.clients.jedis.util.SafeEncoder; +import static redis.clients.jedis.Protocol.Keyword.AUTH; +import static redis.clients.jedis.Protocol.Keyword.AUTH2; +import static redis.clients.jedis.Protocol.Keyword.COPY; +import static redis.clients.jedis.Protocol.Keyword.REPLACE; -import java.util.ArrayList; -import java.util.List; +import redis.clients.jedis.CommandArguments; -public class MigrateParams extends Params { +public class MigrateParams implements IParams { - private static final String COPY = "COPY"; - private static final String REPLACE = "REPLACE"; - private static final String AUTH = "AUTH"; - private static final String AUTH2 = "AUTH2"; + private boolean copy = false; + private boolean replace = false; + private String username = null; + private String passowrd = null; public MigrateParams() { } @@ -20,45 +22,38 @@ public static MigrateParams migrateParams() { } public MigrateParams copy() { - addParam(COPY); + this.copy = true; return this; } public MigrateParams replace() { - addParam(REPLACE); + this.replace = true; return this; } public MigrateParams auth(String password) { - addParam(AUTH, password); + this.passowrd = password; return this; } public MigrateParams auth2(String username, String password) { - addParam(AUTH2, new String[] { username, password }); + this.username = username; + this.passowrd = password; return this; } @Override - public byte[][] getByteParams() { - List byteParams = new ArrayList<>(); - - if (contains(COPY)) { - byteParams.add(SafeEncoder.encode(COPY)); + public void addParams(CommandArguments args) { + if (copy) { + args.add(COPY); } - if (contains(REPLACE)) { - byteParams.add(SafeEncoder.encode(REPLACE)); + if (replace) { + args.add(REPLACE); } - if (contains(AUTH)) { - byteParams.add(SafeEncoder.encode(AUTH)); - byteParams.add(SafeEncoder.encode((String) getParam(AUTH))); - } else if (contains(AUTH2)) { - byteParams.add(SafeEncoder.encode(AUTH2)); - String[] nameAndPass = (String[]) getParam(AUTH2); - byteParams.add(SafeEncoder.encode(nameAndPass[0])); - byteParams.add(SafeEncoder.encode(nameAndPass[1])); + if (username != null) { + args.add(AUTH2).add(username).add(passowrd); + } else if (passowrd != null) { + args.add(AUTH).add(passowrd); } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/RestoreParams.java b/src/main/java/redis/clients/jedis/params/RestoreParams.java index 58e9f12ec8..1acfc185d8 100644 --- a/src/main/java/redis/clients/jedis/params/RestoreParams.java +++ b/src/main/java/redis/clients/jedis/params/RestoreParams.java @@ -5,13 +5,10 @@ import static redis.clients.jedis.Protocol.Keyword.IDLETIME; import static redis.clients.jedis.Protocol.Keyword.REPLACE; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; -public class RestoreParams extends Params { +public class RestoreParams implements IParams { private boolean replace; @@ -45,28 +42,24 @@ public RestoreParams frequency(long frequency) { return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - Collections.addAll(byteParams, args); - + @Override + public void addParams(CommandArguments args) { if (replace) { - byteParams.add(REPLACE.getRaw()); + args.add(REPLACE.getRaw()); } if (absTtl) { - byteParams.add(ABSTTL.getRaw()); + args.add(ABSTTL.getRaw()); } if (idleTime != null) { - byteParams.add(IDLETIME.getRaw()); - byteParams.add(Protocol.toByteArray(idleTime)); + args.add(IDLETIME.getRaw()); + args.add(Protocol.toByteArray(idleTime)); } if (frequency != null) { - byteParams.add(FREQ.getRaw()); - byteParams.add(Protocol.toByteArray(frequency)); + args.add(FREQ.getRaw()); + args.add(Protocol.toByteArray(frequency)); } - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/ScanParams.java b/src/main/java/redis/clients/jedis/params/ScanParams.java similarity index 72% rename from src/main/java/redis/clients/jedis/ScanParams.java rename to src/main/java/redis/clients/jedis/params/ScanParams.java index 626ca3fdbe..8efd384f46 100644 --- a/src/main/java/redis/clients/jedis/ScanParams.java +++ b/src/main/java/redis/clients/jedis/params/ScanParams.java @@ -1,21 +1,19 @@ -package redis.clients.jedis; +package redis.clients.jedis.params; import static redis.clients.jedis.Protocol.Keyword.COUNT; import static redis.clients.jedis.Protocol.Keyword.MATCH; -import redis.clients.jedis.Protocol.Keyword; - import java.nio.ByteBuffer; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.EnumMap; -import java.util.List; import java.util.Map; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.Protocol; + import redis.clients.jedis.util.SafeEncoder; -public class ScanParams { +public class ScanParams implements IParams { private final Map params = new EnumMap<>(Keyword.class); @@ -49,16 +47,15 @@ public ScanParams count(final Integer count) { return this; } - public Collection getParams() { - List paramsList = new ArrayList<>(params.size()); + @Override + public void addParams(CommandArguments args) { for (Map.Entry param : params.entrySet()) { - paramsList.add(param.getKey().getRaw()); - paramsList.add(param.getValue().array()); + args.add(param.getKey()); + args.add(param.getValue().array()); } - return Collections.unmodifiableCollection(paramsList); } - byte[] binaryMatch() { + public byte[] binaryMatch() { if (params.containsKey(MATCH)) { return params.get(MATCH).array(); } else { @@ -66,19 +63,11 @@ byte[] binaryMatch() { } } - String match() { + public String match() { if (params.containsKey(MATCH)) { return new String(params.get(MATCH).array()); } else { return null; } } - - Integer count() { - if (params.containsKey(COUNT)) { - return params.get(COUNT).getInt(); - } else { - return null; - } - } } diff --git a/src/main/java/redis/clients/jedis/params/SetParams.java b/src/main/java/redis/clients/jedis/params/SetParams.java index 4b4aab1408..015f157555 100644 --- a/src/main/java/redis/clients/jedis/params/SetParams.java +++ b/src/main/java/redis/clients/jedis/params/SetParams.java @@ -1,12 +1,10 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; -import redis.clients.jedis.util.SafeEncoder; +import redis.clients.jedis.Protocol.Keyword; -public class SetParams extends Params { +public class SetParams extends Params implements IParams { private static final String XX = "xx"; private static final String NX = "nx"; @@ -111,42 +109,38 @@ public SetParams get() { return this; } - public byte[][] getByteParams(byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - Collections.addAll(byteParams, args); - + @Override + public void addParams(CommandArguments args) { if (contains(NX)) { - byteParams.add(SafeEncoder.encode(NX)); + args.add(Keyword.NX); } if (contains(XX)) { - byteParams.add(SafeEncoder.encode(XX)); + args.add(Keyword.XX); } if (contains(EX)) { - byteParams.add(SafeEncoder.encode(EX)); - byteParams.add(Protocol.toByteArray((long) getParam(EX))); + args.add(Keyword.EX); + args.add(Protocol.toByteArray((long) getParam(EX))); } if (contains(PX)) { - byteParams.add(SafeEncoder.encode(PX)); - byteParams.add(Protocol.toByteArray((long) getParam(PX))); + args.add(Keyword.PX); + args.add(Protocol.toByteArray((long) getParam(PX))); } if (contains(EXAT)) { - byteParams.add(SafeEncoder.encode(EXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(EXAT))); + args.add(Keyword.EXAT); + args.add(Protocol.toByteArray((long) getParam(EXAT))); } if (contains(PXAT)) { - byteParams.add(SafeEncoder.encode(PXAT)); - byteParams.add(Protocol.toByteArray((long) getParam(PXAT))); + args.add(Keyword.PXAT); + args.add(Protocol.toByteArray((long) getParam(PXAT))); } if (contains(KEEPTTL)) { - byteParams.add(SafeEncoder.encode(KEEPTTL)); + args.add(Keyword.KEEPTTL); } if (contains(GET)) { - byteParams.add(SafeEncoder.encode(GET)); + args.add(Keyword.GET); } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/SortingParams.java b/src/main/java/redis/clients/jedis/params/SortingParams.java similarity index 94% rename from src/main/java/redis/clients/jedis/SortingParams.java rename to src/main/java/redis/clients/jedis/params/SortingParams.java index e7760d73a8..f732f93a47 100644 --- a/src/main/java/redis/clients/jedis/SortingParams.java +++ b/src/main/java/redis/clients/jedis/params/SortingParams.java @@ -1,4 +1,4 @@ -package redis.clients.jedis; +package redis.clients.jedis.params; import static redis.clients.jedis.Protocol.Keyword.ALPHA; import static redis.clients.jedis.Protocol.Keyword.ASC; @@ -13,12 +13,14 @@ import java.util.Collections; import java.util.List; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol; import redis.clients.jedis.util.SafeEncoder; /** * Builder Class for {@link Jedis#sort(String, SortingParams) SORT} Parameters. */ -public class SortingParams { +public class SortingParams implements IParams { private final List params = new ArrayList<>(); /** @@ -156,4 +158,11 @@ public SortingParams get(byte[]... patterns) { } return this; } + + @Override + public void addParams(CommandArguments args) { + for (byte[] param : params) { + args.add(param); + } + } } diff --git a/src/main/java/redis/clients/jedis/params/StrAlgoLCSParams.java b/src/main/java/redis/clients/jedis/params/StrAlgoLCSParams.java index e75a5a9093..ad24a87bd3 100644 --- a/src/main/java/redis/clients/jedis/params/StrAlgoLCSParams.java +++ b/src/main/java/redis/clients/jedis/params/StrAlgoLCSParams.java @@ -1,15 +1,10 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; -import redis.clients.jedis.Protocol.Keyword; -import redis.clients.jedis.util.SafeEncoder; -public class StrAlgoLCSParams extends Params { +public class StrAlgoLCSParams extends Params implements IParams { - private static final String LCS = "lcs"; private static final String IDX = "idx"; private static final String LEN = "len"; private static final String WITHMATCHLEN = "withmatchlen"; @@ -60,28 +55,21 @@ public StrAlgoLCSParams minMatchLen(long minMatchLen) { return this; } - public byte[][] getByteParams(Keyword keyword, byte[] argA, byte[] argB) { - ArrayList byteParams = new ArrayList<>(); - byteParams.add(SafeEncoder.encode(LCS)); - byteParams.add(keyword.getRaw()); - byteParams.add(argA); - byteParams.add(argB); - + @Override + public void addParams(CommandArguments args) { if (contains(IDX)) { - byteParams.add(SafeEncoder.encode(IDX)); + args.add(IDX); } if (contains(LEN)) { - byteParams.add(SafeEncoder.encode(LEN)); + args.add(LEN); } if (contains(WITHMATCHLEN)) { - byteParams.add(SafeEncoder.encode(WITHMATCHLEN)); + args.add(WITHMATCHLEN); } if (contains(MINMATCHLEN)) { - byteParams.add(SafeEncoder.encode(MINMATCHLEN)); - byteParams.add(Protocol.toByteArray((long) getParam(MINMATCHLEN))); + args.add(MINMATCHLEN); + args.add(Protocol.toByteArray((long) getParam(MINMATCHLEN))); } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/XAddParams.java b/src/main/java/redis/clients/jedis/params/XAddParams.java index 5647b0cfd7..09a7cb0950 100644 --- a/src/main/java/redis/clients/jedis/params/XAddParams.java +++ b/src/main/java/redis/clients/jedis/params/XAddParams.java @@ -5,14 +5,11 @@ import static redis.clients.jedis.Protocol.Keyword.MINID; import static redis.clients.jedis.Protocol.Keyword.NOMKSTREAM; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; import redis.clients.jedis.util.SafeEncoder; -public class XAddParams extends Params { +public class XAddParams implements IParams { private String id; @@ -67,47 +64,42 @@ public XAddParams limit(long limit) { return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - + @Override + public void addParams(CommandArguments args) { if (nomkstream) { - byteParams.add(NOMKSTREAM.getRaw()); + args.add(NOMKSTREAM.getRaw()); } if (maxLen != null) { - byteParams.add(MAXLEN.getRaw()); + args.add(MAXLEN.getRaw()); if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); + args.add(Protocol.BYTES_TILDE); } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); + args.add(Protocol.BYTES_EQUAL); } - byteParams.add(Protocol.toByteArray(maxLen)); + args.add(Protocol.toByteArray(maxLen)); } else if (minId != null) { - byteParams.add(MINID.getRaw()); + args.add(MINID.getRaw()); if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); + args.add(Protocol.BYTES_TILDE); } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); + args.add(Protocol.BYTES_EQUAL); } - byteParams.add(SafeEncoder.encode(minId)); + args.add(SafeEncoder.encode(minId)); } if (limit != null) { - byteParams.add(LIMIT.getRaw()); - byteParams.add(Protocol.toByteArray(limit)); + args.add(LIMIT.getRaw()); + args.add(Protocol.toByteArray(limit)); } if (id != null) { - byteParams.add(SafeEncoder.encode(id)); + args.add(SafeEncoder.encode(id)); } else { - byteParams.add(Protocol.BYTES_ASTERISK); + args.add(Protocol.BYTES_ASTERISK); } - - Collections.addAll(byteParams, args); - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/XAutoClaimParams.java b/src/main/java/redis/clients/jedis/params/XAutoClaimParams.java index 1cfdffcb80..6317cddb6d 100644 --- a/src/main/java/redis/clients/jedis/params/XAutoClaimParams.java +++ b/src/main/java/redis/clients/jedis/params/XAutoClaimParams.java @@ -1,13 +1,10 @@ package redis.clients.jedis.params; -import redis.clients.jedis.Protocol; - -import java.util.ArrayList; -import java.util.List; - import static redis.clients.jedis.Protocol.Keyword.COUNT; -public class XAutoClaimParams extends Params { +import redis.clients.jedis.CommandArguments; + +public class XAutoClaimParams implements IParams { private Integer count; @@ -29,15 +26,10 @@ public XAutoClaimParams count(int count) { } @Override - public byte[][] getByteParams() { - List byteParams = new ArrayList<>(); - + public void addParams(CommandArguments args) { if (count != null) { - byteParams.add(COUNT.getRaw()); - byteParams.add(Protocol.toByteArray(count)); + args.add(COUNT.getRaw()).add(count); } - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/XClaimParams.java b/src/main/java/redis/clients/jedis/params/XClaimParams.java index 69f973d0b4..fb3e68f0f8 100644 --- a/src/main/java/redis/clients/jedis/params/XClaimParams.java +++ b/src/main/java/redis/clients/jedis/params/XClaimParams.java @@ -1,11 +1,18 @@ package redis.clients.jedis.params; -public class XClaimParams extends Params { +import static redis.clients.jedis.Protocol.Keyword.IDLE; +import static redis.clients.jedis.Protocol.Keyword.TIME; +import static redis.clients.jedis.Protocol.Keyword.RETRYCOUNT; +import static redis.clients.jedis.Protocol.Keyword.FORCE; - private static final String IDLE = "IDLE"; - private static final String TIME = "TIME"; - private static final String RETRYCOUNT = "RETRYCOUNT"; - private static final String FORCE = "FORCE"; +import redis.clients.jedis.CommandArguments; + +public class XClaimParams implements IParams { + + private Long idleTime; + private Long idleUnixTime; + private Integer retryCount; + private boolean force; public XClaimParams() { } @@ -20,7 +27,7 @@ public static XClaimParams xClaimParams() { * @return XClaimParams */ public XClaimParams idle(long idleTime) { - addParam(IDLE, idleTime); + this.idleTime = idleTime; return this; } @@ -30,7 +37,7 @@ public XClaimParams idle(long idleTime) { * @return XClaimParams */ public XClaimParams time(long idleUnixTime) { - addParam(TIME, idleUnixTime); + this.idleUnixTime = idleUnixTime; return this; } @@ -40,7 +47,7 @@ public XClaimParams time(long idleUnixTime) { * @return XClaimParams */ public XClaimParams retryCount(int count) { - addParam(RETRYCOUNT, count); + this.retryCount = count; return this; } @@ -50,7 +57,23 @@ public XClaimParams retryCount(int count) { * @return XClaimParams */ public XClaimParams force() { - addParam(FORCE); + this.force = true; return this; } + + @Override + public void addParams(CommandArguments args) { + if (idleTime != null) { + args.add(IDLE).add(idleTime); + } + if (idleUnixTime != null) { + args.add(TIME).add(idleUnixTime); + } + if (retryCount != null) { + args.add(RETRYCOUNT).add(retryCount); + } + if (force) { + args.add(FORCE); + } + } } diff --git a/src/main/java/redis/clients/jedis/params/XPendingParams.java b/src/main/java/redis/clients/jedis/params/XPendingParams.java index fa2d40a571..59273917fb 100644 --- a/src/main/java/redis/clients/jedis/params/XPendingParams.java +++ b/src/main/java/redis/clients/jedis/params/XPendingParams.java @@ -2,14 +2,12 @@ import static redis.clients.jedis.Protocol.Keyword.IDLE; -import java.util.ArrayList; -import java.util.List; - +import redis.clients.jedis.CommandArguments; import redis.clients.jedis.Protocol; import redis.clients.jedis.StreamEntryID; import redis.clients.jedis.util.SafeEncoder; -public class XPendingParams extends Params { +public class XPendingParams implements IParams { private Long idle; @@ -51,33 +49,31 @@ public XPendingParams consumer(String consumer) { } @Override - public byte[][] getByteParams() { - List byteParams = new ArrayList<>(); + public void addParams(CommandArguments args) { if (idle != null) { - byteParams.add(IDLE.getRaw()); - byteParams.add(Protocol.toByteArray(idle)); + args.add(IDLE.getRaw()); + args.add(Protocol.toByteArray(idle)); } if (start == null) { - byteParams.add(SafeEncoder.encode("-")); + args.add(SafeEncoder.encode("-")); } else { - byteParams.add(SafeEncoder.encode(start.toString())); + args.add(SafeEncoder.encode(start.toString())); } if (end == null) { - byteParams.add(SafeEncoder.encode("+")); + args.add(SafeEncoder.encode("+")); } else { - byteParams.add(SafeEncoder.encode(end.toString())); + args.add(SafeEncoder.encode(end.toString())); } if (count != null) { - byteParams.add(Protocol.toByteArray(count)); + args.add(Protocol.toByteArray(count)); } if (consumer != null) { - byteParams.add(SafeEncoder.encode(consumer)); + args.add(SafeEncoder.encode(consumer)); } - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/XReadGroupParams.java b/src/main/java/redis/clients/jedis/params/XReadGroupParams.java index b7124b0276..b53caa585b 100644 --- a/src/main/java/redis/clients/jedis/params/XReadGroupParams.java +++ b/src/main/java/redis/clients/jedis/params/XReadGroupParams.java @@ -1,31 +1,50 @@ package redis.clients.jedis.params; -public class XReadGroupParams extends Params { +import static redis.clients.jedis.Protocol.Keyword.BLOCK; +import static redis.clients.jedis.Protocol.Keyword.COUNT; +import static redis.clients.jedis.Protocol.Keyword.NOACK; +import static redis.clients.jedis.Protocol.toByteArray; - private static final String COUNT = "COUNT"; - private static final String BLOCK = "BLOCK"; - private static final String NOACK = "NOACK"; +import redis.clients.jedis.CommandArguments; + +public class XReadGroupParams implements IParams { + + private Integer count = null; + private Integer block = null; + private boolean noack = false; public static XReadGroupParams xReadGroupParams() { return new XReadGroupParams(); } public XReadGroupParams count(int count) { - addParam(COUNT, count); + this.count = count; return this; } public XReadGroupParams block(int block) { - addParam(BLOCK, block); + this.block = block; return this; } public XReadGroupParams noAck() { - addParam(NOACK); + this.noack = true; return this; } - public boolean hasBlock() { - return super.contains(BLOCK); + @Override + public void addParams(CommandArguments args) { + if (count != null) { + args.add(COUNT); + args.add(toByteArray(count)); + } + if (block != null) { + args.add(BLOCK); + args.add(toByteArray(block)); + args.blocking(); + } + if (noack) { + args.add(NOACK); + } } } diff --git a/src/main/java/redis/clients/jedis/params/XReadParams.java b/src/main/java/redis/clients/jedis/params/XReadParams.java index 4a55940107..9f587005b5 100644 --- a/src/main/java/redis/clients/jedis/params/XReadParams.java +++ b/src/main/java/redis/clients/jedis/params/XReadParams.java @@ -1,25 +1,40 @@ package redis.clients.jedis.params; -public class XReadParams extends Params { +import static redis.clients.jedis.Protocol.Keyword.BLOCK; +import static redis.clients.jedis.Protocol.Keyword.COUNT; +import static redis.clients.jedis.Protocol.toByteArray; - private static final String COUNT = "COUNT"; - private static final String BLOCK = "BLOCK"; +import redis.clients.jedis.CommandArguments; + +public class XReadParams implements IParams { + + private Integer count = null; + private Integer block = null; public static XReadParams xReadParams() { return new XReadParams(); } public XReadParams count(int count) { - addParam(COUNT, count); + this.count = count; return this; } public XReadParams block(int block) { - addParam(BLOCK, block); + this.block = block; return this; } - public boolean hasBlock() { - return super.contains(BLOCK); + @Override + public void addParams(CommandArguments args) { + if (count != null) { + args.add(COUNT); + args.add(toByteArray(count)); + } + if (block != null) { + args.add(BLOCK); + args.add(toByteArray(block)); + args.blocking(); + } } } diff --git a/src/main/java/redis/clients/jedis/params/XTrimParams.java b/src/main/java/redis/clients/jedis/params/XTrimParams.java index 2bdd508d11..27eb3c5b08 100644 --- a/src/main/java/redis/clients/jedis/params/XTrimParams.java +++ b/src/main/java/redis/clients/jedis/params/XTrimParams.java @@ -1,17 +1,14 @@ package redis.clients.jedis.params; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import redis.clients.jedis.Protocol; -import redis.clients.jedis.util.SafeEncoder; - import static redis.clients.jedis.Protocol.Keyword.LIMIT; import static redis.clients.jedis.Protocol.Keyword.MAXLEN; import static redis.clients.jedis.Protocol.Keyword.MINID; -public class XTrimParams extends Params { +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.util.SafeEncoder; + +public class XTrimParams implements IParams { private Long maxLen; @@ -53,38 +50,33 @@ public XTrimParams limit(long limit) { return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - List byteParams = new ArrayList<>(); - byteParams.add(key); - + @Override + public void addParams(CommandArguments args) { if (maxLen != null) { - byteParams.add(MAXLEN.getRaw()); + args.add(MAXLEN.getRaw()); if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); + args.add(Protocol.BYTES_TILDE); } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); + args.add(Protocol.BYTES_EQUAL); } - byteParams.add(Protocol.toByteArray(maxLen)); + args.add(Protocol.toByteArray(maxLen)); } else if (minId != null) { - byteParams.add(MINID.getRaw()); + args.add(MINID.getRaw()); if (approximateTrimming) { - byteParams.add(Protocol.BYTES_TILDE); + args.add(Protocol.BYTES_TILDE); } else if (exactTrimming) { - byteParams.add(Protocol.BYTES_EQUAL); + args.add(Protocol.BYTES_EQUAL); } - byteParams.add(SafeEncoder.encode(minId)); + args.add(SafeEncoder.encode(minId)); } if (limit != null) { - byteParams.add(LIMIT.getRaw()); - byteParams.add(Protocol.toByteArray(limit)); + args.add(LIMIT.getRaw()); + args.add(Protocol.toByteArray(limit)); } - - Collections.addAll(byteParams, args); - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/ZAddParams.java b/src/main/java/redis/clients/jedis/params/ZAddParams.java index 2838fae630..2862c81e57 100644 --- a/src/main/java/redis/clients/jedis/params/ZAddParams.java +++ b/src/main/java/redis/clients/jedis/params/ZAddParams.java @@ -1,11 +1,8 @@ package redis.clients.jedis.params; -import redis.clients.jedis.util.SafeEncoder; +import redis.clients.jedis.CommandArguments; -import java.util.ArrayList; -import java.util.Collections; - -public class ZAddParams extends Params { +public class ZAddParams extends Params implements IParams { private static final String XX = "xx"; private static final String NX = "nx"; @@ -66,29 +63,23 @@ public ZAddParams lt() { return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - byteParams.add(key); - + @Override + public void addParams(CommandArguments args) { if (contains(NX)) { - byteParams.add(SafeEncoder.encode(NX)); + args.add(NX); } if (contains(XX)) { - byteParams.add(SafeEncoder.encode(XX)); + args.add(XX); } if (contains(CH)) { - byteParams.add(SafeEncoder.encode(CH)); + args.add(CH); } if (contains(LT)) { - byteParams.add(SafeEncoder.encode(LT)); + args.add(LT); } if (contains(GT)) { - byteParams.add(SafeEncoder.encode(GT)); + args.add(GT); } - - Collections.addAll(byteParams, args); - - return byteParams.toArray(new byte[byteParams.size()][]); } } diff --git a/src/main/java/redis/clients/jedis/params/ZIncrByParams.java b/src/main/java/redis/clients/jedis/params/ZIncrByParams.java index 8dd3f9a759..d088df548a 100644 --- a/src/main/java/redis/clients/jedis/params/ZIncrByParams.java +++ b/src/main/java/redis/clients/jedis/params/ZIncrByParams.java @@ -1,9 +1,6 @@ package redis.clients.jedis.params; -import redis.clients.jedis.util.SafeEncoder; - -import java.util.ArrayList; -import java.util.Collections; +import redis.clients.jedis.CommandArguments; /** * Parameters for ZINCRBY commands
@@ -19,7 +16,7 @@ *
* Works with Redis 3.0.2 and onwards. */ -public class ZIncrByParams extends Params { +public class ZIncrByParams extends Params implements IParams { private static final String XX = "xx"; private static final String NX = "nx"; @@ -50,21 +47,16 @@ public ZIncrByParams xx() { return this; } - public byte[][] getByteParams(byte[] key, byte[]... args) { - ArrayList byteParams = new ArrayList<>(); - byteParams.add(key); - + @Override + public void addParams(CommandArguments args) { if (contains(NX)) { - byteParams.add(SafeEncoder.encode(NX)); + args.add(NX); } if (contains(XX)) { - byteParams.add(SafeEncoder.encode(XX)); + args.add(XX); } - byteParams.add(SafeEncoder.encode(INCR)); - - Collections.addAll(byteParams, args); - return byteParams.toArray(new byte[byteParams.size()][]); + args.add(INCR); } } diff --git a/src/main/java/redis/clients/jedis/ZParams.java b/src/main/java/redis/clients/jedis/params/ZParams.java similarity index 79% rename from src/main/java/redis/clients/jedis/ZParams.java rename to src/main/java/redis/clients/jedis/params/ZParams.java index 8f74593ca1..b30e1680cf 100644 --- a/src/main/java/redis/clients/jedis/ZParams.java +++ b/src/main/java/redis/clients/jedis/params/ZParams.java @@ -1,16 +1,17 @@ -package redis.clients.jedis; +package redis.clients.jedis.params; import static redis.clients.jedis.Protocol.Keyword.AGGREGATE; import static redis.clients.jedis.Protocol.Keyword.WEIGHTS; import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; import java.util.List; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol; import redis.clients.jedis.util.SafeEncoder; -public class ZParams { +public class ZParams implements IParams { + public enum Aggregate { SUM, MIN, MAX; @@ -45,13 +46,14 @@ public ZParams weights(final double... weights) { return this; } - public Collection getParams() { - return Collections.unmodifiableCollection(params); - } - public ZParams aggregate(final Aggregate aggregate) { params.add(AGGREGATE.getRaw()); params.add(aggregate.raw); return this; } + + @Override + public void addParams(CommandArguments args) { + params.forEach(param -> args.add(param)); + } } diff --git a/src/main/java/redis/clients/jedis/params/package-info.java b/src/main/java/redis/clients/jedis/params/package-info.java new file mode 100644 index 0000000000..3127f0c062 --- /dev/null +++ b/src/main/java/redis/clients/jedis/params/package-info.java @@ -0,0 +1,4 @@ +/* + * This package contains the classes that represent optional parameters of Redis commands. + */ +package redis.clients.jedis.params; diff --git a/src/main/java/redis/clients/jedis/providers/ClusterConnectionProvider.java b/src/main/java/redis/clients/jedis/providers/ClusterConnectionProvider.java new file mode 100644 index 0000000000..aaa22cc4e8 --- /dev/null +++ b/src/main/java/redis/clients/jedis/providers/ClusterConnectionProvider.java @@ -0,0 +1,136 @@ +package redis.clients.jedis.providers; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +import redis.clients.jedis.ClusterCommandArguments; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisClientConfig; +import redis.clients.jedis.Connection; +import redis.clients.jedis.ConnectionPool; +import redis.clients.jedis.JedisClusterInfoCache; +import redis.clients.jedis.exceptions.JedisClusterOperationException; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; + +public class ClusterConnectionProvider implements ConnectionProvider { + + protected final JedisClusterInfoCache cache; + + public ClusterConnectionProvider(Set jedisClusterNodes, JedisClientConfig clientConfig) { + this.cache = new JedisClusterInfoCache(clientConfig); + initializeSlotsCache(jedisClusterNodes, clientConfig); + } + + public ClusterConnectionProvider(Set jedisClusterNodes, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig) { + this.cache = new JedisClusterInfoCache(clientConfig, poolConfig); + initializeSlotsCache(jedisClusterNodes, clientConfig); + } + + private void initializeSlotsCache(Set startNodes, JedisClientConfig clientConfig) { + ArrayList startNodeList = new ArrayList<>(startNodes); + Collections.shuffle(startNodeList); + + for (HostAndPort hostAndPort : startNodeList) { + try (Connection jedis = new Connection(hostAndPort, clientConfig)) { + cache.discoverClusterNodesAndSlots(jedis); + return; + } catch (JedisConnectionException e) { + // try next nodes + } + } + } + + @Override + public void close() { + cache.reset(); + } + + public void renewSlotCache() { + cache.renewClusterSlots(null); + } + + public void renewSlotCache(Connection jedis) { + cache.renewClusterSlots(jedis); + } + + public Map getNodes() { + return cache.getNodes(); + } + + public HostAndPort getNode(int slot) { + return slot >= 0 ? cache.getSlotNode(slot) : null; + } + + public Connection getConnection(HostAndPort node) { + return node != null ? cache.setupNodeIfNotExist(node).getResource() : getConnection(); + } + + @Override + public Connection getConnection(CommandArguments args) { + final int slot = ((ClusterCommandArguments) args).getCommandHashSlot(); + return slot >= 0 ? getConnectionFromSlot(slot) : getConnection(); + } + + @Override + public Connection getConnection() { + // In antirez's redis-rb-cluster implementation, getRandomConnection always + // return valid connection (able to ping-pong) or exception if all + // connections are invalid + + List pools = cache.getShuffledNodesPool(); + + JedisException suppressed = null; + for (ConnectionPool pool : pools) { + Connection jedis = null; + try { + jedis = pool.getResource(); + if (jedis == null) { + continue; + } + + jedis.ping(); + return jedis; + + } catch (JedisException ex) { + if (suppressed == null) { // remembering first suppressed exception + suppressed = ex; + } + if (jedis != null) { + jedis.close(); + } + } + } + + JedisClusterOperationException noReachableNode = new JedisClusterOperationException("No reachable node in cluster."); + if (suppressed != null) { + noReachableNode.addSuppressed(suppressed); + } + throw noReachableNode; + } + + public Connection getConnectionFromSlot(int slot) { + ConnectionPool connectionPool = cache.getSlotPool(slot); + if (connectionPool != null) { + // It can't guaranteed to get valid connection because of node assignment + return connectionPool.getResource(); + } else { + // It's abnormal situation for cluster mode that we have just nothing for slot. + // Try to rediscover state + renewSlotCache(); + connectionPool = cache.getSlotPool(slot); + if (connectionPool != null) { + return connectionPool.getResource(); + } else { + // no choice, fallback to new connection to random node + return getConnection(); + } + } + } +} diff --git a/src/main/java/redis/clients/jedis/providers/ConnectionProvider.java b/src/main/java/redis/clients/jedis/providers/ConnectionProvider.java new file mode 100644 index 0000000000..8efafac33a --- /dev/null +++ b/src/main/java/redis/clients/jedis/providers/ConnectionProvider.java @@ -0,0 +1,11 @@ +package redis.clients.jedis.providers; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Connection; + +public interface ConnectionProvider extends AutoCloseable { + + Connection getConnection(); + + Connection getConnection(CommandArguments args); +} diff --git a/src/main/java/redis/clients/jedis/providers/ManagedConnectionProvider.java b/src/main/java/redis/clients/jedis/providers/ManagedConnectionProvider.java new file mode 100644 index 0000000000..4f35c60cdf --- /dev/null +++ b/src/main/java/redis/clients/jedis/providers/ManagedConnectionProvider.java @@ -0,0 +1,27 @@ +package redis.clients.jedis.providers; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Connection; + +public class ManagedConnectionProvider implements ConnectionProvider { + + private Connection connection; + + public final void setConnection(Connection connection) { + this.connection = connection; + } + + @Override + public void close() { + } + + @Override + public final Connection getConnection() { + return connection; + } + + @Override + public final Connection getConnection(CommandArguments args) { + return connection; + } +} diff --git a/src/main/java/redis/clients/jedis/providers/PooledConnectionProvider.java b/src/main/java/redis/clients/jedis/providers/PooledConnectionProvider.java new file mode 100644 index 0000000000..e14db49471 --- /dev/null +++ b/src/main/java/redis/clients/jedis/providers/PooledConnectionProvider.java @@ -0,0 +1,56 @@ +package redis.clients.jedis.providers; + +import org.apache.commons.pool2.PooledObjectFactory; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Connection; +import redis.clients.jedis.ConnectionFactory; +import redis.clients.jedis.ConnectionPool; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisClientConfig; +import redis.clients.jedis.util.Pool; + +public class PooledConnectionProvider implements ConnectionProvider { + + private final Pool pool; + + public PooledConnectionProvider(HostAndPort hostAndPort) { + this(new ConnectionFactory(hostAndPort)); + } + + public PooledConnectionProvider(HostAndPort hostAndPort, JedisClientConfig clientConfig) { + this(new ConnectionFactory(hostAndPort, clientConfig)); + } + + public PooledConnectionProvider(PooledObjectFactory factory) { + this(factory, new GenericObjectPoolConfig<>()); + } + + public PooledConnectionProvider(PooledObjectFactory factory, GenericObjectPoolConfig poolConfig) { + this(new ConnectionPool(factory, poolConfig)); + } + + private PooledConnectionProvider(Pool pool) { + this.pool = pool; + } + + @Override + public void close() { + pool.close(); + } + + public final Pool getPool() { + return pool; + } + + @Override + public Connection getConnection() { + return pool.getResource(); + } + + @Override + public Connection getConnection(CommandArguments args) { + return pool.getResource(); + } +} diff --git a/src/main/java/redis/clients/jedis/providers/ShardedConnectionProvider.java b/src/main/java/redis/clients/jedis/providers/ShardedConnectionProvider.java new file mode 100644 index 0000000000..b1240a0eb5 --- /dev/null +++ b/src/main/java/redis/clients/jedis/providers/ShardedConnectionProvider.java @@ -0,0 +1,160 @@ +package redis.clients.jedis.providers; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.SortedMap; +import java.util.TreeMap; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.JedisClientConfig; +import redis.clients.jedis.Connection; +import redis.clients.jedis.ConnectionPool; +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.ShardedCommandArguments; +import redis.clients.jedis.exceptions.JedisException; +import redis.clients.jedis.util.Hashing; + +public class ShardedConnectionProvider implements ConnectionProvider { + + private final TreeMap nodes = new TreeMap<>(); + private final Map resources = new HashMap<>(); + private final JedisClientConfig clientConfig; + private final GenericObjectPoolConfig poolConfig; + private final Hashing algo; + + public ShardedConnectionProvider(List shards) { + this(shards, DefaultJedisClientConfig.builder().build()); + } + + public ShardedConnectionProvider(List shards, JedisClientConfig clientConfig) { + this(shards, clientConfig, new GenericObjectPoolConfig()); + } + + public ShardedConnectionProvider(List shards, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig) { + this(shards, clientConfig, poolConfig, Hashing.MURMUR_HASH); + } + + public ShardedConnectionProvider(List shards, JedisClientConfig clientConfig, + Hashing algo) { + this(shards, clientConfig, new GenericObjectPoolConfig(), algo); + } + + public ShardedConnectionProvider(List shards, JedisClientConfig clientConfig, + GenericObjectPoolConfig poolConfig, Hashing algo) { + this.clientConfig = clientConfig; + this.poolConfig = poolConfig; + this.algo = algo; + initialize(shards); + } + + private void initialize(List shards) { + for (int i = 0; i < shards.size(); i++) { + HostAndPort shard = shards.get(i); + for (int n = 0; n < 160; n++) { + Long hash = this.algo.hash("SHARD-" + i + "-NODE-" + n); + nodes.put(hash, shard); + setupNodeIfNotExist(shard); + } + } + } + + private ConnectionPool setupNodeIfNotExist(final HostAndPort node) { + String nodeKey = node.toString(); + ConnectionPool existingPool = resources.get(nodeKey); + if (existingPool != null) return existingPool; + + ConnectionPool nodePool = new ConnectionPool(node, clientConfig, poolConfig); + resources.put(nodeKey, nodePool); + return nodePool; + } + + public Hashing getHashingAlgo() { + return algo; + } + + private void reset() { + for (ConnectionPool pool : resources.values()) { + try { + if (pool != null) { + pool.destroy(); + } + } catch (RuntimeException e) { + // pass + } + } + resources.clear(); + nodes.clear(); + } + + @Override + public void close() { + reset(); + } + + public HostAndPort getNode(Long hash) { + return hash != null ? getNodeFromHash(hash) : null; + } + + public Connection getConnection(HostAndPort node) { + return node != null ? setupNodeIfNotExist(node).getResource() : getConnection(); + } + + @Override + public Connection getConnection(CommandArguments args) { + final Long hash = ((ShardedCommandArguments) args).getKeyHash(); + return hash != null ? getConnection(getNodeFromHash(hash)) : getConnection(); + } + + private List getShuffledNodesPool() { + List pools = new ArrayList<>(resources.values()); + Collections.shuffle(pools); + return pools; + } + + @Override + public Connection getConnection() { + List pools = getShuffledNodesPool(); + + JedisException suppressed = null; + for (ConnectionPool pool : pools) { + Connection jedis = null; + try { + jedis = pool.getResource(); + if (jedis == null) { + continue; + } + + jedis.ping(); + return jedis; + + } catch (JedisException ex) { + if (suppressed == null) { // remembering first suppressed exception + suppressed = ex; + } + if (jedis != null) { + jedis.close(); + } + } + } + + JedisException noReachableNode = new JedisException("No reachable shard."); + if (suppressed != null) { + noReachableNode.addSuppressed(suppressed); + } + throw noReachableNode; + } + + private HostAndPort getNodeFromHash(Long hash) { + SortedMap tail = nodes.tailMap(hash); + if (tail.isEmpty()) { + return nodes.get(nodes.firstKey()); + } + return tail.get(tail.firstKey()); + } +} diff --git a/src/main/java/redis/clients/jedis/AccessControlLogEntry.java b/src/main/java/redis/clients/jedis/resps/AccessControlLogEntry.java similarity index 98% rename from src/main/java/redis/clients/jedis/AccessControlLogEntry.java rename to src/main/java/redis/clients/jedis/resps/AccessControlLogEntry.java index e09f43ea9f..d60359edeb 100644 --- a/src/main/java/redis/clients/jedis/AccessControlLogEntry.java +++ b/src/main/java/redis/clients/jedis/resps/AccessControlLogEntry.java @@ -1,4 +1,4 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.io.Serializable; import java.util.*; diff --git a/src/main/java/redis/clients/jedis/AccessControlUser.java b/src/main/java/redis/clients/jedis/resps/AccessControlUser.java similarity index 96% rename from src/main/java/redis/clients/jedis/AccessControlUser.java rename to src/main/java/redis/clients/jedis/resps/AccessControlUser.java index c515bbde3e..23f877f7a8 100644 --- a/src/main/java/redis/clients/jedis/AccessControlUser.java +++ b/src/main/java/redis/clients/jedis/resps/AccessControlUser.java @@ -1,4 +1,4 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.util.ArrayList; import java.util.List; diff --git a/src/main/java/redis/clients/jedis/GeoRadiusResponse.java b/src/main/java/redis/clients/jedis/resps/GeoRadiusResponse.java similarity index 91% rename from src/main/java/redis/clients/jedis/GeoRadiusResponse.java rename to src/main/java/redis/clients/jedis/resps/GeoRadiusResponse.java index bc3414185b..b8f5dfa997 100644 --- a/src/main/java/redis/clients/jedis/GeoRadiusResponse.java +++ b/src/main/java/redis/clients/jedis/resps/GeoRadiusResponse.java @@ -1,5 +1,6 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; +import redis.clients.jedis.GeoCoordinate; import redis.clients.jedis.util.SafeEncoder; public class GeoRadiusResponse { diff --git a/src/main/java/redis/clients/jedis/resps/KeyedZSetElement.java b/src/main/java/redis/clients/jedis/resps/KeyedZSetElement.java index c7fae57f34..d1639937f1 100644 --- a/src/main/java/redis/clients/jedis/resps/KeyedZSetElement.java +++ b/src/main/java/redis/clients/jedis/resps/KeyedZSetElement.java @@ -1,6 +1,5 @@ package redis.clients.jedis.resps; -import redis.clients.jedis.Tuple; import redis.clients.jedis.util.SafeEncoder; /** diff --git a/src/main/java/redis/clients/jedis/ScanResult.java b/src/main/java/redis/clients/jedis/resps/ScanResult.java similarity index 92% rename from src/main/java/redis/clients/jedis/ScanResult.java rename to src/main/java/redis/clients/jedis/resps/ScanResult.java index 19a3a1035c..0cb8cf5430 100644 --- a/src/main/java/redis/clients/jedis/ScanResult.java +++ b/src/main/java/redis/clients/jedis/resps/ScanResult.java @@ -1,6 +1,7 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.util.List; +import redis.clients.jedis.params.ScanParams; import redis.clients.jedis.util.SafeEncoder; diff --git a/src/main/java/redis/clients/jedis/util/Slowlog.java b/src/main/java/redis/clients/jedis/resps/Slowlog.java similarity index 95% rename from src/main/java/redis/clients/jedis/util/Slowlog.java rename to src/main/java/redis/clients/jedis/resps/Slowlog.java index d32a1b76f7..13898af98d 100644 --- a/src/main/java/redis/clients/jedis/util/Slowlog.java +++ b/src/main/java/redis/clients/jedis/resps/Slowlog.java @@ -1,9 +1,10 @@ -package redis.clients.jedis.util; +package redis.clients.jedis.resps; import java.util.ArrayList; import java.util.List; import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.util.SafeEncoder; public class Slowlog { diff --git a/src/main/java/redis/clients/jedis/StreamConsumersInfo.java b/src/main/java/redis/clients/jedis/resps/StreamConsumersInfo.java similarity index 97% rename from src/main/java/redis/clients/jedis/StreamConsumersInfo.java rename to src/main/java/redis/clients/jedis/resps/StreamConsumersInfo.java index 2cd4251cb7..09239836c5 100644 --- a/src/main/java/redis/clients/jedis/StreamConsumersInfo.java +++ b/src/main/java/redis/clients/jedis/resps/StreamConsumersInfo.java @@ -1,4 +1,4 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.util.Map; diff --git a/src/main/java/redis/clients/jedis/StreamEntry.java b/src/main/java/redis/clients/jedis/resps/StreamEntry.java similarity index 92% rename from src/main/java/redis/clients/jedis/StreamEntry.java rename to src/main/java/redis/clients/jedis/resps/StreamEntry.java index d706f92ee0..0d76ad1e12 100644 --- a/src/main/java/redis/clients/jedis/StreamEntry.java +++ b/src/main/java/redis/clients/jedis/resps/StreamEntry.java @@ -1,8 +1,9 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.io.IOException; import java.io.Serializable; import java.util.Map; +import redis.clients.jedis.StreamEntryID; public class StreamEntry implements Serializable { diff --git a/src/main/java/redis/clients/jedis/StreamGroupInfo.java b/src/main/java/redis/clients/jedis/resps/StreamGroupInfo.java similarity index 95% rename from src/main/java/redis/clients/jedis/StreamGroupInfo.java rename to src/main/java/redis/clients/jedis/resps/StreamGroupInfo.java index 7c01adf76a..1aaaf38f1e 100644 --- a/src/main/java/redis/clients/jedis/StreamGroupInfo.java +++ b/src/main/java/redis/clients/jedis/resps/StreamGroupInfo.java @@ -1,7 +1,8 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.io.Serializable; import java.util.Map; +import redis.clients.jedis.StreamEntryID; /** * This class holds information about a stream group. They can be access via getters. For future diff --git a/src/main/java/redis/clients/jedis/StreamInfo.java b/src/main/java/redis/clients/jedis/resps/StreamInfo.java similarity index 96% rename from src/main/java/redis/clients/jedis/StreamInfo.java rename to src/main/java/redis/clients/jedis/resps/StreamInfo.java index 7d91c98b7f..8d217b7d19 100644 --- a/src/main/java/redis/clients/jedis/StreamInfo.java +++ b/src/main/java/redis/clients/jedis/resps/StreamInfo.java @@ -1,7 +1,8 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.io.Serializable; import java.util.Map; +import redis.clients.jedis.StreamEntryID; /** * This class holds information about stream. They can be access via getters. For future purpose diff --git a/src/main/java/redis/clients/jedis/StreamPendingEntry.java b/src/main/java/redis/clients/jedis/resps/StreamPendingEntry.java similarity index 94% rename from src/main/java/redis/clients/jedis/StreamPendingEntry.java rename to src/main/java/redis/clients/jedis/resps/StreamPendingEntry.java index 97dc5951b3..a14d03bba9 100644 --- a/src/main/java/redis/clients/jedis/StreamPendingEntry.java +++ b/src/main/java/redis/clients/jedis/resps/StreamPendingEntry.java @@ -1,7 +1,8 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.io.IOException; import java.io.Serializable; +import redis.clients.jedis.StreamEntryID; public class StreamPendingEntry implements Serializable { diff --git a/src/main/java/redis/clients/jedis/StreamPendingSummary.java b/src/main/java/redis/clients/jedis/resps/StreamPendingSummary.java similarity index 91% rename from src/main/java/redis/clients/jedis/StreamPendingSummary.java rename to src/main/java/redis/clients/jedis/resps/StreamPendingSummary.java index 46a670df6a..023d8a3947 100644 --- a/src/main/java/redis/clients/jedis/StreamPendingSummary.java +++ b/src/main/java/redis/clients/jedis/resps/StreamPendingSummary.java @@ -1,7 +1,8 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.io.Serializable; import java.util.Map; +import redis.clients.jedis.StreamEntryID; public class StreamPendingSummary implements Serializable { diff --git a/src/main/java/redis/clients/jedis/Tuple.java b/src/main/java/redis/clients/jedis/resps/Tuple.java similarity index 98% rename from src/main/java/redis/clients/jedis/Tuple.java rename to src/main/java/redis/clients/jedis/resps/Tuple.java index 2a47e67603..63e63554c0 100644 --- a/src/main/java/redis/clients/jedis/Tuple.java +++ b/src/main/java/redis/clients/jedis/resps/Tuple.java @@ -1,4 +1,4 @@ -package redis.clients.jedis; +package redis.clients.jedis.resps; import java.util.Arrays; import java.util.Objects; diff --git a/src/main/java/redis/clients/jedis/search/Document.java b/src/main/java/redis/clients/jedis/search/Document.java new file mode 100644 index 0000000000..48396dcc0a --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/Document.java @@ -0,0 +1,134 @@ +package redis.clients.jedis.search; + +import redis.clients.jedis.util.SafeEncoder; + +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Document represents a single indexed document or entity in the engine + */ +public class Document implements Serializable { + + private static final long serialVersionUID = 4884173545291367373L; + + private final String id; + private double score; + private byte[] payload; + private final Map properties; + + public Document(String id, double score) { + this(id, new HashMap<>(), score); + } + + public Document(String id) { + this(id, 1.0); + } + + public Document(String id, Map fields) { + this(id, fields, 1.0f); + } + + public Document(String id, Map fields, double score) { + this(id, fields, score, null); + } + + public Document(String id, Map fields, double score, byte[] payload) { + this.id = id; + this.properties = new HashMap<>(fields); + this.score = score; + this.payload = payload; + } + + public Iterable> getProperties() { + return properties.entrySet(); + } + + public static Document load(String id, double score, byte[] payload, List fields) { + return Document.load(id, score, payload, fields, true); + } + + public static Document load(String id, double score, byte[] payload, List fields, boolean decode) { + Document ret = new Document(id, score); + ret.payload = payload; + if (fields != null) { + for (int i = 0; i < fields.size(); i += 2) { + ret.set(SafeEncoder.encode(fields.get(i)), decode ? SafeEncoder.encode(fields.get(i + 1)) : fields.get(i + 1)); + } + } + return ret; + } + + public Document set(String key, Object value) { + properties.put(key, value); + return this; + } + + /** + * return the property value inside a key + * + * @param key key of the property + * + * @return the property value + */ + public Object get(String key) { + return properties.get(key); + } + + /** + * return the property value inside a key + * + * @param key key of the property + * + * @return the property value + */ + public String getString(String key) { + Object value = properties.get(key); + if (value instanceof String) { + return (String) value; + } + return value instanceof byte[] ? SafeEncoder.encode((byte[]) value) : value.toString(); + } + + /** + * @return the document's score + */ + public double getScore() { + return score; + } + + public byte[] getPayload() { + return payload; + } + + /** + * Set the document's score + * + * @param score new score to set + * @return the document itself + */ + public Document setScore(float score) { + this.score = score; + return this; + } + + /** + * @return the document's id + */ + public String getId() { + return id; + } + + public boolean hasProperty(String key) { + return properties.containsKey(key); + } + + @Override + public String toString() { + return "id:" + this.getId() + ", score: " + this.getScore() + + ", payload:" + SafeEncoder.encode(this.getPayload()) + + ", properties:" + this.getProperties(); + } +} diff --git a/src/main/java/redis/clients/jedis/search/FieldName.java b/src/main/java/redis/clients/jedis/search/FieldName.java new file mode 100644 index 0000000000..c66ea25801 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/FieldName.java @@ -0,0 +1,93 @@ +package redis.clients.jedis.search; + +import java.util.List; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.params.IParams; + +import redis.clients.jedis.util.SafeEncoder; + +public class FieldName implements IParams { + + private static final String AS_ENCODED = "AS"; + private static final byte[] AS_BINARY = SafeEncoder.encode(AS_ENCODED); + private static final byte[] AS = SafeEncoder.encode("AS"); + + private final String name; + private String attribute; + + public FieldName(String name) { + this(name, null); + } + + public FieldName(String name, String attribute) { + this.name = name; + this.attribute = attribute; + } + + public int addCommandEncodedArguments(List args) { + args.add(name); + if (attribute == null) { + return 1; + } + + args.add(AS_ENCODED); + args.add(attribute); + return 3; + } + + public int addCommandBinaryArguments(List args) { + args.add(SafeEncoder.encode(name)); + if (attribute == null) { + return 1; + } + + args.add(AS_BINARY); + args.add(SafeEncoder.encode(attribute)); + return 3; + } + + public int addCommandArguments(CommandArguments args) { + args.add(SafeEncoder.encode(name)); + if (attribute == null) { + return 1; + } + + args.add(AS); + args.add(SafeEncoder.encode(attribute)); + return 3; + } + + @Override + public void addParams(CommandArguments args) { + addCommandArguments(args); + } + + String getName() { + return name; + } + + @Override + public String toString() { + return attribute == null ? name : (name + " AS " + attribute); + } + + public static FieldName of(String name) { + return new FieldName(name); + } + + public FieldName as(String attribute) { + this.attribute = attribute; + return this; + } + + public static FieldName[] convert(String... names) { + if (names == null) { + return null; + } + FieldName[] fields = new FieldName[names.length]; + for (int i = 0; i < names.length; i++) { + fields[i] = FieldName.of(names[i]); + } + return fields; + } +} diff --git a/src/main/java/redis/clients/jedis/search/IndexDefinition.java b/src/main/java/redis/clients/jedis/search/IndexDefinition.java new file mode 100644 index 0000000000..73a4f6ae8e --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/IndexDefinition.java @@ -0,0 +1,160 @@ +package redis.clients.jedis.search; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.params.IParams; +import redis.clients.jedis.search.SearchProtocol.SearchKeyword; + +/** + * IndexDefinition encapsulates configuration for index definition creation and should be given to + * the client on index creation + */ +public class IndexDefinition implements IParams { + + public enum Type { + HASH, + JSON + } + + private final Type type; + private boolean async = false; + private String[] prefixes; + private String filter; + private String languageField; + private String language; + private String scoreFiled; + private double score = 1.0; // Default score when score isn't defined + private String payloadField; + + public IndexDefinition() { + this(null); + } + + public IndexDefinition(Type type) { + this.type = type; + } + + public Type getType() { + return type; + } + + public boolean isAsync() { + return async; + } + + public IndexDefinition setAsync(boolean async) { + this.async = async; + return this; + } + + public String[] getPrefixes() { + return prefixes; + } + + public IndexDefinition setPrefixes(String... prefixes) { + this.prefixes = prefixes; + return this; + } + + public String getFilter() { + return filter; + } + + public IndexDefinition setFilter(String filter) { + this.filter = filter; + return this; + } + + public String getLanguageField() { + return languageField; + } + + public IndexDefinition setLanguageField(String languageField) { + this.languageField = languageField; + return this; + } + + public String getLanguage() { + return language; + } + + public IndexDefinition setLanguage(String language) { + this.language = language; + return this; + } + + public String getScoreFiled() { + return scoreFiled; + } + + public IndexDefinition setScoreFiled(String scoreFiled) { + this.scoreFiled = scoreFiled; + return this; + } + + public double getScore() { + return score; + } + + public IndexDefinition setScore(double score) { + this.score = score; + return this; + } + + public String getPayloadField() { + return payloadField; + } + + public IndexDefinition setPayloadField(String payloadField) { + this.payloadField = payloadField; + return this; + } + + @Override + public void addParams(CommandArguments args) { + + if (type != null) { + args.add(SearchKeyword.ON.name()); + args.add(type.name()); + } + + if (async) { + args.add(SearchKeyword.ASYNC.name()); + } + + if (prefixes != null && prefixes.length > 0) { + args.add(SearchKeyword.PREFIX.name()); + args.add(Integer.toString(prefixes.length)); + args.addObjects((Object[]) prefixes); + } + + if (filter != null) { + args.add(SearchKeyword.FILTER.name()); + args.add(filter); + } + + if (languageField != null) { + args.add(SearchKeyword.LANGUAGE_FIELD.name()); + args.add(languageField); + } + + if (language != null) { + args.add(SearchKeyword.LANGUAGE.name()); + args.add(language); + } + + if (scoreFiled != null) { + args.add(SearchKeyword.SCORE_FIELD.name()); + args.add(scoreFiled); + } + + if (score != 1.0) { + args.add(SearchKeyword.SCORE.name()); + args.add(Double.toString(score)); + } + + if (payloadField != null) { + args.add(SearchKeyword.PAYLOAD_FIELD.name()); + args.add(payloadField); + } + } +} diff --git a/src/main/java/redis/clients/jedis/search/IndexOptions.java b/src/main/java/redis/clients/jedis/search/IndexOptions.java new file mode 100644 index 0000000000..a8b93d8cf0 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/IndexOptions.java @@ -0,0 +1,129 @@ +package redis.clients.jedis.search; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.params.IParams; +import redis.clients.jedis.search.SearchProtocol.SearchKeyword; + +/** + * IndexOptions encapsulates flags for index creation and should be given to the client on index + * creation + * + * @since 2.0 + */ +public class IndexOptions implements IParams { + + /** + * Set this to tell the index not to save term offset vectors. This reduces memory consumption but + * does not allow performing exact matches, and reduces overall relevance of multi-term queries + */ + public static final int USE_TERM_OFFSETS = 0x01; + + /** + * If set (default), we keep flags per index record telling us what fields the term appeared on, + * and allowing us to filter results by field + */ + public static final int KEEP_FIELD_FLAGS = 0x02; + + /** + * With each document:term record, store how often the term appears within the document. This can + * be used for sorting documents by their relevance to the given term. + */ + public static final int KEEP_TERM_FREQUENCIES = 0x08; + + public static final int DEFAULT_FLAGS = USE_TERM_OFFSETS | KEEP_FIELD_FLAGS | KEEP_TERM_FREQUENCIES; + + private final int flags; + private List stopwords; + private long expire = 0L; + private IndexDefinition definition; + + /** + * Default constructor + * + * @param flags flag mask + */ + public IndexOptions(int flags) { + this.flags = flags; + } + + /** + * The default indexing options - use term offsets and keep fields flags + */ + public static IndexOptions defaultOptions() { + return new IndexOptions(DEFAULT_FLAGS); + } + + /** + * Set a custom stopword list + * + * @param stopwords the list of stopwords + * @return the options object itself, for builder-style construction + */ + public IndexOptions setStopwords(String... stopwords) { + this.stopwords = Arrays.asList(stopwords); + return this; + } + + /** + * Set the index to contain no stopwords, overriding the default list + * + * @return the options object itself, for builder-style constructions + */ + public IndexOptions setNoStopwords() { + stopwords = new ArrayList<>(0); + return this; + } + + /** + * Temporary + * + * @param expire + * @return IndexOptions + */ + public IndexOptions setTemporary(long expire) { + this.expire = expire; + return this; + } + + public IndexDefinition getDefinition() { + return definition; + } + + public IndexOptions setDefinition(IndexDefinition definition) { + this.definition = definition; + return this; + } + + @Override + public void addParams(CommandArguments args) { + + if (definition != null) { + definition.addParams(args); + } + + if ((flags & USE_TERM_OFFSETS) == 0) { + args.add(SearchKeyword.NOOFFSETS.name()); + } + if ((flags & KEEP_FIELD_FLAGS) == 0) { + args.add(SearchKeyword.NOFIELDS.name()); + } + if ((flags & KEEP_TERM_FREQUENCIES) == 0) { + args.add(SearchKeyword.NOFREQS.name()); + } + if (expire > 0) { + args.add(SearchKeyword.TEMPORARY.name()); + args.add(Long.toString(this.expire)); + } + + if (stopwords != null) { + args.add(SearchKeyword.STOPWORDS.name()); + args.add(Integer.toString(stopwords.size())); + if (!stopwords.isEmpty()) { + args.addObjects(stopwords); + } + } + } +} diff --git a/src/main/java/redis/clients/jedis/search/Query.java b/src/main/java/redis/clients/jedis/search/Query.java new file mode 100644 index 0000000000..e66ec2db1d --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/Query.java @@ -0,0 +1,522 @@ +package redis.clients.jedis.search; + +import java.util.LinkedList; +import java.util.List; + +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.args.Rawable; +import redis.clients.jedis.params.IParams; +import redis.clients.jedis.search.SearchProtocol.SearchKeyword; +import redis.clients.jedis.util.SafeEncoder; + +/** + * Query represents query parameters and filters to load results from the engine + */ +public class Query implements IParams { + + /** + * Filter represents a filtering rules in a query + */ + public abstract static class Filter implements IParams { + + public final String property; + + public Filter(String property) { + this.property = property; + } + } + + /** + * NumericFilter wraps a range filter on a numeric field. It can be inclusive or exclusive + */ + public static class NumericFilter extends Filter { + + private final double min; + private final boolean exclusiveMin; + private final double max; + private final boolean exclusiveMax; + + public NumericFilter(String property, double min, boolean exclusiveMin, double max, boolean exclusiveMax) { + super(property); + this.min = min; + this.max = max; + this.exclusiveMax = exclusiveMax; + this.exclusiveMin = exclusiveMin; + } + + public NumericFilter(String property, double min, double max) { + this(property, min, false, max, false); + } + + private byte[] formatNum(double num, boolean exclude) { + return exclude ? SafeEncoder.encode("(" + num) : Protocol.toByteArray(num); + } + + @Override + public void addParams(CommandArguments args) { + args.add(SearchKeyword.FILTER.getRaw()); + args.add(SafeEncoder.encode(property)); + args.add(formatNum(min, exclusiveMin)); + args.add(formatNum(max, exclusiveMax)); + } + } + + /** + * GeoFilter encapsulates a radius filter on a geographical indexed fields + */ + public static class GeoFilter extends Filter { + + public static final String KILOMETERS = "km"; + public static final String METERS = "m"; + public static final String FEET = "ft"; + public static final String MILES = "mi"; + + private final double lon; + private final double lat; + private final double radius; + private final String unit; + + public GeoFilter(String property, double lon, double lat, double radius, String unit) { + super(property); + this.lon = lon; + this.lat = lat; + this.radius = radius; + this.unit = unit; + } + + @Override + public void addParams(CommandArguments args) { + args.add(SearchKeyword.GEOFILTER.getRaw()); + args.add(SafeEncoder.encode(property)); + args.add(Protocol.toByteArray(lon)); + args.add(Protocol.toByteArray(lat)); + args.add(Protocol.toByteArray(radius)); + args.add(SafeEncoder.encode(unit)); + } + } + + public static class Paging { + + int offset; + int num; + + public Paging(int offset, int num) { + this.offset = offset; + this.num = num; + } + } + + public static class HighlightTags { + + private final String open; + private final String close; + + public HighlightTags(String open, String close) { + this.open = open; + this.close = close; + } + } + + /** + * The query's filter list. We only support AND operation on all those filters + */ + private final List _filters = new LinkedList<>(); + + /** + * The textual part of the query + */ + private final String _queryString; + + /** + * The sorting parameters + */ + private final Paging _paging = new Paging(0, 10); + + private boolean _verbatim = false; + private boolean _noContent = false; + private boolean _noStopwords = false; + private boolean _withScores = false; + private boolean _withPayloads = false; + private String _language = null; + private String[] _fields = null; + private String[] _keys = null; + private String[] _returnFields = null; + private FieldName[] returnFieldNames = null; + private String[] highlightFields = null; + private String[] summarizeFields = null; + private String[] highlightTags = null; + private String summarizeSeparator = null; + private int summarizeNumFragments = -1; + private int summarizeFragmentLen = -1; + private byte[] _payload = null; + private String _sortBy = null; + private boolean _sortAsc = true; + private boolean wantsHighlight = false; + private boolean wantsSummarize = false; + private String _scorer = null; + + public Query() { + this("*"); + } + + /** + * Create a new index + * + * @param queryString the textual part of the query + */ + public Query(String queryString) { + _queryString = queryString; + } + + @Override + public void addParams(CommandArguments args) { + args.add(SafeEncoder.encode(_queryString)); + + if (_verbatim) { + args.add(SearchKeyword.VERBATIM.getRaw()); + } + if (_noContent) { + args.add(SearchKeyword.NOCONTENT.getRaw()); + } + if (_noStopwords) { + args.add(SearchKeyword.NOSTOPWORDS.getRaw()); + } + if (_withScores) { + args.add(SearchKeyword.WITHSCORES.getRaw()); + } + if (_withPayloads) { + args.add(SearchKeyword.WITHPAYLOADS.getRaw()); + } + if (_language != null) { + args.add(SearchKeyword.LANGUAGE.getRaw()); + args.add(SafeEncoder.encode(_language)); + } + + if (_scorer != null) { + args.add(SearchKeyword.SCORER.getRaw()); + args.add(SafeEncoder.encode(_scorer)); + } + + if (_fields != null && _fields.length > 0) { + args.add(SearchKeyword.INFIELDS.getRaw()); + args.add(Protocol.toByteArray(_fields.length)); + for (String f : _fields) { + args.add(SafeEncoder.encode(f)); + } + } + + if (_sortBy != null) { + args.add(SearchKeyword.SORTBY.getRaw()); + args.add(SafeEncoder.encode(_sortBy)); + args.add((_sortAsc ? SearchKeyword.ASC : SearchKeyword.DESC).getRaw()); + } + + if (_payload != null) { + args.add(SearchKeyword.PAYLOAD.getRaw()); + args.add(_payload); + } + + if (_paging.offset != 0 || _paging.num != 10) { + args.add(SearchKeyword.LIMIT.getRaw()).add(Protocol.toByteArray(_paging.offset)).add(Protocol.toByteArray(_paging.num)); + } + + if (!_filters.isEmpty()) { + _filters.forEach(filter -> filter.addParams(args)); + } + + if (wantsHighlight) { + args.add(SearchKeyword.HIGHLIGHT.getRaw()); + if (highlightFields != null) { + args.add(SearchKeyword.FIELDS.getRaw()); + args.add(Protocol.toByteArray(highlightFields.length)); + for (String s : highlightFields) { + args.add(SafeEncoder.encode(s)); + } + } + if (highlightTags != null) { + args.add(SearchKeyword.TAGS.getRaw()); + for (String t : highlightTags) { + args.add(SafeEncoder.encode(t)); + } + } + } + if (wantsSummarize) { + args.add(SearchKeyword.SUMMARIZE.getRaw()); + if (summarizeFields != null) { + args.add(SearchKeyword.FIELDS.getRaw()); + args.add(Protocol.toByteArray(summarizeFields.length)); + for (String s : summarizeFields) { + args.add(SafeEncoder.encode(s)); + } + } + if (summarizeNumFragments != -1) { + args.add(SearchKeyword.FRAGS.getRaw()); + args.add(Protocol.toByteArray(summarizeNumFragments)); + } + if (summarizeFragmentLen != -1) { + args.add(SearchKeyword.LEN.getRaw()); + args.add(Protocol.toByteArray(summarizeFragmentLen)); + } + if (summarizeSeparator != null) { + args.add(SearchKeyword.SEPARATOR.getRaw()); + args.add(SafeEncoder.encode(summarizeSeparator)); + } + } + + if (_keys != null && _keys.length > 0) { + args.add(SearchKeyword.INKEYS.getRaw()); + args.add(Protocol.toByteArray(_keys.length)); + for (String f : _keys) { + args.add(SafeEncoder.encode(f)); + } + } + + if (_returnFields != null && _returnFields.length > 0) { + args.add(SearchKeyword.RETURN.getRaw()); + args.add(Protocol.toByteArray(_returnFields.length)); + for (String f : _returnFields) { + args.add(SafeEncoder.encode(f)); + } + } else if (returnFieldNames != null && returnFieldNames.length > 0) { + args.add(SearchKeyword.RETURN.getRaw()); +// final int returnCountIndex = args.size(); + DelayedRawable returnCountObject = new DelayedRawable(); +// args.add(null); // holding a place for setting the total count later. + args.add(returnCountObject); // holding a place for setting the total count later. + int returnCount = 0; + for (FieldName fn : returnFieldNames) { + returnCount += fn.addCommandArguments(args); + } +// args.set(returnCountIndex, Protocol.toByteArray(returnCount)); + returnCountObject.setRaw(Protocol.toByteArray(returnCount)); + } + } + + private static class DelayedRawable implements Rawable { + + private byte[] raw = null; + + public void setRaw(byte[] raw) { + this.raw = raw; + } + + @Override + public byte[] getRaw() { + return raw; + } + } + + /** + * Limit the results to a certain offset and limit + * + * @param offset the first result to show, zero based indexing + * @param limit how many results we want to show + * @return the query itself, for builder-style syntax + */ + public Query limit(Integer offset, Integer limit) { + _paging.offset = offset; + _paging.num = limit; + return this; + } + + /** + * Add a filter to the query's filter list + * + * @param f either a numeric or geo filter object + * @return the query itself + */ + public Query addFilter(Filter f) { + _filters.add(f); + return this; + } + + /* Set the query payload to be evaluated by the scoring function */ + public Query setPayload(byte[] payload) { + _payload = payload; + return this; + } + + /** + * Set the query to verbatim mode, disabling stemming and query expansion + * + * @return the query object + */ + public Query setVerbatim() { + this._verbatim = true; + return this; + } + + public boolean getNoContent() { + return _noContent; + } + + /** + * Set the query not to return the contents of documents, and rather just return the ids + * + * @return the query itself + */ + public Query setNoContent() { + this._noContent = true; + return this; + } + + /** + * Set the query not to filter for stopwords. In general this should not be used + * + * @return the query object + */ + public Query setNoStopwords() { + this._noStopwords = true; + return this; + } + + public boolean getWithScores() { + return _withScores; + } + + /** + * Set the query to return a factored score for each results. This is useful to merge results from + * multiple queries. + * + * @return the query object itself + */ + public Query setWithScores() { + this._withScores = true; + return this; + } + + public boolean getWithPayloads() { + return _withPayloads; + } + + /** + * Set the query to return object payloads, if any were given + * + * @return the query object itself + * + */ + public Query setWithPayload() { + this._withPayloads = true; + return this; + } + + /** + * Set the query language, for stemming purposes + *

+ * See http://redisearch.io for documentation on languages and stemming + * + * @param language a language. + * + * @return the query object itself + */ + public Query setLanguage(String language) { + this._language = language; + return this; + } + + /** + * Set the query custom scorer + *

+ * See http://redisearch.io for documentation on extending RediSearch + * + * @param scorer a custom scorer. + * + * @return the query object itself + */ + public Query setScorer(String scorer) { + this._scorer = scorer; + return this; + } + + /** + * Limit the query to results that are limited to a specific set of fields + * + * @param fields a list of TEXT fields in the schemas + * @return the query object itself + */ + public Query limitFields(String... fields) { + this._fields = fields; + return this; + } + + /** + * Limit the query to results that are limited to a specific set of keys + * + * @param keys a list of TEXT fields in the schemas + * @return the query object itself + */ + public Query limitKeys(String... keys) { + this._keys = keys; + return this; + } + + /** + * Result's projection - the fields to return by the query + * + * @param fields a list of TEXT fields in the schemas + * @return the query object itself + */ + public Query returnFields(String... fields) { + this._returnFields = fields; + this.returnFieldNames = null; + return this; + } + + /** + * Result's projection - the fields to return by the query + * + * @param fields a list of TEXT fields in the schemas + * @return the query object itself + */ + public Query returnFields(FieldName... fields) { + this.returnFieldNames = fields; + this._returnFields = null; + return this; + } + + public Query highlightFields(HighlightTags tags, String... fields) { + if (fields == null || fields.length > 0) { + highlightFields = fields; + } + if (tags != null) { + highlightTags = new String[]{tags.open, tags.close}; + } else { + highlightTags = null; + } + wantsHighlight = true; + return this; + } + + public Query highlightFields(String... fields) { + return highlightFields(null, fields); + } + + public Query summarizeFields(int contextLen, int fragmentCount, String separator, String... fields) { + if (fields == null || fields.length > 0) { + summarizeFields = fields; + } + summarizeFragmentLen = contextLen; + summarizeNumFragments = fragmentCount; + summarizeSeparator = separator; + wantsSummarize = true; + return this; + } + + public Query summarizeFields(String... fields) { + return summarizeFields(-1, -1, null, fields); + } + + /** + * Set the query to be sorted by a Sortable field defined in the schema + * + * @param field the sorting field's name + * @param ascending if set to true, the sorting order is ascending, else descending + * @return the query object itself + */ + public Query setSortBy(String field, boolean ascending) { + _sortBy = field; + _sortAsc = ascending; + return this; + } +} diff --git a/src/main/java/redis/clients/jedis/search/RediSearchCommands.java b/src/main/java/redis/clients/jedis/search/RediSearchCommands.java new file mode 100644 index 0000000000..0321ecaadf --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/RediSearchCommands.java @@ -0,0 +1,55 @@ +package redis.clients.jedis.search; + +import java.util.List; +import java.util.Map; +import redis.clients.jedis.search.aggr.AggregationBuilder; +import redis.clients.jedis.search.aggr.AggregationResult; + +public interface RediSearchCommands { + + String ftCreate(String indexName, IndexOptions indexOptions, Schema schema); + + default String ftAlter(String indexName, Schema.Field... fields) { + return ftAlter(indexName, Schema.from(fields)); + } + + String ftAlter(String indexName, Schema schema); + + SearchResult ftSearch(String indexName, Query query); + + SearchResult ftSearch(byte[] indexName, Query query); + + String ftExplain(String indexName, Query query); + + List ftExplainCLI(String indexName, Query query); + + AggregationResult ftAggregate(String indexName, AggregationBuilder aggr); + + AggregationResult ftCursorRead(String indexName, long cursorId, int count); + + String ftCursorDel(String indexName, long cursorId); + + String ftDropIndex(String indexName); + + String ftDropIndexDD(String indexName); + + String ftSynUpdate(String indexName, String synonymGroupId, String... terms); + + Map> ftSynDump(String indexName); + + Map ftInfo(String indexName); + + String ftAliasAdd(String aliasName, String indexName); + + String ftAliasUpdate(String aliasName, String indexName); + + String ftAliasDel(String aliasName); + + Map ftConfigGet(String option); + + Map ftConfigGet(String indexName, String option); + + String ftConfigSet(String option, String value); + + String ftConfigSet(String indexName, String option, String value); +} diff --git a/src/main/java/redis/clients/jedis/search/RediSearchPipelineCommands.java b/src/main/java/redis/clients/jedis/search/RediSearchPipelineCommands.java new file mode 100644 index 0000000000..db517c3112 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/RediSearchPipelineCommands.java @@ -0,0 +1,12 @@ +package redis.clients.jedis.search; + +import redis.clients.jedis.Response; + +public interface RediSearchPipelineCommands { + + Response ftCreate(String indexName, IndexOptions indexOptions, Schema schema); + + Response ftSearch(String indexName, Query query); + + Response ftSearch(byte[] indexName, Query query); +} diff --git a/src/main/java/redis/clients/jedis/search/RediSearchUtil.java b/src/main/java/redis/clients/jedis/search/RediSearchUtil.java new file mode 100644 index 0000000000..1200a5f253 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/RediSearchUtil.java @@ -0,0 +1,36 @@ +package redis.clients.jedis.search; + +import java.util.HashMap; +import java.util.Map; +import redis.clients.jedis.util.SafeEncoder; + +public class RediSearchUtil { + + public static Map toStringMap(Map input) { + Map output = new HashMap<>(input.size()); + for (Map.Entry entry : input.entrySet()) { + String key = entry.getKey(); + Object obj = entry.getValue(); + if (key == null || obj == null) { + throw new NullPointerException("A null argument cannot be sent to Redis."); + } + String str; + if (obj instanceof byte[]) { + str = SafeEncoder.encode((byte[]) obj); + } else if (obj instanceof redis.clients.jedis.GeoCoordinate) { + redis.clients.jedis.GeoCoordinate geo = (redis.clients.jedis.GeoCoordinate) obj; + str = geo.getLongitude() + "," + geo.getLatitude(); + } else if (obj instanceof String) { + str = (String) obj; + } else { + str = obj.toString(); + } + output.put(key, str); + } + return output; + } + + private RediSearchUtil() { + throw new InstantiationError("Must not instantiate this class"); + } +} diff --git a/src/main/java/redis/clients/jedis/search/Schema.java b/src/main/java/redis/clients/jedis/search/Schema.java new file mode 100644 index 0000000000..8b53bea10c --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/Schema.java @@ -0,0 +1,276 @@ +package redis.clients.jedis.search; + +import java.util.ArrayList; +import java.util.List; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.params.IParams; + +/** + * Schema abstracs the schema definition when creating an index. Documents can contain fields not + * mentioned in the schema, but the index will only index pre-defined fields + */ +public class Schema { + + public enum FieldType { + TAG, + TEXT, + GEO, + NUMERIC; + } + + public final List fields; + + public Schema() { + this.fields = new ArrayList<>(); + } + + public static Schema from(Field... fields) { + Schema schema = new Schema(); + for (Field field : fields) { + schema.addField(field); + } + return schema; + } + + /** + * Add a text field to the schema with a given weight + * + * @param name the field's name + * @param weight its weight, a positive floating point number + * @return the schema object + */ + public Schema addTextField(String name, double weight) { + fields.add(new TextField(name, weight)); + return this; + } + + /** + * Add a text field that can be sorted on + * + * @param name the field's name + * @param weight its weight, a positive floating point number + * @return the schema object + */ + public Schema addSortableTextField(String name, double weight) { + fields.add(new TextField(name, weight, true)); + return this; + } + + /** + * Add a geo filtering field to the schema. + * + * @param name the field's name + * @return the schema object + */ + public Schema addGeoField(String name) { + fields.add(new Field(name, FieldType.GEO, false)); + return this; + } + + /** + * Add a numeric field to the schema + * + * @param name the fields's nam e + * @return the schema object + */ + public Schema addNumericField(String name) { + fields.add(new Field(name, FieldType.NUMERIC, false)); + return this; + } + + /* Add a numeric field that can be sorted on */ + public Schema addSortableNumericField(String name) { + fields.add(new Field(name, FieldType.NUMERIC, true)); + return this; + } + + public Schema addTagField(String name) { + fields.add(new TagField(name)); + return this; + } + + public Schema addTagField(String name, String separator) { + fields.add(new TagField(name, separator)); + return this; + } + + public Schema addSortableTagField(String name, String separator) { + fields.add(new TagField(name, separator, true)); + return this; + } + + public Schema addField(Field field) { + fields.add(field); + return this; + } + + @Override + public String toString() { + return "Schema{fields=" + fields + "}"; + } + + public static class Field implements IParams { + + private final FieldName fieldName; + public final String name; + public final FieldType type; + public final boolean sortable; + public final boolean noindex; + + public Field(String name, FieldType type, boolean sortable) { + this(name, type, sortable, false); + } + + public Field(String name, FieldType type, boolean sortable, boolean noindex) { + this(FieldName.of(name), type, sortable, noindex); + } + + public Field(FieldName name, FieldType type) { + this(name, type, false, false); + } + + public Field(FieldName name, FieldType type, boolean sortable, boolean noIndex) { + this.fieldName = name; + this.name = this.fieldName.getName(); + this.type = type; + this.sortable = sortable; + this.noindex = noIndex; + } + + @Override + public final void addParams(CommandArguments args) { + this.fieldName.addParams(args); + args.add(type.name()); + addTypeArgs(args); + if (sortable) { + args.add("SORTABLE"); + } + if (noindex) { + args.add("NOINDEX"); + } + } + + /** + * Sub-classes should override this method. + * + * @param args + */ + protected void addTypeArgs(CommandArguments args) { + } + + @Override + public String toString() { + return "Field{name='" + name + "', type=" + type + ", sortable=" + sortable + ", noindex=" + noindex + "}"; + } + } + + /** + * FullText field spec. + */ + public static class TextField extends Field { + + private final double weight; + private final boolean nostem; + private final String phonetic; + + public TextField(String name) { + this(name, 1.0); + } + + public TextField(FieldName name) { + this(name, 1.0, false, false, false, null); + } + + public TextField(String name, double weight) { + this(name, weight, false); + } + + public TextField(String name, double weight, boolean sortable) { + this(name, weight, sortable, false); + } + + public TextField(String name, double weight, boolean sortable, boolean nostem) { + this(name, weight, sortable, nostem, false); + } + + public TextField(String name, double weight, boolean sortable, boolean nostem, boolean noindex) { + this(name, weight, sortable, nostem, noindex, null); + } + + public TextField(String name, double weight, boolean sortable, boolean nostem, boolean noindex, String phonetic) { + super(name, FieldType.TEXT, sortable, noindex); + this.weight = weight; + this.nostem = nostem; + this.phonetic = phonetic; + } + + public TextField(FieldName name, double weight, boolean sortable, boolean nostem, boolean noindex, String phonetic) { + super(name, FieldType.TEXT, sortable, noindex); + this.weight = weight; + this.nostem = nostem; + this.phonetic = phonetic; + } + + @Override + protected void addTypeArgs(CommandArguments args) { + if (weight != 1.0) { + args.add("WEIGHT"); + args.add(Double.toString(weight)); + } + if (nostem) { + args.add("NOSTEM"); + } + if (phonetic != null) { + args.add("PHONETIC"); + args.add(this.phonetic); + } + } + + @Override + public String toString() { + return "TextField{name='" + name + "', type=" + type + ", sortable=" + sortable + ", noindex=" + noindex + + ", weight=" + weight + ", nostem=" + nostem + ", phonetic='" + phonetic + "'}"; + } + } + + public static class TagField extends Field { + + private final String separator; + + public TagField(String name) { + this(name, null); + } + + public TagField(String name, String separator) { + this(name, separator, false); + } + + public TagField(String name, boolean sortable) { + this(name, null, sortable); + } + + public TagField(String name, String separator, boolean sortable) { + super(name, FieldType.TAG, sortable); + this.separator = separator; + } + + public TagField(FieldName name, String separator, boolean sortable) { + super(name, FieldType.TAG, sortable, false); + this.separator = separator; + } + + @Override + public void addTypeArgs(CommandArguments args) { + if (separator != null) { + args.add("SEPARATOR"); + args.add(separator); + } + } + + @Override + public String toString() { + return "TagField{name='" + name + "', type=" + type + ", sortable=" + sortable + ", noindex=" + noindex + + ", separator='" + separator + "'}"; + } + } +} diff --git a/src/main/java/redis/clients/jedis/search/SearchProtocol.java b/src/main/java/redis/clients/jedis/search/SearchProtocol.java new file mode 100644 index 0000000000..6424b3f07b --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/SearchProtocol.java @@ -0,0 +1,62 @@ +package redis.clients.jedis.search; + +import redis.clients.jedis.args.Rawable; +import redis.clients.jedis.commands.ProtocolCommand; +import redis.clients.jedis.util.SafeEncoder; + +public class SearchProtocol { + + public enum SearchCommand implements ProtocolCommand { + + CREATE("FT.CREATE"), + ALTER("FT.ALTER"), + INFO("FT.INFO"), + SEARCH("FT.SEARCH"), + EXPLAIN("FT.EXPLAIN"), + EXPLAINCLI("FT.EXPLAINCLI"), + AGGREGATE("FT.AGGREGATE"), + CURSOR("FT.CURSOR"), + CONFIG("FT.CONFIG"), + ALIASADD("FT.ALIASADD"), + ALIASUPDATE("FT.ALIASUPDATE"), + ALIASDEL("FT.ALIASDEL"), + SYNUPDATE("FT.SYNUPDATE"), + SYNDUMP("FT.SYNDUMP"), +// SUGADD("FT.SUGADD"), +// SUGGET("FT.SUGGET"), +// SUGDEL("FT.SUGDEL"), +// SUGLEN("FT.SUGLEN"), + DROPINDEX("FT.DROPINDEX"); + + private final byte[] raw; + + private SearchCommand(String alt) { + raw = SafeEncoder.encode(alt); + } + + @Override + public byte[] getRaw() { + return raw; + } + } + + public enum SearchKeyword implements Rawable { + + SCHEMA, VERBATIM, NOCONTENT, NOSTOPWORDS, WITHSCORES, WITHPAYLOADS, LANGUAGE, INFIELDS, SORTBY, + ASC, DESC, PAYLOAD, LIMIT, HIGHLIGHT, FIELDS, TAGS, SUMMARIZE, FRAGS, LEN, SEPARATOR, INKEYS, + RETURN, /*NOSAVE, PARTIAL, REPLACE,*/ FILTER, GEOFILTER, INCR, MAX, FUZZY, DD, /*DELETE,*/ DEL, + READ, COUNT, ADD, TEMPORARY, STOPWORDS, NOFREQS, NOFIELDS, NOOFFSETS, /*IF,*/ SET, GET, ON, + ASYNC, PREFIX, LANGUAGE_FIELD, SCORE_FIELD, SCORE, PAYLOAD_FIELD, SCORER; + + private final byte[] raw; + + private SearchKeyword() { + raw = SafeEncoder.encode(name()); + } + + @Override + public byte[] getRaw() { + return raw; + } + } +} diff --git a/src/main/java/redis/clients/jedis/search/SearchResult.java b/src/main/java/redis/clients/jedis/search/SearchResult.java new file mode 100644 index 0000000000..b980f8e7eb --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/SearchResult.java @@ -0,0 +1,84 @@ +package redis.clients.jedis.search; + +import java.util.ArrayList; +import java.util.List; +import redis.clients.jedis.Builder; +import redis.clients.jedis.BuilderFactory; + +/** + * SearchResult encapsulates the returned result from a search query. It contains publicly + * accessible fields for the total number of results, and an array of {@link Document} objects + * containing the actual returned documents. + */ +public class SearchResult { + + private final long totalResults; + private final List documents; + + private SearchResult(long totalResults, List documents) { + this.totalResults = totalResults; + this.documents = documents; + } + + public long getTotalResults() { + return totalResults; + } + + public List getDocuments() { + return documents; + } + + public static class SearchResultBuilder extends Builder { + + private final boolean hasContent; + private final boolean hasScores; + private final boolean hasPayloads; + private final boolean decode; + + public SearchResultBuilder(boolean hasContent, boolean hasScores, boolean hasPayloads, boolean decode) { + this.hasContent = hasContent; + this.hasScores = hasScores; + this.hasPayloads = hasPayloads; + this.decode = decode; + } + + @Override + public SearchResult build(Object data) { + List resp = (List) data; + + int step = 1; + int scoreOffset = 0; + int contentOffset = 1; + int payloadOffset = 0; + if (hasScores) { + step += 1; + scoreOffset = 1; + contentOffset += 1; + } + if (hasContent) { + step += 1; + if (hasPayloads) { + payloadOffset = scoreOffset + 1; + step += 1; + contentOffset += 1; + } + } + + // the first element is always the number of results + long totalResults = (Long) resp.get(0); + List documents = new ArrayList<>(resp.size() - 1); + + for (int i = 1; i < resp.size(); i += step) { + + double score = hasScores ? BuilderFactory.DOUBLE.build(resp.get(i + scoreOffset)) : 1.0; + byte[] payload = hasPayloads ? (byte[]) resp.get(i + payloadOffset) : null; + List fields = hasContent ? (List) resp.get(i + contentOffset) : null; + String id = new String((byte[]) resp.get(i)); + + documents.add(Document.load(id, score, payload, fields, decode)); + } + + return new SearchResult(totalResults, documents); + } + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/AggregationBuilder.java b/src/main/java/redis/clients/jedis/search/aggr/AggregationBuilder.java new file mode 100644 index 0000000000..a7d0c6c076 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/AggregationBuilder.java @@ -0,0 +1,146 @@ +package redis.clients.jedis.search.aggr; + +import java.util.*; +import redis.clients.jedis.search.FieldName; +import redis.clients.jedis.util.SafeEncoder; + +/** + * @author Guy Korland + */ +public class AggregationBuilder { + + private final List args = new ArrayList<>(); + private boolean isWithCursor = false; + + public AggregationBuilder(String query) { + args.add(query); + } + + public AggregationBuilder() { + this("*"); + } + + public AggregationBuilder load(String... fields) { + return load(FieldName.convert(fields)); + } + + public AggregationBuilder load(FieldName... fields) { + args.add("LOAD"); + final int loadCountIndex = args.size(); + args.add(null); + int loadCount = 0; + for (FieldName fn : fields) { + loadCount += fn.addCommandEncodedArguments(args); + } + args.set(loadCountIndex, Integer.toString(loadCount)); + return this; + } + + public AggregationBuilder limit(int offset, int count) { + Limit limit = new Limit(offset, count); + limit.addArgs(args); + return this; + } + + public AggregationBuilder limit(int count) { + return limit(0, count); + } + + public AggregationBuilder sortBy(SortedField... fields) { + args.add("SORTBY"); + args.add(Integer.toString(fields.length * 2)); + for (SortedField field : fields) { + args.add(field.getField()); + args.add(field.getOrder()); + } + + return this; + } + + public AggregationBuilder sortBy(int max, SortedField... fields) { + sortBy(fields); + if (max > 0) { + args.add("MAX"); + args.add(Integer.toString(max)); + } + return this; + } + + public AggregationBuilder sortByAsc(String field) { + return sortBy(SortedField.asc(field)); + } + + public AggregationBuilder sortByDesc(String field) { + return sortBy(SortedField.desc(field)); + } + + public AggregationBuilder apply(String projection, String alias) { + args.add("APPLY"); + args.add(projection); + args.add("AS"); + args.add(alias); + return this; + } + + public AggregationBuilder groupBy(Collection fields, Collection reducers) { + String[] fieldsArr = new String[fields.size()]; + Group g = new Group(fields.toArray(fieldsArr)); + for (Reducer r : reducers) { + g.reduce(r); + } + groupBy(g); + return this; + } + + public AggregationBuilder groupBy(String field, Reducer... reducers) { + return groupBy(Collections.singletonList(field), Arrays.asList(reducers)); + } + + public AggregationBuilder groupBy(Group group) { + args.add("GROUPBY"); + group.addArgs(args); + return this; + } + + public AggregationBuilder filter(String expression) { + args.add("FILTER"); + args.add(expression); + return this; + } + + public AggregationBuilder cursor(int count, long maxIdle) { + isWithCursor = true; + if (count > 0) { + args.add("WITHCURSOR"); + args.add("COUNT"); + args.add(Integer.toString(count)); + if (maxIdle < Long.MAX_VALUE && maxIdle >= 0) { + args.add("MAXIDLE"); + args.add(Long.toString(maxIdle)); + } + } + return this; + } + + public List getArgs() { + return Collections.unmodifiableList(args); + } + + public void serializeRedisArgs(List redisArgs) { + for (String s : getArgs()) { + redisArgs.add(SafeEncoder.encode(s)); + } + } + + public String getArgsString() { + StringJoiner sj = new StringJoiner(" "); + for (String s : getArgs()) { + sj.add(s); + } + return sj.toString(); + } + + public boolean isWithCursor() { + return isWithCursor; + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/AggregationResult.java b/src/main/java/redis/clients/jedis/search/aggr/AggregationResult.java new file mode 100644 index 0000000000..cda4d6a4a1 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/AggregationResult.java @@ -0,0 +1,58 @@ +package redis.clients.jedis.search.aggr; + +import redis.clients.jedis.exceptions.JedisDataException; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * Created by mnunberg on 2/22/18. + */ +public class AggregationResult { + + public final long totalResults; + + private long cursorId = -1; + private final List> results = new ArrayList<>(); + + public AggregationResult(Object resp, long cursorId) { + this(resp); + this.cursorId = cursorId; + } + + public AggregationResult(Object resp) { + List list = (List) resp; + // the first element is always the number of results + totalResults = (Long) list.get(0); + + for (int i = 1; i < list.size(); i++) { + List raw = (List) list.get(i); + Map cur = new HashMap<>(); + for (int j = 0; j < raw.size(); j += 2) { + Object r = raw.get(j); + if (r instanceof JedisDataException) { + throw (JedisDataException) r; + } + cur.put(new String((byte[]) r), raw.get(j + 1)); + } + results.add(cur); + } + } + + public List> getResults() { + return results; + } + + public Row getRow(int index) { + if (index >= results.size()) { + return null; + } + return new Row(results.get(index)); + } + + public long getCursorId() { + return cursorId; + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/Group.java b/src/main/java/redis/clients/jedis/search/aggr/Group.java new file mode 100644 index 0000000000..a60cb5ac0c --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/Group.java @@ -0,0 +1,51 @@ +package redis.clients.jedis.search.aggr; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Created by mnunberg on 2/22/18. + */ +public class Group { + + private final List reducers = new ArrayList<>(); + private final List fields = new ArrayList<>(); + private Limit limit = new Limit(0, 0); + + public Group(String... fields) { + this.fields.addAll(Arrays.asList(fields)); + } + + public Group reduce(Reducer r) { + reducers.add(r); + return this; + } + + public Group limit(Limit limit) { + this.limit = limit; + return this; + } + + public void addArgs(List args) { + args.add(Integer.toString(fields.size())); + args.addAll(fields); + for (Reducer r : reducers) { + args.add("REDUCE"); + args.add(r.getName()); + r.addArgs(args); + String alias = r.getAlias(); + if (alias != null && !alias.isEmpty()) { + args.add("AS"); + args.add(alias); + } + } + args.addAll(limit.getArgs()); + } + + public List getArgs() { + List args = new ArrayList<>(); + addArgs(args); + return args; + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/Limit.java b/src/main/java/redis/clients/jedis/search/aggr/Limit.java new file mode 100644 index 0000000000..9f512c9713 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/Limit.java @@ -0,0 +1,39 @@ +package redis.clients.jedis.search.aggr; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by mnunberg on 2/22/18. + */ +public class Limit { + + public static final Limit NO_LIMIT = new Limit(0, 0); + + private final int offset; + private final int count; + + public Limit(int offset, int count) { + this.offset = offset; + this.count = count; + } + + public void addArgs(List args) { + if (count == 0) { + return; + } + args.add("LIMIT"); + args.add(Integer.toString(offset)); + args.add(Integer.toString(count)); + } + + public List getArgs() { + if (count == 0) { + return Collections.emptyList(); + } + List ll = new ArrayList<>(3); + addArgs(ll); + return ll; + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/Reducer.java b/src/main/java/redis/clients/jedis/search/aggr/Reducer.java new file mode 100644 index 0000000000..858fc0f7c2 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/Reducer.java @@ -0,0 +1,71 @@ +package redis.clients.jedis.search.aggr; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created by mnunberg on 2/22/18. + * + * This class is normally received via one of the subclasses or via Reducers + */ +public abstract class Reducer { + + private String alias; + private final String field; + + protected Reducer(String field) { + this.field = field; + this.alias = null; + } + + protected Reducer() { + this(null); + } + + protected List getOwnArgs() { + if (field == null) { + return Collections.emptyList(); + } + List ret = new ArrayList<>(); + ret.add(field); + return ret; + } + + /** + * @return The name of the reducer + */ + public abstract String getName(); + + public final String getAlias() { + return alias; + } + + public final Reducer setAlias(String alias) { + this.alias = alias; + return this; + } + + public final Reducer as(String alias) { + return setAlias(alias); + } + + public final Reducer setAliasAsField() { + if (field == null || field.isEmpty()) { + throw new IllegalArgumentException("Cannot set to field name since no field exists"); + } + return setAlias(field); + } + + public void addArgs(List args) { + List ownArgs = getOwnArgs(); + args.add(Integer.toString(ownArgs.size())); + args.addAll(ownArgs); + } + + public final List getArgs() { + List args = new ArrayList<>(); + addArgs(args); + return args; + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/Reducers.java b/src/main/java/redis/clients/jedis/search/aggr/Reducers.java new file mode 100644 index 0000000000..4ac4d4ccfc --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/Reducers.java @@ -0,0 +1,122 @@ +package redis.clients.jedis.search.aggr; + +import java.util.List; + +/** + * Created by mnunberg on 2/22/18. + */ +public class Reducers { + + public static Reducer count() { + return new Reducer() { + @Override + public String getName() { + return "COUNT"; + } + }; + } + + private static Reducer singleFieldReducer(String name, String field) { + return new Reducer(field) { + @Override + public String getName() { + return name; + } + }; + } + + public static Reducer count_distinct(String field) { + return singleFieldReducer("COUNT_DISTINCT", field); + } + + public static Reducer count_distinctish(String field) { + return singleFieldReducer("COUNT_DISTINCTISH", field); + } + + public static Reducer sum(String field) { + return singleFieldReducer("SUM", field); + } + + public static Reducer min(String field) { + return singleFieldReducer("MIN", field); + } + + public static Reducer max(String field) { + return singleFieldReducer("MAX", field); + } + + public static Reducer avg(String field) { + return singleFieldReducer("AVG", field); + } + + public static Reducer stddev(String field) { + return singleFieldReducer("STDDEV", field); + } + + public static Reducer quantile(String field, double percentile) { + return new Reducer(field) { + @Override + public String getName() { + return "QUANTILE"; + } + + @Override + protected List getOwnArgs() { + List args = super.getOwnArgs(); + args.add(Double.toString(percentile)); + return args; + } + }; + } + + /** + * REDUCE FIRST_VALUE {nargs} {property} [BY {property} [ASC|DESC]] + * + * @param field + * @param sortBy + * @return Reducer + */ + public static Reducer first_value(String field, SortedField sortBy) { + return new Reducer(field) { + @Override + public String getName() { + return "FIRST_VALUE"; + } + + @Override + protected List getOwnArgs() { + List args = super.getOwnArgs(); + if (sortBy != null) { + args.add("BY"); + args.add(sortBy.getField()); + args.add(sortBy.getOrder()); + } + return args; + } + }; + } + + public static Reducer first_value(String field) { + return first_value(field, null); + } + + public static Reducer to_list(String field) { + return singleFieldReducer("TOLIST", field); + } + + public static Reducer random_sample(String field, int size) { + return new Reducer(field) { + @Override + public String getName() { + return "RANDOM_SAMPLE"; + } + + @Override + protected List getOwnArgs() { + List args = super.getOwnArgs(); + args.add(Integer.toString(size)); + return args; + } + }; + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/Row.java b/src/main/java/redis/clients/jedis/search/aggr/Row.java new file mode 100644 index 0000000000..b7dbe2601d --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/Row.java @@ -0,0 +1,42 @@ +package redis.clients.jedis.search.aggr; + +import java.util.Map; + +/** + * Created by mnunberg on 5/17/18. + * + * Row in aggregation result-set + */ +public class Row { + + private final Map fields; + + public Row(Map fields) { + this.fields = fields; + } + + public boolean containsKey(String key) { + return fields.containsKey(key); + } + + public String getString(String key) { + if (!containsKey(key)) { + return ""; + } + return new String((byte[]) fields.get(key)); + } + + public long getLong(String key) { + if (!containsKey(key)) { + return 0; + } + return Long.parseLong(getString(key)); + } + + public double getDouble(String key) { + if (!containsKey(key)) { + return 0; + } + return Double.parseDouble(getString(key)); + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/SortedField.java b/src/main/java/redis/clients/jedis/search/aggr/SortedField.java new file mode 100644 index 0000000000..4270d2f60d --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/SortedField.java @@ -0,0 +1,35 @@ +package redis.clients.jedis.search.aggr; + +/** + * Created by mnunberg on 2/22/18. + */ +public class SortedField { + + public enum SortOrder { + ASC, DESC + } + + private final String fieldName; + private final SortOrder sortOrder; + + public SortedField(String fieldName, SortOrder order) { + this.fieldName = fieldName; + this.sortOrder = order; + } + + public final String getOrder() { + return sortOrder.toString(); + } + + public final String getField() { + return fieldName; + } + + public static SortedField asc(String field) { + return new SortedField(field, SortOrder.ASC); + } + + public static SortedField desc(String field) { + return new SortedField(field, SortOrder.DESC); + } +} diff --git a/src/main/java/redis/clients/jedis/search/aggr/package-info.java b/src/main/java/redis/clients/jedis/search/aggr/package-info.java new file mode 100644 index 0000000000..ecebca2390 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/aggr/package-info.java @@ -0,0 +1,4 @@ +/* + * This package contains the classes related to Aggregation commands in RediSearch module. + */ +package redis.clients.jedis.search.aggr; diff --git a/src/main/java/redis/clients/jedis/search/package-info.java b/src/main/java/redis/clients/jedis/search/package-info.java new file mode 100644 index 0000000000..e406948657 --- /dev/null +++ b/src/main/java/redis/clients/jedis/search/package-info.java @@ -0,0 +1,4 @@ +/* + * This package contains the classes related to RediSearch module. + */ +package redis.clients.jedis.search; diff --git a/src/main/java/redis/clients/jedis/util/IOUtils.java b/src/main/java/redis/clients/jedis/util/IOUtils.java index 5a35020316..37d66f0c5c 100644 --- a/src/main/java/redis/clients/jedis/util/IOUtils.java +++ b/src/main/java/redis/clients/jedis/util/IOUtils.java @@ -4,8 +4,6 @@ import java.net.Socket; public class IOUtils { - private IOUtils() { - } public static void closeQuietly(Socket sock) { // It's same thing as Apache Commons - IOUtils.closeQuietly() @@ -17,4 +15,19 @@ public static void closeQuietly(Socket sock) { } } } + + public static void closeQuietly(AutoCloseable resource) { + // It's same thing as Apache Commons - IOUtils.closeQuietly() + if (resource != null) { + try { + resource.close(); + } catch (Exception e) { + // ignored + } + } + } + + private IOUtils() { + throw new InstantiationError("Must not instantiate this class"); + } } diff --git a/src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java b/src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java index dc24a4e38e..7bedf5060a 100644 --- a/src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java +++ b/src/main/java/redis/clients/jedis/util/JedisClusterCRC16.java @@ -42,7 +42,7 @@ public static int getSlot(String key) { throw new JedisClusterOperationException("Slot calculation of null is impossible"); } - key = JedisClusterHashTagUtil.getHashTag(key); + key = JedisClusterHashTag.getHashTag(key); // optimization with modulo operator with power of 2 equivalent to getCRC16(key) % 16384 return getCRC16(key) & (16384 - 1); } diff --git a/src/main/java/redis/clients/jedis/util/JedisClusterHashTagUtil.java b/src/main/java/redis/clients/jedis/util/JedisClusterHashTag.java similarity index 92% rename from src/main/java/redis/clients/jedis/util/JedisClusterHashTagUtil.java rename to src/main/java/redis/clients/jedis/util/JedisClusterHashTag.java index 9fd1abd0b7..eab1cf46f2 100644 --- a/src/main/java/redis/clients/jedis/util/JedisClusterHashTagUtil.java +++ b/src/main/java/redis/clients/jedis/util/JedisClusterHashTag.java @@ -4,9 +4,9 @@ * Holds various methods/utilities to manipulate and parse redis hash-tags. See Cluster-Spec : Keys hash tags */ -public final class JedisClusterHashTagUtil { +public final class JedisClusterHashTag { - private JedisClusterHashTagUtil() { + private JedisClusterHashTag() { throw new InstantiationError("Must not instantiate this class"); } diff --git a/src/main/java/redis/clients/jedis/util/JedisURIHelper.java b/src/main/java/redis/clients/jedis/util/JedisURIHelper.java index 518d93e321..dd502e5e34 100644 --- a/src/main/java/redis/clients/jedis/util/JedisURIHelper.java +++ b/src/main/java/redis/clients/jedis/util/JedisURIHelper.java @@ -1,6 +1,7 @@ package redis.clients.jedis.util; import java.net.URI; +import redis.clients.jedis.HostAndPort; public final class JedisURIHelper { @@ -13,6 +14,10 @@ private JedisURIHelper() { throw new InstantiationError("Must not instantiate this class"); } + public static HostAndPort getHostAndPort(URI uri) { + return new HostAndPort(uri.getHost(), uri.getPort()); + } + public static String getUser(URI uri) { String userInfo = uri.getUserInfo(); if (userInfo != null) { diff --git a/src/main/java/redis/clients/jedis/util/KeyMergeUtil.java b/src/main/java/redis/clients/jedis/util/KeyMergeUtil.java deleted file mode 100644 index 8448b006a0..0000000000 --- a/src/main/java/redis/clients/jedis/util/KeyMergeUtil.java +++ /dev/null @@ -1,21 +0,0 @@ -package redis.clients.jedis.util; - -public final class KeyMergeUtil { - private KeyMergeUtil() { - throw new InstantiationError("Must not instantiate this class"); - } - - public static String[] merge(String destKey, String[] keys) { - String[] mergedKeys = new String[keys.length + 1]; - mergedKeys[0] = destKey; - System.arraycopy(keys, 0, mergedKeys, 1, keys.length); - return mergedKeys; - } - - public static byte[][] merge(byte[] destKey, byte[][] keys) { - byte[][] mergedKeys = new byte[keys.length + 1][]; - mergedKeys[0] = destKey; - System.arraycopy(keys, 0, mergedKeys, 1, keys.length); - return mergedKeys; - } -} \ No newline at end of file diff --git a/src/main/java/redis/clients/jedis/util/Pool.java b/src/main/java/redis/clients/jedis/util/Pool.java index 5f53cae2ba..5c34568dfb 100644 --- a/src/main/java/redis/clients/jedis/util/Pool.java +++ b/src/main/java/redis/clients/jedis/util/Pool.java @@ -1,20 +1,22 @@ package redis.clients.jedis.util; -import java.io.Closeable; -import java.util.NoSuchElementException; - import org.apache.commons.pool2.PooledObjectFactory; import org.apache.commons.pool2.impl.GenericObjectPool; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; - -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.exceptions.JedisExhaustedPoolException; -public class Pool extends GenericObjectPool implements Closeable { +public class Pool extends GenericObjectPool { + + /** + * @deprecated Use {@link Pool#Pool(org.apache.commons.pool2.PooledObjectFactory, + * org.apache.commons.pool2.impl.GenericObjectPoolConfig)}. + */ + @Deprecated + public Pool(GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + this(factory, poolConfig); + } - public Pool(final GenericObjectPoolConfig poolConfig, PooledObjectFactory factory) { + public Pool(final PooledObjectFactory factory, final GenericObjectPoolConfig poolConfig) { super(factory, poolConfig); } @@ -23,20 +25,21 @@ public void close() { destroy(); } + public void destroy() { + try { + super.close(); + } catch (RuntimeException e) { + throw new JedisException("Could not destroy the pool", e); + } + } + public T getResource() { try { return super.borrowObject(); - } catch (JedisDataException jde) { - throw jde; - } catch (NoSuchElementException nse) { - if (null == nse.getCause()) { // The exception was caused by an exhausted pool - throw new JedisExhaustedPoolException( - "Could not get a resource since the pool is exhausted", nse); - } - // Otherwise, the exception was caused by the implemented activateObject() or ValidateObject() - throw new JedisException("Could not get a resource from the pool", nse); + } catch (JedisException je) { + throw je; } catch (Exception e) { - throw new JedisConnectionException("Could not get a resource from the pool", e); + throw new JedisException("Could not get a resource from the pool", e); } } @@ -62,14 +65,6 @@ public void returnBrokenResource(final T resource) { } } - public void destroy() { - try { - super.close(); - } catch (RuntimeException e) { - throw new JedisException("Could not destroy the pool", e); - } - } - @Override public void addObjects(int count) { try { diff --git a/src/main/java/redis/clients/jedis/util/RedisInputStream.java b/src/main/java/redis/clients/jedis/util/RedisInputStream.java index aa8ce4b8a3..edba833db8 100644 --- a/src/main/java/redis/clients/jedis/util/RedisInputStream.java +++ b/src/main/java/redis/clients/jedis/util/RedisInputStream.java @@ -13,7 +13,6 @@ import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; - import redis.clients.jedis.exceptions.JedisConnectionException; /** diff --git a/src/main/java/redis/clients/jedis/util/SafeEncoder.java b/src/main/java/redis/clients/jedis/util/SafeEncoder.java index f08f7976b8..314d721851 100644 --- a/src/main/java/redis/clients/jedis/util/SafeEncoder.java +++ b/src/main/java/redis/clients/jedis/util/SafeEncoder.java @@ -1,17 +1,17 @@ package redis.clients.jedis.util; -import java.io.UnsupportedEncodingException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.exceptions.JedisException; - /** * The only reason to have this is to be able to compatible with java 1.5 :( */ public final class SafeEncoder { + public static volatile Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + private SafeEncoder() { throw new InstantiationError("Must not instantiate this class"); } @@ -28,11 +28,11 @@ public static byte[] encode(final String str) { if (str == null) { throw new IllegalArgumentException("null value cannot be sent to redis"); } - return str.getBytes(Protocol.CHARSET); + return str.getBytes(DEFAULT_CHARSET); } public static String encode(final byte[] data) { - return new String(data, Protocol.CHARSET); + return new String(data, DEFAULT_CHARSET); } /** diff --git a/src/main/java/redis/clients/jedis/util/ShardInfo.java b/src/main/java/redis/clients/jedis/util/ShardInfo.java deleted file mode 100644 index fd06665a57..0000000000 --- a/src/main/java/redis/clients/jedis/util/ShardInfo.java +++ /dev/null @@ -1,20 +0,0 @@ -package redis.clients.jedis.util; - -public abstract class ShardInfo { - private int weight; - - public ShardInfo() { - } - - public ShardInfo(int weight) { - this.weight = weight; - } - - public int getWeight() { - return this.weight; - } - - protected abstract T createResource(); - - public abstract String getName(); -} diff --git a/src/main/java/redis/clients/jedis/util/Sharded.java b/src/main/java/redis/clients/jedis/util/Sharded.java deleted file mode 100644 index 9d01a27a39..0000000000 --- a/src/main/java/redis/clients/jedis/util/Sharded.java +++ /dev/null @@ -1,109 +0,0 @@ -package redis.clients.jedis.util; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.SortedMap; -import java.util.TreeMap; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class Sharded> { - - public static final int DEFAULT_WEIGHT = 1; - private TreeMap nodes; - private final Hashing algo; - private final Map, R> resources = new LinkedHashMap<>(); - - /** - * The default pattern used for extracting a key tag. The pattern must have a group (between - * parenthesis), which delimits the tag to be hashed. A null pattern avoids applying the regular - * expression for each lookup, improving performance a little bit is key tags aren't being used. - */ - private Pattern tagPattern = null; - // the tag is anything between {} - public static final Pattern DEFAULT_KEY_TAG_PATTERN = Pattern.compile("\\{(.+?)\\}"); - - public Sharded(List shards) { - this(shards, Hashing.MURMUR_HASH); // MD5 is really not good as we works - // with 64-bits not 128 - } - - public Sharded(List shards, Hashing algo) { - this.algo = algo; - initialize(shards); - } - - public Sharded(List shards, Pattern tagPattern) { - this(shards, Hashing.MURMUR_HASH, tagPattern); // MD5 is really not good - // as we works with - // 64-bits not 128 - } - - public Sharded(List shards, Hashing algo, Pattern tagPattern) { - this.algo = algo; - this.tagPattern = tagPattern; - initialize(shards); - } - - private void initialize(List shards) { - nodes = new TreeMap<>(); - - for (int i = 0; i != shards.size(); ++i) { - final S shardInfo = shards.get(i); - int N = 160 * shardInfo.getWeight(); - if (shardInfo.getName() == null) for (int n = 0; n < N; n++) { - nodes.put(this.algo.hash("SHARD-" + i + "-NODE-" + n), shardInfo); - } - else for (int n = 0; n < N; n++) { - nodes.put(this.algo.hash(shardInfo.getName() + "*" + n), shardInfo); - } - resources.put(shardInfo, shardInfo.createResource()); - } - } - - public R getShard(byte[] key) { - return resources.get(getShardInfo(key)); - } - - public R getShard(String key) { - return resources.get(getShardInfo(key)); - } - - public S getShardInfo(byte[] key) { - SortedMap tail = nodes.tailMap(algo.hash(key)); - if (tail.isEmpty()) { - return nodes.get(nodes.firstKey()); - } - return tail.get(tail.firstKey()); - } - - public S getShardInfo(String key) { - return getShardInfo(SafeEncoder.encode(getKeyTag(key))); - } - - /** - * A key tag is a special pattern inside a key that, if preset, is the only part of the key hashed - * in order to select the server for this key. - * @see partitioning - * @param key - * @return The tag if it exists, or the original key - */ - public String getKeyTag(String key) { - if (tagPattern != null) { - Matcher m = tagPattern.matcher(key); - if (m.find()) return m.group(1); - } - return key; - } - - public Collection getAllShardInfo() { - return Collections.unmodifiableCollection(nodes.values()); - } - - public Collection getAllShards() { - return Collections.unmodifiableCollection(resources.values()); - } -} diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/ACLJedisPoolTest.java similarity index 94% rename from src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java rename to src/test/java/redis/clients/jedis/ACLJedisPoolTest.java index d504ebdb8a..7a878b015a 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/ACLJedisPoolTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -12,25 +12,17 @@ import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisFactory; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Protocol; import redis.clients.jedis.exceptions.InvalidURIException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.exceptions.JedisExhaustedPoolException; -import redis.clients.jedis.tests.utils.RedisVersionUtil; +import redis.clients.jedis.util.RedisVersionUtil; /** * This test class is a copy of {@link JedisPoolTest}. *

* This test is only executed when the server/cluster is Redis 6. or more. */ -public class JedisPoolWithCompleteCredentialsTest { - private static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); +public class ACLJedisPoolTest { + private static final HostAndPort hnp = HostAndPorts.getRedisServers().get(0); @BeforeClass public static void prepare() throws Exception { @@ -120,7 +112,7 @@ public void checkPoolRepairedWhenJedisIsBroken() { assertTrue(pool.isClosed()); } - @Test(expected = JedisExhaustedPoolException.class) + @Test(expected = JedisException.class) public void checkPoolOverflow() { GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); config.setMaxTotal(1); diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/ACLJedisSentinelPoolTest.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/JedisSentinelPoolWithCompleteCredentialsTest.java rename to src/test/java/redis/clients/jedis/ACLJedisSentinelPoolTest.java index b2e13455a2..f79245235a 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/ACLJedisSentinelPoolTest.java @@ -1,37 +1,31 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; + +import static org.junit.Assert.*; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisClientConfig; -import redis.clients.jedis.JedisSentinelPool; -import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.tests.utils.RedisVersionUtil; - -import static org.junit.Assert.*; +import redis.clients.jedis.util.RedisVersionUtil; /** * This test class is mostly a copy of {@link JedisSentinelPoolTest}. *

* This tests are only executed when the server/cluster is Redis 6 or more. */ -public class JedisSentinelPoolWithCompleteCredentialsTest { +public class ACLJedisSentinelPoolTest { private static final String MASTER_NAME = "aclmaster"; //protected static HostAndPort master = HostAndPortUtil.getRedisServers().get(8); - protected static HostAndPort sentinel1 = HostAndPortUtil.getSentinelServers().get(4); + protected static HostAndPort sentinel1 = HostAndPorts.getSentinelServers().get(4); protected Set sentinels = new HashSet<>(); diff --git a/src/test/java/redis/clients/jedis/tests/JedisWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/ACLJedisTest.java similarity index 77% rename from src/test/java/redis/clients/jedis/tests/JedisWithCompleteCredentialsTest.java rename to src/test/java/redis/clients/jedis/ACLJedisTest.java index 173d082e77..577280daa6 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/ACLJedisTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; @@ -7,20 +7,15 @@ import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisClientConfig; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.tests.commands.JedisCommandTestBase; -import redis.clients.jedis.tests.utils.RedisVersionUtil; +import redis.clients.jedis.commands.jedis.JedisCommandsTestBase; +import redis.clients.jedis.util.RedisVersionUtil; /** * This test class is a copy of {@link JedisTest}. *

* This test is only executed when the server/cluster is Redis 6. or more. */ -public class JedisWithCompleteCredentialsTest extends JedisCommandTestBase { +public class ACLJedisTest extends JedisCommandsTestBase { /** * Use to check if the ACL test should be ran. ACL are available only in 6.0 and later @@ -40,16 +35,6 @@ public void useWithoutConnecting() { } } - @Test - public void connectWithShardInfo() { - JedisShardInfo shardInfo = new JedisShardInfo("localhost", Protocol.DEFAULT_PORT); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - try (Jedis jedis = new Jedis(shardInfo)) { - jedis.get("foo"); - } - } - @Test public void connectWithConfig() { try (Jedis jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().build())) { @@ -129,15 +114,15 @@ public void connectWithURICredentials() throws URISyntaxException { public void allowUrlWithNoDBAndNoPassword() { try (Jedis j1 = new Jedis("redis://localhost:6379")) { assertEquals("OK", j1.auth("acljedis", "fizzbuzz")); - assertEquals("localhost", j1.getClient().getHost()); - assertEquals(6379, j1.getClient().getPort()); +// assertEquals("localhost", j1.getClient().getHost()); +// assertEquals(6379, j1.getClient().getPort()); assertEquals(0, j1.getDB()); } try (Jedis j2 = new Jedis("redis://localhost:6379/")) { assertEquals("OK", j2.auth("acljedis", "fizzbuzz")); - assertEquals("localhost", j2.getClient().getHost()); - assertEquals(6379, j2.getClient().getPort()); +// assertEquals("localhost", j2.getClient().getHost()); +// assertEquals(6379, j2.getClient().getPort()); assertEquals(0, j2.getDB()); } } diff --git a/src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java b/src/test/java/redis/clients/jedis/BuilderTest.java similarity index 84% rename from src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java rename to src/test/java/redis/clients/jedis/BuilderTest.java index a9ef9a6c5e..2ab8ed4bb5 100644 --- a/src/test/java/redis/clients/jedis/tests/BuilderFactoryTest.java +++ b/src/test/java/redis/clients/jedis/BuilderTest.java @@ -1,12 +1,11 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import org.junit.Test; -import redis.clients.jedis.BuilderFactory; +public class BuilderTest { -public class BuilderFactoryTest { @Test public void buildDouble() { Double build = BuilderFactory.DOUBLE.build("1.0".getBytes()); @@ -18,4 +17,4 @@ public void buildDouble() { build = BuilderFactory.DOUBLE.build("-inf".getBytes()); assertEquals(Double.valueOf(Double.NEGATIVE_INFINITY), build); } -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/ConnectionTest.java b/src/test/java/redis/clients/jedis/ConnectionTest.java new file mode 100644 index 0000000000..ee9a0a9742 --- /dev/null +++ b/src/test/java/redis/clients/jedis/ConnectionTest.java @@ -0,0 +1,43 @@ +package redis.clients.jedis; + +import org.junit.After; +import org.junit.Test; + +import redis.clients.jedis.exceptions.JedisConnectionException; + +public class ConnectionTest { + + private Connection client; + + @After + public void tearDown() throws Exception { + if (client != null) { + client.close(); + } + } + + @Test(expected = JedisConnectionException.class) + public void checkUnkownHost() { + client = new Connection("someunknownhost", Protocol.DEFAULT_PORT); + client.connect(); + } + + @Test(expected = JedisConnectionException.class) + public void checkWrongPort() { + client = new Connection(Protocol.DEFAULT_HOST, 55665); + client.connect(); + } + + @Test + public void connectIfNotConnectedWhenSettingTimeoutInfinite() { + client = new Connection("localhost", 6379); + client.setTimeoutInfinite(); + } + + @Test + public void checkCloseable() { + client = new Connection("localhost", 6379); + client.connect(); + client.close(); + } +} diff --git a/src/test/java/redis/clients/jedis/HostAndPortTest.java b/src/test/java/redis/clients/jedis/HostAndPortTest.java new file mode 100644 index 0000000000..14fe573e6b --- /dev/null +++ b/src/test/java/redis/clients/jedis/HostAndPortTest.java @@ -0,0 +1,23 @@ +package redis.clients.jedis; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +public class HostAndPortTest { + + @Test + public void checkFrom() throws Exception { + String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e:1999"; + int port = 6379; + HostAndPort hp = HostAndPort.from(host + ":" + Integer.toString(port)); + assertEquals(host, hp.getHost()); + assertEquals(port, hp.getPort()); + } + + @Test(expected = IllegalArgumentException.class) + public void checkFromWithoutPort() throws Exception { + String host = "localhost"; + HostAndPort.from(host + ":"); + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java b/src/test/java/redis/clients/jedis/HostAndPorts.java similarity index 82% rename from src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java rename to src/test/java/redis/clients/jedis/HostAndPorts.java index 180f00fb17..0ce0269f2a 100644 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortUtil.java +++ b/src/test/java/redis/clients/jedis/HostAndPorts.java @@ -1,20 +1,14 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import java.util.ArrayList; import java.util.List; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Protocol; +public final class HostAndPorts { -public final class HostAndPortUtil { private static List redisHostAndPortList = new ArrayList<>(); private static List sentinelHostAndPortList = new ArrayList<>(); private static List clusterHostAndPortList = new ArrayList<>(); - private HostAndPortUtil() { - throw new InstantiationError("Must not instantiate this class"); - } - static { redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT)); redisHostAndPortList.add(new HostAndPort("localhost", Protocol.DEFAULT_PORT + 1)); @@ -55,19 +49,7 @@ public static List parseHosts(String envHosts, for (String hostDef : hostDefs) { - String[] hostAndPortParts = HostAndPort.extractParts(hostDef); - - if (null != hostAndPortParts && 2 == hostAndPortParts.length) { - String host = hostAndPortParts[0]; - int port = Protocol.DEFAULT_PORT; - - try { - port = Integer.parseInt(hostAndPortParts[1]); - } catch (final NumberFormatException nfe) { - } - - envHostsAndPorts.add(new HostAndPort(host, port)); - } + envHostsAndPorts.add(HostAndPort.from(hostDef)); } return envHostsAndPorts; @@ -88,4 +70,8 @@ public static List getSentinelServers() { public static List getClusterServers() { return clusterHostAndPortList; } + + private HostAndPorts() { + throw new InstantiationError("Must not instantiate this class"); + } } diff --git a/src/test/java/redis/clients/jedis/JedisClusterCommandTest.java b/src/test/java/redis/clients/jedis/JedisClusterCommandTest.java new file mode 100644 index 0000000000..d357562c5f --- /dev/null +++ b/src/test/java/redis/clients/jedis/JedisClusterCommandTest.java @@ -0,0 +1,371 @@ +//package redis.clients.jedis; +// +//import static org.junit.Assert.assertEquals; +//import static org.junit.Assert.assertNotNull; +//import static org.junit.Assert.assertTrue; +//import static org.junit.Assert.fail; +//import static org.mockito.ArgumentMatchers.any; +//import static org.mockito.ArgumentMatchers.anyInt; +//import static org.mockito.ArgumentMatchers.anyLong; +//import static org.mockito.Mockito.doAnswer; +//import static org.mockito.Mockito.inOrder; +//import static org.mockito.Mockito.mock; +//import static org.mockito.Mockito.times; +//import static org.mockito.Mockito.when; +// +//import java.time.Duration; +//import java.util.concurrent.atomic.AtomicLong; +//import java.util.function.LongConsumer; +//import org.junit.Test; +//import org.mockito.InOrder; +//import org.mockito.invocation.InvocationOnMock; +//import org.mockito.stubbing.Answer; +//import redis.clients.jedis.HostAndPort; +//import redis.clients.jedis.Jedis; +//import redis.clients.jedis.JedisClusterCommand; +//import redis.clients.jedis.JedisClusterConnectionHandler; +//import redis.clients.jedis.JedisSlotBasedConnectionHandler; +//import redis.clients.jedis.exceptions.JedisAskDataException; +//import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; +//import redis.clients.jedis.exceptions.JedisClusterOperationException; +//import redis.clients.jedis.exceptions.JedisConnectionException; +//import redis.clients.jedis.exceptions.JedisMovedDataException; +//import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; +// +//public class JedisClusterCommandTest { +// +// private static final Duration ONE_SECOND = Duration.ofSeconds(1); +// +// @Test +// public void runSuccessfulExecute() { +// JedisClusterConnectionHandler connectionHandler = mock(JedisClusterConnectionHandler.class); +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, +// Duration.ZERO) { +// @Override +// public String execute(Jedis connection) { +// return "foo"; +// } +// +// @Override +// protected void sleep(long ignored) { +// throw new RuntimeException("This test should never sleep"); +// } +// }; +// String actual = testMe.run(""); +// assertEquals("foo", actual); +// } +// +// @Test +// public void runFailOnFirstExecSuccessOnSecondExec() { +// JedisClusterConnectionHandler connectionHandler = mock(JedisClusterConnectionHandler.class); +// +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, +// ONE_SECOND) { +// boolean isFirstCall = true; +// +// @Override +// public String execute(Jedis connection) { +// if (isFirstCall) { +// isFirstCall = false; +// throw new JedisConnectionException("Borkenz"); +// } +// +// return "foo"; +// } +// +// @Override +// protected void sleep(long ignored) { +// throw new RuntimeException("This test should never sleep"); +// } +// }; +// +// String actual = testMe.run(""); +// assertEquals("foo", actual); +// } +// +// @Test +// public void runAlwaysFailing() { +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// +// final LongConsumer sleep = mock(LongConsumer.class); +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 3, +// ONE_SECOND) { +// @Override +// public String execute(Jedis connection) { +// throw new JedisConnectionException("Connection failed"); +// } +// +// @Override +// protected void sleep(long sleepMillis) { +// sleep.accept(sleepMillis); +// } +// }; +// +// try { +// testMe.run(""); +// fail("cluster command did not fail"); +// } catch (JedisClusterMaxAttemptsException e) { +// // expected +// } +// InOrder inOrder = inOrder(connectionHandler, sleep); +// inOrder.verify(connectionHandler, times(2)).getConnectionFromSlot(anyInt()); +// inOrder.verify(sleep).accept(anyLong()); +// inOrder.verify(connectionHandler).renewSlotCache(); +// inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); +// inOrder.verifyNoMoreInteractions(); +// } +// +// @Test +// public void runMovedSuccess() { +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// +// final HostAndPort movedTarget = new HostAndPort(null, 0); +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, +// ONE_SECOND) { +// boolean isFirstCall = true; +// +// @Override +// public String execute(Jedis connection) { +// if (isFirstCall) { +// isFirstCall = false; +// +// // Slot 0 moved +// throw new JedisMovedDataException("", movedTarget, 0); +// } +// +// return "foo"; +// } +// +// @Override +// protected void sleep(long ignored) { +// throw new RuntimeException("This test should never sleep"); +// } +// }; +// +// String actual = testMe.run(""); +// assertEquals("foo", actual); +// +// InOrder inOrder = inOrder(connectionHandler); +// inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); +// inOrder.verify(connectionHandler).renewSlotCache(any()); +// inOrder.verify(connectionHandler).getConnectionFromNode(movedTarget); +// inOrder.verifyNoMoreInteractions(); +// } +// +// @Test +// public void runAskSuccess() { +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// Jedis connection = mock(Jedis.class); +// final HostAndPort askTarget = new HostAndPort(null, 0); +// when(connectionHandler.getConnectionFromNode(askTarget)).thenReturn(connection); +// +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, +// ONE_SECOND) { +// boolean isFirstCall = true; +// +// @Override +// public String execute(Jedis connection) { +// if (isFirstCall) { +// isFirstCall = false; +// +// // Slot 0 moved +// throw new JedisAskDataException("", askTarget, 0); +// } +// +// return "foo"; +// } +// +// @Override +// protected void sleep(long ignored) { +// throw new RuntimeException("This test should never sleep"); +// } +// }; +// +// String actual = testMe.run(""); +// assertEquals("foo", actual); +// +// InOrder inOrder = inOrder(connectionHandler, connection); +// inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); +// inOrder.verify(connectionHandler).getConnectionFromNode(askTarget); +// inOrder.verify(connection).asking(); +// inOrder.verify(connection).close(); // From the finally clause in runWithRetries() +// inOrder.verifyNoMoreInteractions(); +// } +// +// @Test +// public void runMovedThenAllNodesFailing() { +// // Test: +// // First attempt is a JedisMovedDataException() move, because we asked the wrong node. +// // All subsequent attempts are JedisConnectionExceptions, because all nodes are now down. +// // In response to the JedisConnectionExceptions, run() retries random nodes until maxAttempts is +// // reached. +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// +// final Jedis redirecter = mock(Jedis.class); +// when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(redirecter); +// +// final Jedis failer = mock(Jedis.class); +// when(connectionHandler.getConnectionFromNode(any(HostAndPort.class))).thenReturn(failer); +// doAnswer((Answer) (InvocationOnMock invocation) -> { +// when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(failer); +// return null; +// }).when(connectionHandler).renewSlotCache(); +// +// final LongConsumer sleep = mock(LongConsumer.class); +// final HostAndPort movedTarget = new HostAndPort(null, 0); +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 5, +// ONE_SECOND) { +// @Override +// public String execute(Jedis connection) { +// if (redirecter == connection) { +// // First attempt, report moved +// throw new JedisMovedDataException("Moved", movedTarget, 0); +// } +// +// if (failer == connection) { +// // Second attempt in response to the move, report failure +// throw new JedisConnectionException("Connection failed"); +// } +// +// throw new IllegalStateException("Should have thrown jedis exception"); +// } +// +// @Override +// protected void sleep(long sleepMillis) { +// sleep.accept(sleepMillis); +// } +// }; +// +// try { +// testMe.run(""); +// fail("cluster command did not fail"); +// } catch (JedisClusterMaxAttemptsException e) { +// // expected +// } +// InOrder inOrder = inOrder(connectionHandler, sleep); +// inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); +// inOrder.verify(connectionHandler).renewSlotCache(redirecter); +// inOrder.verify(connectionHandler, times(2)).getConnectionFromNode(movedTarget); +// inOrder.verify(sleep).accept(anyLong()); +// inOrder.verify(connectionHandler).renewSlotCache(); +// inOrder.verify(connectionHandler, times(2)).getConnectionFromSlot(anyInt()); +// inOrder.verify(sleep).accept(anyLong()); +// inOrder.verify(connectionHandler).renewSlotCache(); +// inOrder.verifyNoMoreInteractions(); +// } +// +// @Test +// public void runMasterFailingReplicaRecovering() { +// // We have two nodes, master and replica, and master has just gone down permanently. +// // +// // Test: +// // 1. We try to contact master => JedisConnectionException +// // 2. We try to contact master => JedisConnectionException +// // 3. sleep and renew +// // 4. We try to contact replica => Success, because it has now failed over +// +// final Jedis master = mock(Jedis.class); +// when(master.toString()).thenReturn("master"); +// +// final Jedis replica = mock(Jedis.class); +// when(replica.toString()).thenReturn("replica"); +// +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// +// when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(master); +// +// doAnswer((Answer) (InvocationOnMock invocation) -> { +// when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(replica); +// return null; +// }).when(connectionHandler).renewSlotCache(); +// +// final AtomicLong totalSleepMs = new AtomicLong(); +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, +// ONE_SECOND) { +// +// @Override +// public String execute(Jedis connection) { +// assertNotNull(connection); +// +// if (connection == master) { +// throw new JedisConnectionException("Master is down"); +// } +// +// assert connection == replica; +// +// return "Success!"; +// } +// +// @Override +// protected void sleep(long sleepMillis) { +// assert sleepMillis > 0; +// totalSleepMs.addAndGet(sleepMillis); +// } +// }; +// +// assertEquals("Success!", testMe.run("")); +// InOrder inOrder = inOrder(connectionHandler); +// inOrder.verify(connectionHandler, times(2)).getConnectionFromSlot(anyInt()); +// inOrder.verify(connectionHandler).renewSlotCache(); +// inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); +// inOrder.verifyNoMoreInteractions(); +// assertTrue(totalSleepMs.get() > 0); +// } +// +// @Test(expected = JedisNoReachableClusterNodeException.class) +// public void runRethrowsJedisNoReachableClusterNodeException() { +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// when(connectionHandler.getConnectionFromSlot(anyInt())).thenThrow( +// JedisNoReachableClusterNodeException.class); +// +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, +// Duration.ZERO) { +// @Override +// public String execute(Jedis connection) { +// return null; +// } +// +// @Override +// protected void sleep(long ignored) { +// throw new RuntimeException("This test should never sleep"); +// } +// }; +// +// testMe.run(""); +// } +// +// @Test +// public void runStopsRetryingAfterTimeout() { +// JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); +// +// final LongConsumer sleep = mock(LongConsumer.class); +// JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 3, +// Duration.ZERO) { +// @Override +// public String execute(Jedis connection) { +// try { +// // exceed deadline +// Thread.sleep(2L); +// } catch (InterruptedException e) { +// throw new RuntimeException(e); +// } +// throw new JedisConnectionException("Connection failed"); +// } +// +// @Override +// protected void sleep(long sleepMillis) { +// sleep.accept(sleepMillis); +// } +// }; +// +// try { +// testMe.run(""); +// fail("cluster command did not fail"); +// } catch (JedisClusterOperationException e) { +// // expected +// } +// InOrder inOrder = inOrder(connectionHandler, sleep); +// inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); +// inOrder.verifyNoMoreInteractions(); +// } +//} diff --git a/src/test/java/redis/clients/jedis/JedisClusterPipelineTest.java b/src/test/java/redis/clients/jedis/JedisClusterPipelineTest.java new file mode 100644 index 0000000000..9f2296eb06 --- /dev/null +++ b/src/test/java/redis/clients/jedis/JedisClusterPipelineTest.java @@ -0,0 +1,461 @@ +package redis.clients.jedis; + +import static org.hamcrest.CoreMatchers.equalTo; +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThat; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static redis.clients.jedis.Protocol.CLUSTER_HASHSLOTS; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.hamcrest.CoreMatchers; +import org.hamcrest.Matcher; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.args.ClusterResetType; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.providers.ClusterConnectionProvider; +import redis.clients.jedis.resps.Tuple; +import redis.clients.jedis.util.JedisClusterTestUtil; +import redis.clients.jedis.util.SafeEncoder; + +public class JedisClusterPipelineTest { + private static Jedis node1; + private static Jedis node2; + private static Jedis node3; + private static final String LOCAL_IP = "127.0.0.1"; + private static final int DEFAULT_TIMEOUT = 2000; + private static final int DEFAULT_REDIRECTIONS = 5; + private static final ConnectionPoolConfig DEFAULT_POOL_CONFIG = new ConnectionPoolConfig(); + private static final DefaultJedisClientConfig DEFAULT_CLIENT_CONFIG = DefaultJedisClientConfig + .builder().password("cluster").build(); + + private HostAndPort nodeInfo1 = HostAndPorts.getClusterServers().get(0); + private HostAndPort nodeInfo2 = HostAndPorts.getClusterServers().get(1); + private HostAndPort nodeInfo3 = HostAndPorts.getClusterServers().get(2); + private Set nodes = new HashSet<>(); + { + nodes.add(nodeInfo1); + nodes.add(nodeInfo2); + nodes.add(nodeInfo3); + } + + @Before + public void setUp() throws InterruptedException { + node1 = new Jedis(nodeInfo1); + node1.auth("cluster"); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2); + node2.auth("cluster"); + node2.flushAll(); + + node3 = new Jedis(nodeInfo3); + node3.auth("cluster"); + node3.flushAll(); + + // add nodes to cluster + node1.clusterMeet(LOCAL_IP, nodeInfo2.getPort()); + node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); + + // split available slots across the three nodes + int slotsPerNode = CLUSTER_HASHSLOTS / 3; + int[] node1Slots = new int[slotsPerNode]; + int[] node2Slots = new int[slotsPerNode + 1]; + int[] node3Slots = new int[slotsPerNode]; + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < CLUSTER_HASHSLOTS; i++) { + if (i < slotsPerNode) { + node1Slots[slot1++] = i; + } else if (i > slotsPerNode * 2) { + node3Slots[slot3++] = i; + } else { + node2Slots[slot2++] = i; + } + } + + node1.clusterAddSlots(node1Slots); + node2.clusterAddSlots(node2Slots); + node3.clusterAddSlots(node3Slots); + + JedisClusterTestUtil.waitForClusterReady(node1, node2, node3); + } + + @AfterClass + public static void cleanUp() { + node1.flushDB(); + node2.flushDB(); + node3.flushDB(); + node1.clusterReset(ClusterResetType.SOFT); + node2.clusterReset(ClusterResetType.SOFT); + node3.clusterReset(ClusterResetType.SOFT); + } + + @After + public void tearDown() throws InterruptedException { + cleanUp(); + } + + @Test + public void clusterPipelineSync() { + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline clusterPipeline = new ClusterPipeline(provider); + + Response r1 = clusterPipeline.set("key1", "value1"); + Response r2 = clusterPipeline.set("key2", "value2"); + Response r3 = clusterPipeline.set("key3", "value3"); + Response r4 = clusterPipeline.get("key1"); + Response r5 = clusterPipeline.get("key2"); + Response r6 = clusterPipeline.get("key3"); + + clusterPipeline.sync(); + Assert.assertEquals("OK", r1.get()); + Assert.assertEquals("OK", r2.get()); + Assert.assertEquals("OK", r3.get()); + Assert.assertEquals("value1", r4.get()); + Assert.assertEquals("value2", r5.get()); + Assert.assertEquals("value3", r6.get()); + } + + @Test + public void pipelineResponse() { + try (JedisCluster jc = new JedisCluster(nodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + jc.set("string", "foo"); + jc.lpush("list", "foo"); + jc.hset("hash", "foo", "bar"); + jc.zadd("zset", 1, "foo"); + jc.sadd("set", "foo"); + jc.setrange("setrange", 0, "0123456789"); + byte[] bytesForSetRange = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + jc.setrange("setrangebytes".getBytes(), 0, bytesForSetRange); + } + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + + Response string = p.get("string"); + Response list = p.lpop("list"); + Response hash = p.hget("hash", "foo"); + Response> zset = p.zrange("zset", 0, -1); + Response set = p.spop("set"); + Response blist = p.exists("list"); + Response zincrby = p.zincrby("zset", 1, "foo"); + Response zcard = p.zcard("zset"); + p.lpush("list", "bar"); + Response> lrange = p.lrange("list", 0, -1); + Response> hgetAll = p.hgetAll("hash"); + p.sadd("set", "foo"); + Response> smembers = p.smembers("set"); + Response> zrangeWithScores = p.zrangeWithScores("zset", 0, -1); + Response getrange = p.getrange("setrange", 1, 3); + Response getrangeBytes = p.getrange("setrangebytes".getBytes(), 6, 8); + p.sync(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + assertEquals(false, blist.get()); + assertEquals(Double.valueOf(2), zincrby.get()); + assertEquals(Long.valueOf(1), zcard.get()); + assertEquals(1, lrange.get().size()); + assertNotNull(hgetAll.get().get("foo")); + assertEquals(1, smembers.get().size()); + assertEquals(1, zrangeWithScores.get().size()); + assertEquals("123", getrange.get()); + byte[] expectedGetRangeBytes = { 6, 7, 8 }; + assertArrayEquals(expectedGetRangeBytes, getrangeBytes.get()); + } + + @Test + public void pipelineBinarySafeHashCommands() { + try (JedisCluster jc = new JedisCluster(nodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + jc.hset("key".getBytes(), "f1".getBytes(), "v111".getBytes()); + jc.hset("key".getBytes(), "f22".getBytes(), "v2222".getBytes()); + } + + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response> fmap = p.hgetAll("key".getBytes()); + Response> fkeys = p.hkeys("key".getBytes()); + Response> fordered = p.hmget("key".getBytes(), "f22".getBytes(), "f1".getBytes()); + Response> fvals = p.hvals("key".getBytes()); + p.sync(); + + assertNotNull(fmap.get()); + // we have to do these strange contortions because byte[] is not a very + // good key + // for a java Map. It only works with equality (you need the exact key + // object to retrieve + // the value) I recommend we switch to using ByteBuffer or something + // similar: + // http://stackoverflow.com/questions/1058149/using-a-byte-array-as-hashmap-key-java + Map map = fmap.get(); + Set mapKeys = map.keySet(); + Iterator iterMap = mapKeys.iterator(); + byte[] firstMapKey = iterMap.next(); + byte[] secondMapKey = iterMap.next(); + assertFalse(iterMap.hasNext()); + verifyHasBothValues(firstMapKey, secondMapKey, "f1".getBytes(), "f22".getBytes()); + byte[] firstMapValue = map.get(firstMapKey); + byte[] secondMapValue = map.get(secondMapKey); + verifyHasBothValues(firstMapValue, secondMapValue, "v111".getBytes(), "v2222".getBytes()); + + assertNotNull(fkeys.get()); + Iterator iter = fkeys.get().iterator(); + byte[] firstKey = iter.next(); + byte[] secondKey = iter.next(); + assertFalse(iter.hasNext()); + verifyHasBothValues(firstKey, secondKey, "f1".getBytes(), "f22".getBytes()); + + assertNotNull(fordered.get()); + assertArrayEquals("v2222".getBytes(), fordered.get().get(0)); + assertArrayEquals("v111".getBytes(), fordered.get().get(1)); + + assertNotNull(fvals.get()); + assertEquals(2, fvals.get().size()); + byte[] firstValue = fvals.get().get(0); + byte[] secondValue = fvals.get().get(1); + verifyHasBothValues(firstValue, secondValue, "v111".getBytes(), "v2222".getBytes()); + } + + private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, byte[] value1, byte[] value2) { + assertFalse(Arrays.equals(firstKey, secondKey)); + assertTrue(Arrays.equals(firstKey, value1) || Arrays.equals(firstKey, value2)); + assertTrue(Arrays.equals(secondKey, value1) || Arrays.equals(secondKey, value2)); + } + + @Test(expected = IllegalStateException.class) + public void pipelineResponseWithinPipeline() { + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response string = p.get("string"); + string.get(); + p.sync(); + } + + @Test + public void pipelineWithPubSub() { + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline pipelined = new ClusterPipeline(provider); + Response p1 = pipelined.publish("foo", "bar"); + Response p2 = pipelined.publish("foo".getBytes(), "bar".getBytes()); + pipelined.sync(); + assertEquals(0, p1.get().longValue()); + assertEquals(0, p2.get().longValue()); + } + + @Test + public void canRetrieveUnsetKey() { + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response shouldNotExist = p.get(UUID.randomUUID().toString()); + p.sync(); + assertNull(shouldNotExist.get()); + } + + @Test + public void piplineWithError() { + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + p.set("foo", "bar"); + Response> error = p.smembers("foo"); + Response r = p.get("foo"); + p.sync(); + try { + error.get(); + fail(); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals(r.get(), "bar"); + } + + @Test + public void testEval() { + String script = "return 'success!'"; + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response result = p.eval(script); + p.sync(); + + assertEquals("success!", result.get()); + } + + @Test + public void testEvalWithBinary() { + String script = "return 'success!'"; + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response result = p.eval(SafeEncoder.encode(script)); + p.sync(); + + assertArrayEquals(SafeEncoder.encode("success!"), (byte[]) result.get()); + } + + @Test + public void testEvalKeyAndArg() { + String key = "test"; + String arg = "3"; + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + p.set(key, "0"); + Response result0 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); + p.incr(key); + Response result1 = p.eval(script, Arrays.asList(key), Arrays.asList(arg)); + Response result2 = p.get(key); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertEquals("13", result2.get()); + } + + @Test + public void testEvalKeyAndArgWithBinary() { + // binary + byte[] bKey = SafeEncoder.encode("test"); + byte[] bArg = SafeEncoder.encode("3"); + byte[] bScript = SafeEncoder + .encode("redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"); + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline bP = new ClusterPipeline(provider); + bP.set(bKey, SafeEncoder.encode("0")); + Response bResult0 = bP.eval(bScript, Arrays.asList(bKey), Arrays.asList(bArg)); + bP.incr(bKey); + Response bResult1 = bP.eval(bScript, Arrays.asList(bKey), Arrays.asList(bArg)); + Response bResult2 = bP.get(bKey); + bP.sync(); + + assertNull(bResult0.get()); + assertNull(bResult1.get()); + assertArrayEquals(SafeEncoder.encode("13"), bResult2.get()); + } + + @Test + public void testEvalNestedLists() { + String script = "return { {KEYS[1]} , {2} }"; + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response result = p.eval(script, 1, "key1"); + p.sync(); + + List results = (List) result.get(); + assertThat((List) results.get(0), listWithItem("key1")); + assertThat((List) results.get(1), listWithItem(2L)); + } + + @Test + public void testEvalNestedListsWithBinary() { + byte[] bScript = SafeEncoder.encode("return { {KEYS[1]} , {2} }"); + byte[] bKey = SafeEncoder.encode("key1"); + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response result = p.eval(bScript, 1, bKey); + p.sync(); + + List results = (List) result.get(); + assertThat((List) results.get(0), listWithItem(bKey)); + assertThat((List) results.get(1), listWithItem(2L)); + } + + @Test + public void testEvalsha() { + String script = "return 'success!'"; + String sha1; + try (JedisCluster jc = new JedisCluster(nodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + sha1 = jc.scriptLoad(script, "sampleKey"); + assertTrue(jc.scriptExists(sha1, "sampleKey")); + } + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + Response result = p.evalsha(sha1, 1, "sampleKey"); + p.sync(); + + assertEquals("success!", result.get()); + } + + @Test + public void testEvalshaKeyAndArg() { + String key = "test"; + String arg = "3"; + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + String sha1; + try (JedisCluster jc = new JedisCluster(nodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + sha1 = jc.scriptLoad(script, key); + assertTrue(jc.scriptExists(sha1, key)); + } + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + p.set(key, "0"); + Response result0 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); + p.incr(key); + Response result1 = p.evalsha(sha1, Arrays.asList(key), Arrays.asList(arg)); + Response result2 = p.get(key); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertEquals("13", result2.get()); + } + + @Test + public void testEvalshaKeyAndArgWithBinary() { + byte[] bKey = SafeEncoder.encode("test"); + byte[] bArg = SafeEncoder.encode("3"); + String script = "redis.call('INCRBY', KEYS[1], ARGV[1]) redis.call('INCRBY', KEYS[1], ARGV[1])"; + byte[] bScript = SafeEncoder.encode(script); + byte[] bSha1; + try (JedisCluster jc = new JedisCluster(nodes, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, + DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { + bSha1 = jc.scriptLoad(bScript, bKey); + assertTrue(jc.scriptExists(bSha1, bKey)); + } + + ClusterConnectionProvider provider = new ClusterConnectionProvider(nodes, DEFAULT_CLIENT_CONFIG); + ClusterPipeline p = new ClusterPipeline(provider); + p.set(bKey, SafeEncoder.encode("0")); + Response result0 = p.evalsha(bSha1, Arrays.asList(bKey), Arrays.asList(bArg)); + p.incr(bKey); + Response result1 = p.evalsha(bSha1, Arrays.asList(bKey), Arrays.asList(bArg)); + Response result2 = p.get(bKey); + p.sync(); + + assertNull(result0.get()); + assertNull(result1.get()); + assertArrayEquals(SafeEncoder.encode("13"), result2.get()); + } + + private Matcher> listWithItem(T expected) { + return CoreMatchers. hasItem(equalTo(expected)); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java b/src/test/java/redis/clients/jedis/JedisClusterTest.java similarity index 82% rename from src/test/java/redis/clients/jedis/tests/JedisClusterTest.java rename to src/test/java/redis/clients/jedis/JedisClusterTest.java index 8efd87e4f2..e43f9423da 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/JedisClusterTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -6,11 +6,12 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; + +import static redis.clients.jedis.Protocol.CLUSTER_HASHSLOTS; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.io.IOException; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; @@ -33,22 +34,15 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import redis.clients.jedis.GeoCoordinate; -import redis.clients.jedis.GeoUnit; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.ClusterReset; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.JedisClusterInfoCache; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; +import redis.clients.jedis.args.ClusterResetType; +import redis.clients.jedis.args.GeoUnit; import redis.clients.jedis.exceptions.*; import redis.clients.jedis.params.GeoRadiusParam; import redis.clients.jedis.params.GeoRadiusStoreParam; -import redis.clients.jedis.tests.utils.ClientKillerUtil; -import redis.clients.jedis.tests.utils.JedisClusterTestUtil; +import redis.clients.jedis.util.ClientKillerUtil; +import redis.clients.jedis.util.JedisClusterTestUtil; import redis.clients.jedis.util.JedisClusterCRC16; +import redis.clients.jedis.util.Pool; public class JedisClusterTest { private static Jedis node1; @@ -60,15 +54,15 @@ public class JedisClusterTest { private static final int DEFAULT_TIMEOUT = 2000; private static final int DEFAULT_REDIRECTIONS = 5; - private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); + private static final ConnectionPoolConfig DEFAULT_POOL_CONFIG = new ConnectionPoolConfig(); private static final DefaultJedisClientConfig DEFAULT_CLIENT_CONFIG = DefaultJedisClientConfig.builder().password("cluster").build(); - private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); - private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); - private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); - private HostAndPort nodeInfo4 = HostAndPortUtil.getClusterServers().get(3); - private HostAndPort nodeInfoSlave2 = HostAndPortUtil.getClusterServers().get(4); + private HostAndPort nodeInfo1 = HostAndPorts.getClusterServers().get(0); + private HostAndPort nodeInfo2 = HostAndPorts.getClusterServers().get(1); + private HostAndPort nodeInfo3 = HostAndPorts.getClusterServers().get(2); + private HostAndPort nodeInfo4 = HostAndPorts.getClusterServers().get(3); + private HostAndPort nodeInfoSlave2 = HostAndPorts.getClusterServers().get(4); protected Logger log = LoggerFactory.getLogger(getClass().getName()); @Before @@ -99,11 +93,11 @@ public void setUp() throws InterruptedException { node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); // split available slots across the three nodes - int slotsPerNode = JedisCluster.HASHSLOTS / 3; + int slotsPerNode = CLUSTER_HASHSLOTS / 3; int[] node1Slots = new int[slotsPerNode]; int[] node2Slots = new int[slotsPerNode + 1]; int[] node3Slots = new int[slotsPerNode]; - for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) { + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < CLUSTER_HASHSLOTS; i++) { if (i < slotsPerNode) { node1Slots[slot1++] = i; } else if (i > slotsPerNode * 2) { @@ -126,10 +120,10 @@ public static void cleanUp() { node2.flushDB(); node3.flushDB(); node4.flushDB(); - node1.clusterReset(ClusterReset.SOFT); - node2.clusterReset(ClusterReset.SOFT); - node3.clusterReset(ClusterReset.SOFT); - node4.clusterReset(ClusterReset.SOFT); + node1.clusterReset(ClusterResetType.SOFT); + node2.clusterReset(ClusterResetType.SOFT); + node3.clusterReset(ClusterResetType.SOFT); + node4.clusterReset(ClusterResetType.SOFT); } @After @@ -164,7 +158,7 @@ public void testThrowAskException() { @Test public void testDiscoverNodesAutomatically() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -195,20 +189,25 @@ public void testDiscoverNodesAutomaticallyWithSocketConfig() { @Test public void testSetClientName() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); String clientName = "myAppName"; try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", clientName, DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc.getClusterNodes(); - Collection values = clusterNodes.values(); - for (JedisPool jedisPool : values) { - Jedis jedis = jedisPool.getResource(); - try { +// Map clusterNodes = jc.getClusterNodes(); +// Collection values = clusterNodes.values(); +// for (JedisPool jedisPool : values) { +// Jedis jedis = jedisPool.getResource(); +// try { +// assertEquals(clientName, jedis.clientGetname()); +// } finally { +// jedis.close(); +// } +// } + for (Pool pool : jc.getClusterNodes().values()) { + try (Jedis jedis = new Jedis(pool.getResource())) { assertEquals(clientName, jedis.clientGetname()); - } finally { - jedis.close(); } } } @@ -221,8 +220,13 @@ public void testSetClientNameWithConfig() { try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DefaultJedisClientConfig.builder().password("cluster").clientName(clientName).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { - jc.getClusterNodes().values().forEach(jedisPool -> { - try (Jedis jedis = jedisPool.getResource()) { +// jc.getClusterNodes().values().forEach(jedisPool -> { +// try (Jedis jedis = jedisPool.getResource()) { +// assertEquals(clientName, jedis.clientGetname()); +// } +// }); + jc.getClusterNodes().values().forEach(pool -> { + try (Jedis jedis = new Jedis(pool.getResource())) { assertEquals(clientName, jedis.clientGetname()); } }); @@ -231,7 +235,7 @@ public void testSetClientNameWithConfig() { @Test public void testCalculateConnectionPerSlot() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -278,7 +282,7 @@ public void testReadonlyAndReadwrite() throws Exception { } catch (JedisMovedDataException e) { } - nodeSlave2.clusterReset(ClusterReset.SOFT); + nodeSlave2.clusterReset(ClusterResetType.SOFT); nodeSlave2.flushDB(); } @@ -288,7 +292,7 @@ public void testReadonlyAndReadwrite() throws Exception { @Test public void testMigrate() { log.info("test migrate slot"); - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(nodeInfo1); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { @@ -339,7 +343,7 @@ public void testMigrate() { @Test public void testMigrateToNewNode() throws InterruptedException { log.info("test migrate slot to new node"); - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(nodeInfo1); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { @@ -399,7 +403,7 @@ public void testMigrateToNewNode() throws InterruptedException { @Test public void testRecalculateSlotsWhenMoved() throws InterruptedException { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -417,7 +421,7 @@ public void testRecalculateSlotsWhenMoved() throws InterruptedException { @Test public void testAskResponse() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -443,9 +447,10 @@ public void testAskResponseWithConfig() { } } - @Test(expected = JedisClusterMaxAttemptsException.class) +// @Test(expected = JedisClusterMaxAttemptsException.class) + @Test(expected = JedisClusterOperationException.class) public void testRedisClusterMaxRedirections() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -457,7 +462,8 @@ public void testRedisClusterMaxRedirections() { } } - @Test(expected = JedisClusterMaxAttemptsException.class) +// @Test(expected = JedisClusterMaxAttemptsException.class) + @Test(expected = JedisClusterOperationException.class) public void testRedisClusterMaxRedirectionsWithConfig() { HostAndPort hp = new HostAndPort("127.0.0.1", 7379); try (JedisCluster jc = new JedisCluster(Collections.singleton(hp), DEFAULT_CLIENT_CONFIG, @@ -541,7 +547,7 @@ public void testClusterKeySlot() { @Test public void testClusterCountKeysInSlot() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -560,7 +566,7 @@ public void testClusterCountKeysInSlot() { @Test public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() throws InterruptedException { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -582,12 +588,13 @@ public void testStableSlotWhenMigratingNodeOrImportingNodeIsNotSpecified() } } - @Test(expected = JedisExhaustedPoolException.class) +// @Test(expected = JedisExhaustedPoolException.class) + @Test(expected = JedisException.class) public void testIfPoolConfigAppliesToClusterPools() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); config.setMaxTotal(0); config.setMaxWaitMillis(DEFAULT_TIMEOUT); - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config)) { @@ -597,7 +604,7 @@ public void testIfPoolConfigAppliesToClusterPools() { @Test public void testCloseable() throws IOException { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, @@ -622,17 +629,22 @@ public void testCloseableWithConfig() { @Test public void testJedisClusterTimeout() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); try (JedisCluster jc = new JedisCluster(jedisClusterNode, 4000, 4000, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { - for (JedisPool pool : jc.getClusterNodes().values()) { - Jedis jedis = pool.getResource(); - assertEquals(4000, jedis.getClient().getConnectionTimeout()); - assertEquals(4000, jedis.getClient().getSoTimeout()); - jedis.close(); +// for (JedisPool pool : jc.getClusterNodes().values()) { +// Jedis jedis = pool.getResource(); +// assertEquals(4000, jedis.getClient().getConnectionTimeout()); +// assertEquals(4000, jedis.getClient().getSoTimeout()); +// jedis.close(); +// } + for (Pool pool : jc.getClusterNodes().values()) { + try (Connection conn = pool.getResource()) { + assertEquals(4000, conn.getSoTimeout()); + } } } } @@ -645,9 +657,12 @@ public void testJedisClusterTimeoutWithConfig() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.getClusterNodes().values().forEach(pool -> { - try (Jedis jedis = pool.getResource()) { - assertEquals(4000, jedis.getClient().getConnectionTimeout()); - assertEquals(4000, jedis.getClient().getSoTimeout()); +// try (Jedis jedis = pool.getResource()) { +// assertEquals(4000, jedis.getClient().getConnectionTimeout()); +// assertEquals(4000, jedis.getClient().getSoTimeout()); +// } + try (Connection conn = pool.getResource()) { + assertEquals(4000, conn.getSoTimeout()); } }); } @@ -656,7 +671,7 @@ public void testJedisClusterTimeoutWithConfig() { @Test public void testJedisClusterRunsWithMultithreaded() throws InterruptedException, ExecutionException, IOException { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); final JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG); @@ -684,16 +699,21 @@ public String call() throws Exception { jc.close(); } - @Test(timeout = DEFAULT_TIMEOUT) + @Test(timeout = DEFAULT_TIMEOUT * 2) public void testReturnConnectionOnJedisConnectionException() throws InterruptedException { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisPoolConfig config = new JedisPoolConfig(); + ConnectionPoolConfig config = new ConnectionPoolConfig(); config.setMaxTotal(1); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config)) { - try (Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { +// try (Jedis j = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { +// ClientKillerUtil.tagClient(j, "DEAD"); +// ClientKillerUtil.killClient(j, "DEAD"); +// } + try (Connection c = jc.getClusterNodes().get("127.0.0.1:7380").getResource()) { + Jedis j = new Jedis(c); ClientKillerUtil.tagClient(j, "DEAD"); ClientKillerUtil.killClient(j, "DEAD"); } @@ -702,11 +722,11 @@ public void testReturnConnectionOnJedisConnectionException() throws InterruptedE } } - @Test(expected = JedisClusterMaxAttemptsException.class, timeout = DEFAULT_TIMEOUT) + @Test(expected = JedisClusterOperationException.class, timeout = DEFAULT_TIMEOUT) public void testReturnConnectionOnRedirection() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisPoolConfig config = new JedisPoolConfig(); + ConnectionPoolConfig config = new ConnectionPoolConfig(); config.setMaxTotal(1); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config)) { @@ -720,16 +740,17 @@ public void testReturnConnectionOnRedirection() { @Test public void testLocalhostNodeNotAddedWhen127Present() { HostAndPort localhost = new HostAndPort("localhost", 7379); - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); // cluster node is defined as 127.0.0.1; adding localhost should work, // but shouldn't show up. jedisClusterNode.add(localhost); - JedisPoolConfig config = new JedisPoolConfig(); + ConnectionPoolConfig config = new ConnectionPoolConfig(); config.setMaxTotal(1); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, - DEFAULT_REDIRECTIONS, "cluster", DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc.getClusterNodes(); + DEFAULT_REDIRECTIONS, "cluster", config)) { +// Map clusterNodes = jc.getClusterNodes(); + Map clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(localhost))); } @@ -741,11 +762,12 @@ public void testInvalidStartNodeNotAdded() { Set jedisClusterNode = new LinkedHashSet(); jedisClusterNode.add(invalidHost); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - JedisPoolConfig config = new JedisPoolConfig(); + ConnectionPoolConfig config = new ConnectionPoolConfig(); config.setMaxTotal(1); try (JedisCluster jc = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, DEFAULT_TIMEOUT, DEFAULT_REDIRECTIONS, "cluster", config)) { - Map clusterNodes = jc.getClusterNodes(); +// Map clusterNodes = jc.getClusterNodes(); + Map clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertFalse(clusterNodes.containsKey(JedisClusterInfoCache.getNodeKey(invalidHost))); } @@ -753,7 +775,7 @@ public void testInvalidStartNodeNotAdded() { @Test public void nullKeys() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(new HostAndPort(nodeInfo1.getHost(), nodeInfo1.getPort())); try (JedisCluster cluster = new JedisCluster(jedisClusterNode, DEFAULT_TIMEOUT, @@ -765,42 +787,48 @@ public void nullKeys() { try { cluster.exists((String) null); fail(); - } catch (JedisClusterOperationException coe) { +// } catch (JedisClusterOperationException coe) { + } catch (NullPointerException coe) { // expected } try { cluster.exists(foo, null); fail(); - } catch (JedisClusterOperationException coe) { +// } catch (JedisClusterOperationException coe) { + } catch (NullPointerException coe) { // expected } try { cluster.exists(null, foo); fail(); - } catch (JedisClusterOperationException coe) { +// } catch (JedisClusterOperationException coe) { + } catch (NullPointerException coe) { // expected } try { cluster.exists((byte[]) null); fail(); - } catch (JedisClusterOperationException coe) { +// } catch (JedisClusterOperationException coe) { + } catch (NullPointerException coe) { // expected } try { cluster.exists(bfoo, null); fail(); - } catch (JedisClusterOperationException coe) { +// } catch (JedisClusterOperationException coe) { + } catch (NullPointerException coe) { // expected } try { cluster.exists(null, bfoo); fail(); - } catch (JedisClusterOperationException coe) { +// } catch (JedisClusterOperationException coe) { + } catch (NullPointerException coe) { // expected } } @@ -809,7 +837,7 @@ public void nullKeys() { @Test public void clusterRefreshNodes() throws Exception { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(nodeInfo1); jedisClusterNode.add(nodeInfo2); jedisClusterNode.add(nodeInfo3); @@ -824,12 +852,12 @@ public void clusterRefreshNodes() throws Exception { node1.clusterMeet(LOCAL_IP, nodeInfo3.getPort()); node1.clusterMeet(LOCAL_IP, nodeInfo4.getPort()); // split available slots across the three nodes - int slotsPerNode = JedisCluster.HASHSLOTS / 4; + int slotsPerNode = CLUSTER_HASHSLOTS / 4; int[] node1Slots = new int[slotsPerNode]; int[] node2Slots = new int[slotsPerNode]; int[] node3Slots = new int[slotsPerNode]; int[] node4Slots = new int[slotsPerNode]; - for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0, slot4 = 0; i < JedisCluster.HASHSLOTS; i++) { + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0, slot4 = 0; i < CLUSTER_HASHSLOTS; i++) { if (i < slotsPerNode) { node1Slots[slot1++] = i; } else if (i >= slotsPerNode && i < slotsPerNode*2) { @@ -865,7 +893,7 @@ public void clusterRefreshNodes() throws Exception { @Test public void georadiusStore() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(nodeInfo1); jedisClusterNode.add(nodeInfo2); jedisClusterNode.add(nodeInfo3); @@ -883,7 +911,7 @@ public void georadiusStore() { GeoRadiusParam.geoRadiusParam(), GeoRadiusStoreParam.geoRadiusStoreParam().store("{Sicily}Store")); assertEquals(2, size); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("Palermo"); expected.add("Catania"); assertEquals(expected, cluster.zrange("{Sicily}Store", 0, -1)); @@ -892,7 +920,7 @@ public void georadiusStore() { @Test public void georadiusStoreBinary() { - Set jedisClusterNode = new HashSet(); + Set jedisClusterNode = new HashSet<>(); jedisClusterNode.add(nodeInfo1); jedisClusterNode.add(nodeInfo2); jedisClusterNode.add(nodeInfo3); @@ -910,10 +938,10 @@ public void georadiusStoreBinary() { GeoRadiusParam.geoRadiusParam(), GeoRadiusStoreParam.geoRadiusStoreParam().store("{Sicily}Store")); assertEquals(2, size); - Set bexpected = new LinkedHashSet(); - bexpected.add("Palermo".getBytes()); + List bexpected = new ArrayList(); bexpected.add("Palermo".getBytes()); - assertByteArraySetEquals(bexpected, cluster.zrange("{Sicily}Store".getBytes(), 0, -1)); + bexpected.add("Catania".getBytes()); + assertByteArrayListEquals(bexpected, cluster.zrange("{Sicily}Store".getBytes(), 0, -1)); } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java b/src/test/java/redis/clients/jedis/JedisPoolTest.java similarity index 94% rename from src/test/java/redis/clients/jedis/tests/JedisPoolTest.java rename to src/test/java/redis/clients/jedis/JedisPoolTest.java index 559b9c4003..89537df974 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisPoolTest.java +++ b/src/test/java/redis/clients/jedis/JedisPoolTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -15,20 +15,13 @@ import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.Test; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisFactory; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.InvalidURIException; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.exceptions.JedisExhaustedPoolException; public class JedisPoolTest { - private static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + private static final HostAndPort hnp = HostAndPorts.getRedisServers().get(0); @Test public void checkConnections() { @@ -44,7 +37,7 @@ public void checkConnections() { @Test public void checkResourceWithConfig() { - try (JedisPool pool = new JedisPool(HostAndPortUtil.getRedisServers().get(7), + try (JedisPool pool = new JedisPool(HostAndPorts.getRedisServers().get(7), DefaultJedisClientConfig.builder().socketTimeoutMillis(5000).build())) { try (Jedis jedis = pool.getResource()) { @@ -68,8 +61,8 @@ public void checkCloseableConnections() throws Exception { } @Test - public void checkConnectionWithDefaultPort() { - JedisPool pool = new JedisPool(new JedisPoolConfig(), hnp.getHost()); + public void checkConnectionWithDefaultHostAndPort() { + JedisPool pool = new JedisPool(new JedisPoolConfig()); try (Jedis jedis = pool.getResource()) { jedis.auth("foobared"); jedis.set("foo", "bar"); @@ -115,7 +108,7 @@ public void checkPoolRepairedWhenJedisIsBroken() { assertTrue(pool.isClosed()); } - @Test(expected = JedisExhaustedPoolException.class) + @Test(expected = JedisException.class) public void checkPoolOverflow() { GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); config.setMaxTotal(1); diff --git a/src/test/java/redis/clients/jedis/JedisPooledTest.java b/src/test/java/redis/clients/jedis/JedisPooledTest.java new file mode 100644 index 0000000000..92614a30fb --- /dev/null +++ b/src/test/java/redis/clients/jedis/JedisPooledTest.java @@ -0,0 +1,173 @@ +package redis.clients.jedis; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.net.URI; +import java.net.URISyntaxException; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.junit.Test; + +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisException; + +public class JedisPooledTest { + + private static final HostAndPort hnp = HostAndPorts.getRedisServers().get(7); + + @Test + public void checkCloseableConnections() { + JedisPooled pool = new JedisPooled(new ConnectionPoolConfig(), hnp.getHost(), hnp.getPort(), 2000); + pool.set("foo", "bar"); + assertEquals("bar", pool.get("foo")); + pool.close(); + assertTrue(pool.getPool().isClosed()); + } + + @Test + public void checkResourceWithConfig() { + try (JedisPooled pool = new JedisPooled(hnp, + DefaultJedisClientConfig.builder().socketTimeoutMillis(5000).build())) { + + try (Connection jedis = pool.getPool().getResource()) { + assertTrue(jedis.ping()); + assertEquals(5000, jedis.getSoTimeout()); + } + } + } + + @Test(expected = JedisException.class) + public void checkPoolOverflow() { + GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); + config.setMaxTotal(1); + config.setBlockWhenExhausted(false); + try (JedisPooled pool = new JedisPooled(hnp, config); + Connection jedis = pool.getPool().getResource()) { + + try (Connection jedis2 = pool.getPool().getResource()) { + } + } + } + + @Test + public void startWithUrlString() { + try (Jedis j = new Jedis("localhost", 6380)) { + j.auth("foobared"); + j.select(2); + j.set("foo", "bar"); + } + + try (JedisPooled pool = new JedisPooled("redis://:foobared@localhost:6380/2")) { + assertEquals("bar", pool.get("foo")); + } + } + + @Test + public void startWithUrl() throws URISyntaxException { + try (Jedis j = new Jedis("localhost", 6380)) { + j.auth("foobared"); + j.select(2); + j.set("foo", "bar"); + } + + try (JedisPooled pool = new JedisPooled(new URI("redis://:foobared@localhost:6380/2"))) { + assertEquals("bar", pool.get("foo")); + } + } + + @Test(expected = Exception.class) + public void shouldThrowExceptionForInvalidURI() throws URISyntaxException { + new JedisPooled(new URI("localhost:6380")).close(); + } + + @Test + public void allowUrlWithNoDBAndNoPassword() throws URISyntaxException { + new JedisPooled("redis://localhost:6380").close(); + new JedisPooled(new URI("redis://localhost:6380")).close(); + } + + @Test + public void customClientName() { + try (JedisPooled pool = new JedisPooled(hnp, DefaultJedisClientConfig.builder().clientName("my_shiny_client_name").build()); + Connection jedis = pool.getPool().getResource()) { + assertEquals("my_shiny_client_name", new Jedis(jedis).clientGetname()); + } + } + + @Test + public void getNumActiveWhenPoolIsClosed() { + JedisPooled pool = new JedisPooled(hnp); + + try (Connection j = pool.getPool().getResource()) { + j.ping(); + } + + pool.close(); + assertEquals(0, pool.getPool().getNumActive()); + } + + @Test + public void getNumActiveReturnsTheCorrectNumber() { + try (JedisPooled pool = new JedisPooled(new ConnectionPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + + Connection jedis = pool.getPool().getResource(); + assertEquals(1, pool.getPool().getNumActive()); + + Connection jedis2 = pool.getPool().getResource(); + assertEquals(2, pool.getPool().getNumActive()); + + jedis.close(); + assertEquals(1, pool.getPool().getNumActive()); + + jedis2.close(); + assertEquals(0, pool.getPool().getNumActive()); + } + } + + @Test + public void closeResourceTwice() { + try (JedisPooled pool = new JedisPooled(new ConnectionPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + Connection j = pool.getPool().getResource(); + j.ping(); + j.close(); + j.close(); + } + } + + @Test + public void closeBrokenResourceTwice() { + try (JedisPooled pool = new JedisPooled(new ConnectionPoolConfig(), hnp.getHost(), hnp.getPort(), 2000)) { + Connection j = pool.getPool().getResource(); + try { + // make connection broken + j.getOne(); + fail(); + } catch (Exception e) { + assertTrue(e instanceof JedisConnectionException); + } + assertTrue(j.isBroken()); + j.close(); + j.close(); + } + } + + @Test + public void testResetValidPassword() { + ConnectionFactory factory = new ConnectionFactory(HostAndPorts.getRedisServers().get(0), + DefaultJedisClientConfig.builder().password("bad password") + .clientName("my_shiny_client_name").build()); + + try (JedisPooled pool = new JedisPooled(new ConnectionPoolConfig(), factory)) { + try { + pool.get("foo"); + fail("Should not get resource from pool"); + } catch (JedisException e) { } + assertEquals(0, pool.getPool().getNumActive()); + + factory.setPassword("foobared"); + pool.set("foo", "bar"); + assertEquals("bar", pool.get("foo")); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/JedisSentinelPoolTest.java similarity index 86% rename from src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java rename to src/test/java/redis/clients/jedis/JedisSentinelPoolTest.java index 51504bef06..88ca94600c 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/JedisSentinelPoolTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -7,37 +7,28 @@ import java.util.HashSet; import java.util.Set; -import java.util.concurrent.atomic.AtomicInteger; -import org.apache.commons.pool2.PooledObject; -import org.apache.commons.pool2.PooledObjectFactory; -import org.apache.commons.pool2.impl.DefaultPooledObject; import org.apache.commons.pool2.impl.GenericObjectPoolConfig; import org.junit.After; import org.junit.Before; import org.junit.Test; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisFactory; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.JedisSentinelPool; -import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.tests.utils.JedisSentinelTestUtil; +import redis.clients.jedis.util.JedisSentinelTestUtil; public class JedisSentinelPoolTest { + private static final String MASTER_NAME = "mymaster"; - protected static HostAndPort master = HostAndPortUtil.getRedisServers().get(2); - protected static HostAndPort slave1 = HostAndPortUtil.getRedisServers().get(3); + protected static HostAndPort master = HostAndPorts.getRedisServers().get(2); + protected static HostAndPort slave1 = HostAndPorts.getRedisServers().get(3); - protected static HostAndPort sentinel1 = HostAndPortUtil.getSentinelServers().get(1); - protected static HostAndPort sentinel2 = HostAndPortUtil.getSentinelServers().get(3); + protected static HostAndPort sentinel1 = HostAndPorts.getSentinelServers().get(1); + protected static HostAndPort sentinel2 = HostAndPorts.getSentinelServers().get(3); - protected static Jedis sentinelJedis1; - protected static Jedis sentinelJedis2; + protected static Sentinel sentinelJedis1; + protected static Sentinel sentinelJedis2; protected Set sentinels = new HashSet(); @@ -46,8 +37,8 @@ public void setUp() throws Exception { sentinels.add(sentinel1.toString()); sentinels.add(sentinel2.toString()); - sentinelJedis1 = new Jedis(sentinel1); - sentinelJedis2 = new Jedis(sentinel2); + sentinelJedis1 = new Sentinel(sentinel1); + sentinelJedis2 = new Sentinel(sentinel2); } @After @@ -253,8 +244,7 @@ private void waitForJedisSentinelPoolRecognizeNewMaster(JedisSentinelPool pool, if (newMaster.equals(currentHostMaster)) break; - System.out.println("JedisSentinelPool's master is not yet changed, sleep..."); - + // System.out.println("JedisSentinelPool's master is not yet changed, sleep..."); Thread.sleep(100); } } diff --git a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java b/src/test/java/redis/clients/jedis/JedisSentinelTest.java similarity index 85% rename from src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java rename to src/test/java/redis/clients/jedis/JedisSentinelTest.java index 951f0d34a9..ec9fe6c852 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisSentinelTest.java +++ b/src/test/java/redis/clients/jedis/JedisSentinelTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -13,24 +13,23 @@ import org.junit.Before; import org.junit.Test; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.tests.utils.JedisSentinelTestUtil; +import redis.clients.jedis.util.JedisSentinelTestUtil; public class JedisSentinelTest { + private static final String MASTER_NAME = "mymaster"; private static final String MONITOR_MASTER_NAME = "mymastermonitor"; private static final String REMOVE_MASTER_NAME = "mymasterremove"; private static final String FAILOVER_MASTER_NAME = "mymasterfailover"; private static final String MASTER_IP = "127.0.0.1"; - protected static HostAndPort master = HostAndPortUtil.getRedisServers().get(0); - protected static HostAndPort slave = HostAndPortUtil.getRedisServers().get(4); - protected static HostAndPort sentinel = HostAndPortUtil.getSentinelServers().get(0); + protected static HostAndPort master = HostAndPorts.getRedisServers().get(0); + protected static HostAndPort slave = HostAndPorts.getRedisServers().get(4); + protected static HostAndPort sentinel = HostAndPorts.getSentinelServers().get(0); - protected static HostAndPort sentinelForFailover = HostAndPortUtil.getSentinelServers().get(2); - protected static HostAndPort masterForFailover = HostAndPortUtil.getRedisServers().get(5); + protected static HostAndPort sentinelForFailover = HostAndPorts.getSentinelServers().get(2); + protected static HostAndPort masterForFailover = HostAndPorts.getRedisServers().get(5); @Before public void setup() throws InterruptedException { @@ -49,7 +48,7 @@ public void clear() throws InterruptedException { @Test public void sentinel() { - Jedis j = new Jedis(sentinel); + Sentinel j = new Sentinel(sentinel); try { List> masters = j.sentinelMasters(); @@ -63,7 +62,8 @@ public void sentinel() { List masterHostAndPort = j.sentinelGetMasterAddrByName(MASTER_NAME); HostAndPort masterFromSentinel = new HostAndPort(masterHostAndPort.get(0), Integer.parseInt(masterHostAndPort.get(1))); - assertEquals(master, masterFromSentinel); +// assertEquals(master, masterFromSentinel); + assertEquals(master.getPort(), masterFromSentinel.getPort()); List> slaves = j.sentinelReplicas(MASTER_NAME); assertTrue(!slaves.isEmpty()); @@ -79,8 +79,8 @@ public void sentinel() { @Test public void sentinelFailover() throws InterruptedException { - Jedis j = new Jedis(sentinelForFailover); - Jedis j2 = new Jedis(sentinelForFailover); + Sentinel j = new Sentinel(sentinelForFailover); + Sentinel j2 = new Sentinel(sentinelForFailover); try { List masterHostAndPort = j.sentinelGetMasterAddrByName(FAILOVER_MASTER_NAME); @@ -98,12 +98,11 @@ public void sentinelFailover() throws InterruptedException { j.close(); j2.close(); } - } @Test public void sentinelMonitor() { - Jedis j = new Jedis(sentinel); + Sentinel j = new Sentinel(sentinel); try { // monitor new master @@ -124,7 +123,7 @@ public void sentinelMonitor() { @Test public void sentinelRemove() { - Jedis j = new Jedis(sentinel); + Sentinel j = new Sentinel(sentinel); try { ensureMonitored(sentinel, REMOVE_MASTER_NAME, MASTER_IP, master.getPort(), 1); @@ -147,7 +146,7 @@ public void sentinelRemove() { @Test public void sentinelSet() { - Jedis j = new Jedis(sentinel); + Sentinel j = new Sentinel(sentinel); try { Map parameterMap = new HashMap(); @@ -174,7 +173,7 @@ public void sentinelSet() { private void ensureMonitored(HostAndPort sentinel, String masterName, String ip, int port, int quorum) { - Jedis j = new Jedis(sentinel); + Sentinel j = new Sentinel(sentinel); try { j.sentinelMonitor(masterName, ip, port, quorum); } catch (JedisDataException e) { @@ -184,7 +183,7 @@ private void ensureMonitored(HostAndPort sentinel, String masterName, String ip, } private void ensureRemoved(String masterName) { - Jedis j = new Jedis(sentinel); + Sentinel j = new Sentinel(sentinel); try { j.sentinelRemove(masterName); } catch (JedisDataException e) { diff --git a/src/test/java/redis/clients/jedis/tests/JedisTest.java b/src/test/java/redis/clients/jedis/JedisTest.java similarity index 82% rename from src/test/java/redis/clients/jedis/tests/JedisTest.java rename to src/test/java/redis/clients/jedis/JedisTest.java index c40b7ce709..d2344967b7 100644 --- a/src/test/java/redis/clients/jedis/tests/JedisTest.java +++ b/src/test/java/redis/clients/jedis/JedisTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -18,19 +18,13 @@ import org.junit.Test; -import redis.clients.jedis.BinaryJedis; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisClientConfig; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.Protocol; import redis.clients.jedis.exceptions.InvalidURIException; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.tests.commands.JedisCommandTestBase; +import redis.clients.jedis.commands.jedis.JedisCommandsTestBase; import redis.clients.jedis.util.SafeEncoder; -public class JedisTest extends JedisCommandTestBase { +public class JedisTest extends JedisCommandsTestBase { @Test public void useWithoutConnecting() { @@ -53,15 +47,6 @@ public void checkBinaryData() { assertEquals(hash, jedis.hgetAll("foo")); } - @Test - public void connectWithShardInfo() { - JedisShardInfo shardInfo = new JedisShardInfo("localhost", Protocol.DEFAULT_PORT); - shardInfo.setPassword("foobared"); - try (Jedis jedis = new Jedis(shardInfo)) { - jedis.get("foo"); - } - } - @Test public void connectWithConfig() { try (Jedis jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().build())) { @@ -137,15 +122,15 @@ public void failWhenSendingNullValues() { public void shouldThrowInvalidURIExceptionForInvalidURI() throws URISyntaxException { Jedis j = new Jedis(new URI("localhost:6380")); } - - @Test - public void shouldReconnectToSameDB() throws IOException { - jedis.select(1); - jedis.set("foo", "bar"); - jedis.getClient().getSocket().shutdownInput(); - jedis.getClient().getSocket().shutdownOutput(); - assertEquals("bar", jedis.get("foo")); - } +// +// @Test +// public void shouldReconnectToSameDB() throws IOException { +// jedis.select(1); +// jedis.set("foo", "bar"); +// jedis.getClient().getSocket().shutdownInput(); +// jedis.getClient().getSocket().shutdownOutput(); +// assertEquals("bar", jedis.get("foo")); +// } @Test public void startWithUrl() { @@ -192,15 +177,15 @@ public void shouldNotUpdateDbIndexIfSelectFails() { public void allowUrlWithNoDBAndNoPassword() { try (Jedis j1 = new Jedis("redis://localhost:6380")) { j1.auth("foobared"); - assertEquals("localhost", j1.getClient().getHost()); - assertEquals(6380, j1.getClient().getPort()); +// assertEquals("localhost", j1.getClient().getHost()); +// assertEquals(6380, j1.getClient().getPort()); assertEquals(0, j1.getDB()); } try (Jedis j2 = new Jedis("redis://localhost:6380/")) { j2.auth("foobared"); - assertEquals("localhost", j2.getClient().getHost()); - assertEquals(6380, j2.getClient().getPort()); +// assertEquals("localhost", j2.getClient().getHost()); +// assertEquals(6380, j2.getClient().getPort()); assertEquals(0, j2.getDB()); } } @@ -224,20 +209,20 @@ public void uriWithDBindexShouldUseTimeout() throws URISyntaxException, IOExcept @Test public void checkCloseable() { - BinaryJedis bj = new BinaryJedis(); + Jedis bj = new Jedis(); bj.close(); } @Test public void checkCloseableAfterConnect() { - BinaryJedis bj = new BinaryJedis(); + Jedis bj = new Jedis(); bj.connect(); bj.close(); } @Test public void checkCloseableAfterCommand() { - BinaryJedis bj = new BinaryJedis(); + Jedis bj = new Jedis(); bj.auth("foobared"); bj.close(); } diff --git a/src/test/java/redis/clients/jedis/ManagedConnectionProviderTest.java b/src/test/java/redis/clients/jedis/ManagedConnectionProviderTest.java new file mode 100644 index 0000000000..84bca8d1fa --- /dev/null +++ b/src/test/java/redis/clients/jedis/ManagedConnectionProviderTest.java @@ -0,0 +1,38 @@ +package redis.clients.jedis; + +import org.junit.After; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.providers.ManagedConnectionProvider; +import redis.clients.jedis.util.IOUtils; + +public class ManagedConnectionProviderTest { + + private Connection connection; + + @Before + public void setUp() { + connection = new Connection(HostAndPorts.getRedisServers().get(0), + DefaultJedisClientConfig.builder().user("acljedis").password("fizzbuzz").build()); + } + + @After + public void tearDown() { + IOUtils.closeQuietly(connection); + } + + @Test + public void test() { + ManagedConnectionProvider managed = new ManagedConnectionProvider(); + try (UnifiedJedis jedis = new UnifiedJedis(managed)) { + try { + jedis.get("any"); + Assert.fail("Should get NPE."); + } catch (NullPointerException npe) { } + managed.setConnection(connection); + Assert.assertNull(jedis.get("any")); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/ModuleTest.java b/src/test/java/redis/clients/jedis/ModuleTest.java similarity index 83% rename from src/test/java/redis/clients/jedis/tests/ModuleTest.java rename to src/test/java/redis/clients/jedis/ModuleTest.java index 7195faeb1f..3cd9901027 100644 --- a/src/test/java/redis/clients/jedis/tests/ModuleTest.java +++ b/src/test/java/redis/clients/jedis/ModuleTest.java @@ -1,18 +1,16 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.List; - import org.junit.Test; -import redis.clients.jedis.Module; import redis.clients.jedis.commands.ProtocolCommand; -import redis.clients.jedis.tests.commands.JedisCommandTestBase; +import redis.clients.jedis.commands.jedis.JedisCommandsTestBase; import redis.clients.jedis.util.SafeEncoder; -public class ModuleTest extends JedisCommandTestBase { +public class ModuleTest extends JedisCommandsTestBase { static enum ModuleCommand implements ProtocolCommand { SIMPLE("testmodule.simple"); diff --git a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java b/src/test/java/redis/clients/jedis/PipeliningTest.java similarity index 55% rename from src/test/java/redis/clients/jedis/tests/PipeliningTest.java rename to src/test/java/redis/clients/jedis/PipeliningTest.java index 1f535279f5..acadd25857 100644 --- a/src/test/java/redis/clients/jedis/tests/PipeliningTest.java +++ b/src/test/java/redis/clients/jedis/PipeliningTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertArrayEquals; @@ -6,15 +6,12 @@ import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.IOException; -import java.util.ArrayList; import java.util.Arrays; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; @@ -25,17 +22,12 @@ import org.hamcrest.Matcher; import org.junit.Test; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.Pipeline; -import redis.clients.jedis.Response; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.exceptions.AbortedTransactionException; -import redis.clients.jedis.exceptions.JedisBusyException; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.tests.commands.JedisCommandTestBase; +import redis.clients.jedis.resps.Tuple; +import redis.clients.jedis.commands.jedis.JedisCommandsTestBase; import redis.clients.jedis.util.SafeEncoder; -public class PipeliningTest extends JedisCommandTestBase { +public class PipeliningTest extends JedisCommandsTestBase { @Test public void pipeline() { @@ -64,7 +56,7 @@ public void pipelineResponse() { Response string = p.get("string"); Response list = p.lpop("list"); Response hash = p.hget("hash", "foo"); - Response> zset = p.zrange("zset", 0, -1); + Response> zset = p.zrange("zset", 0, -1); Response set = p.spop("set"); Response blist = p.exists("list"); Response zincrby = p.zincrby("zset", 1, "foo"); @@ -74,7 +66,7 @@ public void pipelineResponse() { Response> hgetAll = p.hgetAll("hash"); p.sadd("set", "foo"); Response> smembers = p.smembers("set"); - Response> zrangeWithScores = p.zrangeWithScores("zset", 0, -1); + Response> zrangeWithScores = p.zrangeWithScores("zset", 0, -1); Response getrange = p.getrange("setrange", 1, 3); Response getrangeBytes = p.getrange("setrangebytes".getBytes(), 6, 8); p.sync(); @@ -161,13 +153,13 @@ private void verifyHasBothValues(byte[] firstKey, byte[] secondKey, byte[] value assertTrue(Arrays.equals(firstKey, value1) || Arrays.equals(firstKey, value2)); assertTrue(Arrays.equals(secondKey, value1) || Arrays.equals(secondKey, value2)); } - - @Test - public void pipelineSelect() { - Pipeline p = jedis.pipelined(); - p.select(1); - p.sync(); - } +// +// @Test +// public void pipelineSelect() { +// Pipeline p = jedis.pipelined(); +// p.select(1); +// p.sync(); +// } @Test public void pipelineResponseWithoutData() { @@ -223,150 +215,150 @@ public void piplineWithError() { } assertEquals(r.get(), "bar"); } - - @Test - public void multi() { - Pipeline p = jedis.pipelined(); - p.multi(); - Response r1 = p.hincrBy("a", "f1", -1); - Response r2 = p.hincrBy("a", "f1", -2); - Response> r3 = p.exec(); - List result = p.syncAndReturnAll(); - - assertEquals(new Long(-1), r1.get()); - assertEquals(new Long(-3), r2.get()); - - assertEquals(4, result.size()); - - assertEquals("OK", result.get(0)); - assertEquals("QUEUED", result.get(1)); - assertEquals("QUEUED", result.get(2)); - - // 4th result is a list with the results from the multi - @SuppressWarnings("unchecked") - List multiResult = (List) result.get(3); - assertEquals(new Long(-1), multiResult.get(0)); - assertEquals(new Long(-3), multiResult.get(1)); - - assertEquals(new Long(-1), r3.get().get(0)); - assertEquals(new Long(-3), r3.get().get(1)); - - } - - @Test - public void multiWithMassiveRequests() { - Pipeline p = jedis.pipelined(); - p.multi(); - - List> responseList = new ArrayList>(); - for (int i = 0; i < 100000; i++) { - // any operation should be ok, but shouldn't forget about timeout - responseList.add(p.setbit("test", 1, true)); - } - - Response> exec = p.exec(); - p.sync(); - - // we don't need to check return value - // if below codes run without throwing Exception, we're ok - exec.get(); - - for (Response resp : responseList) { - resp.get(); - } - } - - @Test - public void multiWithSync() { - jedis.set("foo", "314"); - jedis.set("bar", "foo"); - jedis.set("hello", "world"); - Pipeline p = jedis.pipelined(); - Response r1 = p.get("bar"); - p.multi(); - Response r2 = p.get("foo"); - p.exec(); - Response r3 = p.get("hello"); - p.sync(); - - // before multi - assertEquals("foo", r1.get()); - // It should be readable whether exec's response was built or not - assertEquals("314", r2.get()); - // after multi - assertEquals("world", r3.get()); - } - - @Test - public void multiWatch() { - final String key = "foo"; - assertEquals(5L, jedis.incrBy(key, 5L)); - - List expect = new ArrayList<>(); - List expMulti = null; // MULTI will fail - - Pipeline pipe = jedis.pipelined(); - pipe.watch(key); expect.add("OK"); - pipe.incrBy(key, 3L); expect.add(8L); - pipe.multi(); expect.add("OK"); - pipe.incrBy(key, 6L); expect.add("QUEUED"); - assertEquals(expect, pipe.syncAndReturnAll()); expect.clear(); - - try (Jedis tweak = createJedis()) { - assertEquals(10L, tweak.incrBy(key, 2L)); - } - - pipe.incrBy(key, 4L); expect.add("QUEUED"); - pipe.exec(); expect.add(expMulti); // failed MULTI - pipe.incrBy(key, 7L); expect.add(17L); - assertEquals(expect, pipe.syncAndReturnAll()); - } - - @Test - public void multiUnwatch() { - final String key = "foo"; - assertEquals(5L, jedis.incrBy(key, 5L)); - - List expect = new ArrayList<>(); - List expMulti = new ArrayList<>(); - - Pipeline pipe = jedis.pipelined(); - pipe.watch(key); expect.add("OK"); - pipe.incrBy(key, 3L); expect.add(8L); - pipe.unwatch(); expect.add("OK"); - pipe.multi(); expect.add("OK"); - pipe.incrBy(key, 6L); expect.add("QUEUED"); expMulti.add(16L); - assertEquals(expect, pipe.syncAndReturnAll()); expect.clear(); - - try (Jedis tweak = createJedis()) { - assertEquals(10L, tweak.incrBy(key, 2L)); - } - - pipe.incrBy(key, 4L); expect.add("QUEUED"); expMulti.add(20L); - pipe.exec(); expect.add(expMulti); // successful MULTI - pipe.incrBy(key, 7L); expect.add(27L); - assertEquals(expect, pipe.syncAndReturnAll()); - } - - @Test(expected = IllegalStateException.class) - public void pipelineExecWhenNotInMulti() { - Pipeline pipeline = jedis.pipelined(); - pipeline.exec(); - } - - @Test(expected = IllegalStateException.class) - public void pipelineDiscardWhenNotInMulti() { - Pipeline pipeline = jedis.pipelined(); - pipeline.discard(); - } - - @Test(expected = IllegalStateException.class) - public void pipelineMultiWhenAlreadyInMulti() { - Pipeline pipeline = jedis.pipelined(); - pipeline.multi(); - pipeline.set("foo", "3"); - pipeline.multi(); - } +// +// @Test +// public void multi() { +// Pipeline p = jedis.pipelined(); +// p.multi(); +// Response r1 = p.hincrBy("a", "f1", -1); +// Response r2 = p.hincrBy("a", "f1", -2); +// Response> r3 = p.exec(); +// List result = p.syncAndReturnAll(); +// +// assertEquals(new Long(-1), r1.get()); +// assertEquals(new Long(-3), r2.get()); +// +// assertEquals(4, result.size()); +// +// assertEquals("OK", result.get(0)); +// assertEquals("QUEUED", result.get(1)); +// assertEquals("QUEUED", result.get(2)); +// +// // 4th result is a list with the results from the multi +// @SuppressWarnings("unchecked") +// List multiResult = (List) result.get(3); +// assertEquals(new Long(-1), multiResult.get(0)); +// assertEquals(new Long(-3), multiResult.get(1)); +// +// assertEquals(new Long(-1), r3.get().get(0)); +// assertEquals(new Long(-3), r3.get().get(1)); +// +// } +// +// @Test +// public void multiWithMassiveRequests() { +// Pipeline p = jedis.pipelined(); +// p.multi(); +// +// List> responseList = new ArrayList>(); +// for (int i = 0; i < 100000; i++) { +// // any operation should be ok, but shouldn't forget about timeout +// responseList.add(p.setbit("test", 1, true)); +// } +// +// Response> exec = p.exec(); +// p.sync(); +// +// // we don't need to check return value +// // if below codes run without throwing Exception, we're ok +// exec.get(); +// +// for (Response resp : responseList) { +// resp.get(); +// } +// } +// +// @Test +// public void multiWithSync() { +// jedis.set("foo", "314"); +// jedis.set("bar", "foo"); +// jedis.set("hello", "world"); +// Pipeline p = jedis.pipelined(); +// Response r1 = p.get("bar"); +// p.multi(); +// Response r2 = p.get("foo"); +// p.exec(); +// Response r3 = p.get("hello"); +// p.sync(); +// +// // before multi +// assertEquals("foo", r1.get()); +// // It should be readable whether exec's response was built or not +// assertEquals("314", r2.get()); +// // after multi +// assertEquals("world", r3.get()); +// } +// +// @Test +// public void multiWatch() { +// final String key = "foo"; +// assertEquals(5L, jedis.incrBy(key, 5L)); +// +// List expect = new ArrayList<>(); +// List expMulti = null; // MULTI will fail +// +// Pipeline pipe = jedis.pipelined(); +// pipe.watch(key); expect.add("OK"); +// pipe.incrBy(key, 3L); expect.add(8L); +// pipe.multi(); expect.add("OK"); +// pipe.incrBy(key, 6L); expect.add("QUEUED"); +// assertEquals(expect, pipe.syncAndReturnAll()); expect.clear(); +// +// try (Jedis tweak = createJedis()) { +// assertEquals(10L, tweak.incrBy(key, 2L)); +// } +// +// pipe.incrBy(key, 4L); expect.add("QUEUED"); +// pipe.exec(); expect.add(expMulti); // failed MULTI +// pipe.incrBy(key, 7L); expect.add(17L); +// assertEquals(expect, pipe.syncAndReturnAll()); +// } +// +// @Test +// public void multiUnwatch() { +// final String key = "foo"; +// assertEquals(5L, jedis.incrBy(key, 5L)); +// +// List expect = new ArrayList<>(); +// List expMulti = new ArrayList<>(); +// +// Pipeline pipe = jedis.pipelined(); +// pipe.watch(key); expect.add("OK"); +// pipe.incrBy(key, 3L); expect.add(8L); +// pipe.unwatch(); expect.add("OK"); +// pipe.multi(); expect.add("OK"); +// pipe.incrBy(key, 6L); expect.add("QUEUED"); expMulti.add(16L); +// assertEquals(expect, pipe.syncAndReturnAll()); expect.clear(); +// +// try (Jedis tweak = createJedis()) { +// assertEquals(10L, tweak.incrBy(key, 2L)); +// } +// +// pipe.incrBy(key, 4L); expect.add("QUEUED"); expMulti.add(20L); +// pipe.exec(); expect.add(expMulti); // successful MULTI +// pipe.incrBy(key, 7L); expect.add(27L); +// assertEquals(expect, pipe.syncAndReturnAll()); +// } +// +// @Test(expected = IllegalStateException.class) +// public void pipelineExecWhenNotInMulti() { +// Pipeline pipeline = jedis.pipelined(); +// pipeline.exec(); +// } +// +// @Test(expected = IllegalStateException.class) +// public void pipelineDiscardWhenNotInMulti() { +// Pipeline pipeline = jedis.pipelined(); +// pipeline.discard(); +// } +// +// @Test(expected = IllegalStateException.class) +// public void pipelineMultiWhenAlreadyInMulti() { +// Pipeline pipeline = jedis.pipelined(); +// pipeline.multi(); +// pipeline.set("foo", "3"); +// pipeline.multi(); +// } @Test(expected = IllegalStateException.class) public void testJedisThrowExceptionWhenInPipeline() { @@ -393,18 +385,18 @@ public void testResetStateWhenInPipeline() { String result = jedis.get("foo"); assertEquals(result, "3"); } - - @Test - public void testDiscardInPipeline() { - Pipeline pipeline = jedis.pipelined(); - pipeline.multi(); - pipeline.set("foo", "bar"); - Response discard = pipeline.discard(); - Response get = pipeline.get("foo"); - pipeline.sync(); - discard.get(); - get.get(); - } +// +// @Test +// public void testDiscardInPipeline() { +// Pipeline pipeline = jedis.pipelined(); +// pipeline.multi(); +// pipeline.set("foo", "bar"); +// Response discard = pipeline.discard(); +// Response get = pipeline.get("foo"); +// pipeline.sync(); +// discard.get(); +// get.get(); +// } @Test public void waitReplicas() { @@ -413,7 +405,7 @@ public void waitReplicas() { p.waitReplicas(1, 10); p.sync(); - try (Jedis j = new Jedis(HostAndPortUtil.getRedisServers().get(4))) { + try (Jedis j = new Jedis(HostAndPorts.getRedisServers().get(4))) { j.auth("foobared"); assertEquals("replicas", j.get("wait")); } @@ -552,7 +544,7 @@ public void testEvalshaKeyAndArgWithBinary() { byte[] bScript = SafeEncoder.encode(script); byte[] bSha1 = jedis.scriptLoad(bScript); - assertTrue(jedis.scriptExists(bSha1) == 1); + assertTrue(jedis.scriptExists(bSha1)); Pipeline p = jedis.pipelined(); p.set(bKey, SafeEncoder.encode("0")); @@ -566,72 +558,72 @@ public void testEvalshaKeyAndArgWithBinary() { assertNull(result1.get()); assertArrayEquals(SafeEncoder.encode("13"), result2.get()); } - - @Test - public void testPipelinedTransactionResponse() { - - String key1 = "key1"; - String val1 = "val1"; - - String key2 = "key2"; - String val2 = "val2"; - - String key3 = "key3"; - String field1 = "field1"; - String field2 = "field2"; - String field3 = "field3"; - String field4 = "field4"; - - String value1 = "value1"; - String value2 = "value2"; - String value3 = "value3"; - String value4 = "value4"; - - Map hashMap = new HashMap(); - hashMap.put(field1, value1); - hashMap.put(field2, value2); - - String key4 = "key4"; - Map hashMap1 = new HashMap(); - hashMap1.put(field3, value3); - hashMap1.put(field4, value4); - - jedis.set(key1, val1); - jedis.set(key2, val2); - jedis.hmset(key3, hashMap); - jedis.hmset(key4, hashMap1); - - Pipeline pipeline = jedis.pipelined(); - pipeline.multi(); - - pipeline.get(key1); - pipeline.hgetAll(key2); - pipeline.hgetAll(key3); - pipeline.get(key4); - - Response> response = pipeline.exec(); - pipeline.sync(); - - List result = response.get(); - - assertEquals(4, result.size()); - - assertEquals("val1", result.get(0)); - - assertTrue(result.get(1) instanceof JedisDataException); - - Map hashMapReceived = (Map) result.get(2); - Iterator iterator = hashMapReceived.keySet().iterator(); - String mapKey1 = iterator.next(); - String mapKey2 = iterator.next(); - assertFalse(iterator.hasNext()); - verifyHasBothValues(mapKey1, mapKey2, field1, field2); - String mapValue1 = hashMapReceived.get(mapKey1); - String mapValue2 = hashMapReceived.get(mapKey2); - verifyHasBothValues(mapValue1, mapValue2, value1, value2); - - assertTrue(result.get(3) instanceof JedisDataException); - } +// +// @Test +// public void testPipelinedTransactionResponse() { +// +// String key1 = "key1"; +// String val1 = "val1"; +// +// String key2 = "key2"; +// String val2 = "val2"; +// +// String key3 = "key3"; +// String field1 = "field1"; +// String field2 = "field2"; +// String field3 = "field3"; +// String field4 = "field4"; +// +// String value1 = "value1"; +// String value2 = "value2"; +// String value3 = "value3"; +// String value4 = "value4"; +// +// Map hashMap = new HashMap(); +// hashMap.put(field1, value1); +// hashMap.put(field2, value2); +// +// String key4 = "key4"; +// Map hashMap1 = new HashMap(); +// hashMap1.put(field3, value3); +// hashMap1.put(field4, value4); +// +// jedis.set(key1, val1); +// jedis.set(key2, val2); +// jedis.hmset(key3, hashMap); +// jedis.hmset(key4, hashMap1); +// +// Pipeline pipeline = jedis.pipelined(); +// pipeline.multi(); +// +// pipeline.get(key1); +// pipeline.hgetAll(key2); +// pipeline.hgetAll(key3); +// pipeline.get(key4); +// +// Response> response = pipeline.exec(); +// pipeline.sync(); +// +// List result = response.get(); +// +// assertEquals(4, result.size()); +// +// assertEquals("val1", result.get(0)); +// +// assertTrue(result.get(1) instanceof JedisDataException); +// +// Map hashMapReceived = (Map) result.get(2); +// Iterator iterator = hashMapReceived.keySet().iterator(); +// String mapKey1 = iterator.next(); +// String mapKey2 = iterator.next(); +// assertFalse(iterator.hasNext()); +// verifyHasBothValues(mapKey1, mapKey2, field1, field2); +// String mapValue1 = hashMapReceived.get(mapKey1); +// String mapValue2 = hashMapReceived.get(mapKey2); +// verifyHasBothValues(mapValue1, mapValue2, value1, value2); +// +// assertTrue(result.get(3) instanceof JedisDataException); +// } @Test public void testSyncWithNoCommandQueued() { @@ -669,113 +661,113 @@ public void testCloseable() throws IOException { retFuture2.get(); jedis2.close(); } - - @Test - public void testCloseableWithMulti() throws IOException { - // we need to test with fresh instance of Jedis - Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); - jedis2.auth("foobared"); - - Pipeline pipeline = jedis2.pipelined(); - Response retFuture1 = pipeline.set("a", "1"); - Response retFuture2 = pipeline.set("b", "2"); - - pipeline.multi(); - - pipeline.set("a", "a"); - pipeline.set("b", "b"); - - pipeline.close(); - - try { - pipeline.exec(); - fail("close should discard transaction"); - } catch (IllegalStateException e) { - assertTrue(e.getMessage().contains("EXEC without MULTI")); - // pass - } - - // it shouldn't meet any exception - retFuture1.get(); - retFuture2.get(); - jedis2.close(); - } - - @Test - public void execAbort() { - final String luaTimeLimitKey = "lua-time-limit"; - final String luaTimeLimit = jedis.configGet(luaTimeLimitKey).get(1); - jedis.configSet(luaTimeLimitKey, "10"); - - Thread thread = new Thread(() -> { - try (Jedis blocker = createJedis()) { - blocker.eval("while true do end"); - } catch (Exception ex) { - // swallow any exception - } - }); - - Pipeline pipe = jedis.pipelined(); - pipe.incr("foo"); - pipe.multi(); - pipe.incr("foo"); - pipe.sync(); - - thread.start(); - try { - Thread.sleep(12); // allow Redis to be busy with the script and 'lua-time-limit' to exceed - } catch (InterruptedException ex) { } - - pipe.incr("foo"); - Response> txResp = pipe.exec(); - pipe.sync(); - try { - txResp.get(); - } catch (Exception ex) { - assertSame(AbortedTransactionException.class, ex.getClass()); - } finally { - try { - String status = jedis.scriptKill(); - // https://github.com/redis/jedis/issues/2656 - if ("OK".equalsIgnoreCase(status)) { - scriptKillWait(); - } else { - // #2656: Checking if this status is actually 'OK' when error occurs in next command. - org.apache.logging.log4j.LogManager.getLogger().error( - String.format("Status if SCRIPT KILL command is \"%s\"", status)); - } - } finally { - jedis.configSet(luaTimeLimitKey, luaTimeLimit); - } - } - } - - private void scriptKillWait() { - int attemptLeft = 10; - while (attemptLeft > 0) { - try (Jedis pingJedis = createJedis()) { - while (attemptLeft > 0) { - try { - pingJedis.ping(); - return; // wait is over - } catch (JedisBusyException busy) { - Thread.sleep(10); // BUSY, waiting for some time - --attemptLeft; // doing this later; otherwise any exception in Thread.sleep() - // would cause decrement twice for the same turn. - } - } - } catch (Exception any) { - --attemptLeft; - // try new connection - } - } - } - - private void verifyHasBothValues(String firstKey, String secondKey, String value1, String value2) { - assertFalse(firstKey.equals(secondKey)); - assertTrue(firstKey.equals(value1) || firstKey.equals(value2)); - assertTrue(secondKey.equals(value1) || secondKey.equals(value2)); - } +// +// @Test +// public void testCloseableWithMulti() throws IOException { +// // we need to test with fresh instance of Jedis +// Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); +// jedis2.auth("foobared"); +// +// Pipeline pipeline = jedis2.pipelined(); +// Response retFuture1 = pipeline.set("a", "1"); +// Response retFuture2 = pipeline.set("b", "2"); +// +// pipeline.multi(); +// +// pipeline.set("a", "a"); +// pipeline.set("b", "b"); +// +// pipeline.close(); +// +// try { +// pipeline.exec(); +// fail("close should discard transaction"); +// } catch (IllegalStateException e) { +// assertTrue(e.getMessage().contains("EXEC without MULTI")); +// // pass +// } +// +// // it shouldn't meet any exception +// retFuture1.get(); +// retFuture2.get(); +// jedis2.close(); +// } +// +// @Test +// public void execAbort() { +// final String luaTimeLimitKey = "lua-time-limit"; +// final String luaTimeLimit = jedis.configGet(luaTimeLimitKey).get(1); +// jedis.configSet(luaTimeLimitKey, "10"); +// +// Thread thread = new Thread(() -> { +// try (Jedis blocker = createJedis()) { +// blocker.eval("while true do end"); +// } catch (Exception ex) { +// // swallow any exception +// } +// }); +// +// Pipeline pipe = jedis.pipelined(); +// pipe.incr("foo"); +// pipe.multi(); +// pipe.incr("foo"); +// pipe.sync(); +// +// thread.start(); +// try { +// Thread.sleep(12); // allow Redis to be busy with the script and 'lua-time-limit' to exceed +// } catch (InterruptedException ex) { } +// +// pipe.incr("foo"); +// Response> txResp = pipe.exec(); +// pipe.sync(); +// try { +// txResp.get(); +// } catch (Exception ex) { +// assertSame(AbortedTransactionException.class, ex.getClass()); +// } finally { +// try { +// String status = jedis.scriptKill(); +// // https://github.com/redis/jedis/issues/2656 +// if ("OK".equalsIgnoreCase(status)) { +// scriptKillWait(); +// } else { +// // #2656: Checking if this status is actually 'OK' when error occurs in next command. +// org.apache.logging.log4j.LogManager.getLogger().error( +// String.format("Status if SCRIPT KILL command is \"%s\"", status)); +// } +// } finally { +// jedis.configSet(luaTimeLimitKey, luaTimeLimit); +// } +// } +// } +// +// private void scriptKillWait() { +// int attemptLeft = 10; +// while (attemptLeft > 0) { +// try (Jedis pingJedis = createJedis()) { +// while (attemptLeft > 0) { +// try { +// pingJedis.ping(); +// return; // wait is over +// } catch (JedisBusyException busy) { +// Thread.sleep(10); // BUSY, waiting for some time +// --attemptLeft; // doing this later; otherwise any exception in Thread.sleep() +// // would cause decrement twice for the same turn. +// } +// } +// } catch (Exception any) { +// --attemptLeft; +// // try new connection +// } +// } +// } +// +// private void verifyHasBothValues(String firstKey, String secondKey, String value1, String value2) { +// assertFalse(firstKey.equals(secondKey)); +// assertTrue(firstKey.equals(value1) || firstKey.equals(value2)); +// assertTrue(secondKey.equals(value1) || secondKey.equals(value2)); +// } private Matcher> listWithItem(T expected) { return CoreMatchers. hasItem(equalTo(expected)); diff --git a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java b/src/test/java/redis/clients/jedis/ProtocolTest.java similarity index 92% rename from src/test/java/redis/clients/jedis/tests/ProtocolTest.java rename to src/test/java/redis/clients/jedis/ProtocolTest.java index 227ff00694..0fd7fc143a 100644 --- a/src/test/java/redis/clients/jedis/tests/ProtocolTest.java +++ b/src/test/java/redis/clients/jedis/ProtocolTest.java @@ -1,10 +1,11 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; +import redis.clients.jedis.util.FragmentedByteArrayInputStream; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; @@ -18,7 +19,6 @@ import org.junit.Test; -import redis.clients.jedis.Protocol; import redis.clients.jedis.exceptions.JedisBusyException; import redis.clients.jedis.util.RedisInputStream; import redis.clients.jedis.util.RedisOutputStream; @@ -32,7 +32,8 @@ public void buildACommand() throws IOException { PipedOutputStream pos = new PipedOutputStream(pis); RedisOutputStream ros = new RedisOutputStream(pos); - Protocol.sendCommand(ros, Protocol.Command.GET, "SOMEKEY".getBytes(Protocol.CHARSET)); +// Protocol.sendCommand(ros, Protocol.Command.GET, "SOMEKEY".getBytes(Protocol.CHARSET)); + Protocol.sendCommand(ros, new CommandArguments(Protocol.Command.GET).add("SOMEKEY")); ros.flush(); pos.close(); String expectedCommand = "*2\r\n$3\r\nGET\r\n$7\r\nSOMEKEY\r\n"; diff --git a/src/test/java/redis/clients/jedis/ReliableTransactionTest.java b/src/test/java/redis/clients/jedis/ReliableTransactionTest.java new file mode 100644 index 0000000000..5abd5cf126 --- /dev/null +++ b/src/test/java/redis/clients/jedis/ReliableTransactionTest.java @@ -0,0 +1,279 @@ +package redis.clients.jedis; + +import static org.junit.Assert.*; +import static redis.clients.jedis.Protocol.Command.INCR; +import static redis.clients.jedis.Protocol.Command.GET; +import static redis.clients.jedis.Protocol.Command.SET; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.util.SafeEncoder; + +public class ReliableTransactionTest { + + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + + final byte[] bmykey = { 0x42, 0x02, 0x03, 0x04 }; + + private static final HostAndPort hnp = HostAndPorts.getRedisServers().get(0); + + private Connection conn; + private Jedis nj; + + @Before + public void setUp() throws Exception { + conn = new Connection(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); + + nj = new Jedis(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); + nj.flushAll(); + } + + @After + public void tearDown() throws Exception { + nj.close(); + conn.close(); + } + + @Test + public void multi() { + ReliableTransaction trans = new ReliableTransaction(conn); + + trans.sadd("foo", "a"); + trans.sadd("foo", "b"); + trans.scard("foo"); + + List response = trans.exec(); + + List expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); + + // Binary + trans = new ReliableTransaction(conn); + + trans.sadd(bfoo, ba); + trans.sadd(bfoo, bb); + trans.scard(bfoo); + + response = trans.exec(); + + expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); + + } + + @Test + public void watch() { + ReliableTransaction t = new ReliableTransaction(conn, false); + assertEquals("OK", t.watch("mykey", "somekey")); + t.multi(); + + nj.set("mykey", "bar"); + + t.set("mykey", "foo"); + List resp = t.exec(); + assertNull(resp); + assertEquals("bar", nj.get("mykey")); + + // Binary + assertEquals("OK", t.watch(bmykey, "foobar".getBytes())); + t.multi(); + + nj.set(bmykey, bbar); + + t.set(bmykey, bfoo); + resp = t.exec(); + assertNull(resp); + assertArrayEquals(bbar, nj.get(bmykey)); + } + + @Test + public void unwatch() { + ReliableTransaction t = new ReliableTransaction(conn, false); + assertEquals("OK", t.watch("mykey")); + String val = "foo"; + assertEquals("OK", t.unwatch()); + t.multi(); + + nj.set("mykey", "bar"); + + t.set("mykey", val); + List resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); + + // Binary + t.watch(bmykey); + byte[] bval = bfoo; + assertEquals("OK", t.unwatch()); + t.multi(); + + nj.set(bmykey, bbar); + + t.set(bmykey, bval); + resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); + } + + @Test + public void discard() { + ReliableTransaction t = new ReliableTransaction(conn); + String status = t.discard(); + assertEquals("OK", status); + } + + @Test + public void transactionResponse() { + nj.set("string", "foo"); + nj.lpush("list", "foo"); + nj.hset("hash", "foo", "bar"); + nj.zadd("zset", 1, "foo"); + nj.sadd("set", "foo"); + + ReliableTransaction t = new ReliableTransaction(conn); + Response string = t.get("string"); + Response list = t.lpop("list"); + Response hash = t.hget("hash", "foo"); + Response> zset = t.zrange("zset", 0, -1); + Response set = t.spop("set"); + t.exec(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + } + + @Test + public void transactionResponseBinary() { + nj.set("string", "foo"); + nj.lpush("list", "foo"); + nj.hset("hash", "foo", "bar"); + nj.zadd("zset", 1, "foo"); + nj.sadd("set", "foo"); + + ReliableTransaction t = new ReliableTransaction(conn); + Response string = t.get("string".getBytes()); + Response list = t.lpop("list".getBytes()); + Response hash = t.hget("hash".getBytes(), "foo".getBytes()); + Response> zset = t.zrange("zset".getBytes(), 0, -1); + Response set = t.spop("set".getBytes()); + t.exec(); + + assertArrayEquals("foo".getBytes(), string.get()); + assertArrayEquals("foo".getBytes(), list.get()); + assertArrayEquals("bar".getBytes(), hash.get()); + assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); + assertArrayEquals("foo".getBytes(), set.get()); + } + + @Test(expected = IllegalStateException.class) + public void transactionResponseWithinPipeline() { + nj.set("string", "foo"); + + ReliableTransaction t = new ReliableTransaction(conn); + Response string = t.get("string"); + string.get(); + t.exec(); + } + + @Test + public void transactionResponseWithError() { + ReliableTransaction t = new ReliableTransaction(conn); + t.set("foo", "bar"); + Response> error = t.smembers("foo"); + Response r = t.get("foo"); + List l = t.exec(); + assertSame(JedisDataException.class, l.get(1).getClass()); + try { + error.get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals("bar", r.get()); + } + + @Test + public void testCloseable() { + // we need to test with fresh instance of Jedis +// Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); +// jedis2.auth("foobared"); + + ReliableTransaction transaction = new ReliableTransaction(conn); + transaction.set("a", "1"); + transaction.set("b", "2"); + + transaction.close(); + + try { + transaction.exec(); + fail("close should discard transaction"); + } catch (IllegalStateException e) { + assertTrue(e.getMessage().contains("EXEC without MULTI")); + // pass + } + } + + @Test + public void testTransactionWithGeneralCommand() { + ReliableTransaction t = new ReliableTransaction(conn); + t.set("string", "foo"); + t.lpush("list", "foo"); + t.hset("hash", "foo", "bar"); + t.zadd("zset", 1, "foo"); + t.sendCommand(SET, "x", "1"); + t.sadd("set", "foo"); + t.sendCommand(INCR, "x"); + Response string = t.get("string"); + Response list = t.lpop("list"); + Response hash = t.hget("hash", "foo"); + Response> zset = t.zrange("zset", 0, -1); + Response set = t.spop("set"); + Response x = t.sendCommand(GET, "x"); + t.exec(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + assertEquals("2", SafeEncoder.encode((byte[]) x.get())); + } + + @Test + public void transactionResponseWithErrorWithGeneralCommand() { + ReliableTransaction t = new ReliableTransaction(conn); + t.set("foo", "bar"); + t.sendCommand(SET, "x", "1"); + Response> error = t.smembers("foo"); + Response r = t.get("foo"); + Response x = t.sendCommand(GET, "x"); + t.sendCommand(INCR, "x"); + List l = t.exec(); + assertSame(JedisDataException.class, l.get(2).getClass()); + try { + error.get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals("bar", r.get()); + assertEquals("1", SafeEncoder.encode((byte[]) x.get())); + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/SSLACLJedisClusterTest.java similarity index 90% rename from src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java rename to src/test/java/redis/clients/jedis/SSLACLJedisClusterTest.java index 3111f3c00b..9d7b79b649 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterWithCompleteCredentialsTest.java +++ b/src/test/java/redis/clients/jedis/SSLACLJedisClusterTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -14,16 +14,14 @@ import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.*; -import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; -import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; -import redis.clients.jedis.tests.SSLJedisTest.BasicHostnameVerifier; -import redis.clients.jedis.tests.utils.RedisVersionUtil; +import redis.clients.jedis.exceptions.JedisClusterOperationException; +import redis.clients.jedis.SSLJedisTest.BasicHostnameVerifier; +import redis.clients.jedis.util.RedisVersionUtil; -public class SSLJedisClusterWithCompleteCredentialsTest extends JedisClusterTest { +public class SSLACLJedisClusterTest extends JedisClusterTest { private static final int DEFAULT_REDIRECTIONS = 5; - private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); + private static final ConnectionPoolConfig DEFAULT_POOL_CONFIG = new ConnectionPoolConfig(); private final HostAndPortMapper hostAndPortMap = (HostAndPort hostAndPort) -> { String host = hostAndPort.getHost(); @@ -81,7 +79,8 @@ public void testSSLWithoutPortMap() { try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), DefaultJedisClientConfig.builder().user("default").password("cluster").ssl(true).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc.getClusterNodes(); +// Map clusterNodes = jc.getClusterNodes(); + Map clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); @@ -110,7 +109,8 @@ public void connectToNodesFailsWithSSLParametersAndNoHostMapping() { DEFAULT_POOL_CONFIG)) { jc.get("foo"); Assert.fail("It should fail after all cluster attempts."); - } catch (JedisClusterMaxAttemptsException e) { +// } catch (JedisClusterMaxAttemptsException e) { + } catch (JedisClusterOperationException e) { // initial connection to localhost works, but subsequent connections to nodes use 127.0.0.1 // and fail hostname verification assertEquals("No more cluster attempts left.", e.getMessage()); @@ -141,7 +141,8 @@ public void connectByIpAddressFailsWithSSLParameters() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.get("key"); Assert.fail("There should be no reachable node in cluster."); - } catch (JedisNoReachableClusterNodeException e) { +// } catch (JedisNoReachableClusterNodeException e) { + } catch (JedisClusterOperationException e) { assertEquals("No reachable node in cluster.", e.getMessage()); } } @@ -157,7 +158,8 @@ public void connectWithCustomHostNameVerifier() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.get("foo"); Assert.fail("It should fail after all cluster attempts."); - } catch (JedisClusterMaxAttemptsException e) { +// } catch (JedisClusterMaxAttemptsException e) { + } catch (JedisClusterOperationException e) { // initial connection made with 'localhost' but subsequent connections to nodes use 127.0.0.1 // which causes custom hostname verification to fail assertEquals("No more cluster attempts left.", e.getMessage()); @@ -169,7 +171,8 @@ public void connectWithCustomHostNameVerifier() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc2.get("key"); Assert.fail("There should be no reachable node in cluster."); - } catch (JedisNoReachableClusterNodeException e) { +// } catch (JedisNoReachableClusterNodeException e) { + } catch (JedisClusterOperationException e) { // JedisNoReachableClusterNodeException exception occurs from not being able to connect since // the socket factory fails the hostname verification assertEquals("No reachable node in cluster.", e.getMessage()); @@ -204,7 +207,8 @@ public void connectWithEmptyTrustStore() throws Exception { .sslSocketFactory(sslSocketFactory).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.get("key"); Assert.fail("There should be no reachable node in cluster."); - } catch (JedisNoReachableClusterNodeException e) { +// } catch (JedisNoReachableClusterNodeException e) { + } catch (JedisClusterOperationException e) { assertEquals("No reachable node in cluster.", e.getMessage()); } } diff --git a/src/test/java/redis/clients/jedis/SSLACLJedisTest.java b/src/test/java/redis/clients/jedis/SSLACLJedisTest.java new file mode 100644 index 0000000000..a5f8d4adf5 --- /dev/null +++ b/src/test/java/redis/clients/jedis/SSLACLJedisTest.java @@ -0,0 +1,168 @@ +package redis.clients.jedis; + +import static org.junit.Assert.*; + +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URI; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; +import javax.net.ssl.*; + +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.util.RedisVersionUtil; + +/** + * This test class is a copy of {@link SSLJedisTest}. + *

+ * This test is only executed when the server/cluster is Redis 6. or more. + */ +public class SSLACLJedisTest { + + @BeforeClass + public static void prepare() { + // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later + org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", + RedisVersionUtil.checkRedisMajorVersionNumber(6)); + + SSLJedisTest.setupTrustStore(); + } + + @Test + public void connectWithSsl() { + try (Jedis jedis = new Jedis("localhost", 6390, true)) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfig() { + try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig + .builder().ssl(true).build())) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithUrl() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis("rediss://localhost:6390")) { + jedis.auth("default", "foobared"); + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis("rediss://localhost:6390")) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithCompleteCredentialsUrl() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis("rediss://default:foobared@localhost:6390")) { + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis("rediss://acljedis:fizzbuzz@localhost:6390")) { + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithUri() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { + jedis.auth("acljedis", "fizzbuzz"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithCompleteCredentialsUri() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis(URI.create("rediss://default:foobared@localhost:6390"))) { + assertEquals("PONG", jedis.ping()); + } + try (Jedis jedis = new Jedis(URI.create("rediss://acljedis:fizzbuzz@localhost:6390"))) { + assertEquals("PONG", jedis.ping()); + } + } + + /** + * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. + */ + static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { + + KeyStore trustStore = KeyStore.getInstance("jceks"); + try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { + trustStore.load(inputStream, null); + } + + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); + trustManagerFactory.init(trustStore); + TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. + */ + static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { + TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + } }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, unTrustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Very basic hostname verifier implementation for testing. NOT recommended for production. + */ + static class BasicHostnameVerifier implements HostnameVerifier { + + private static final String COMMON_NAME_RDN_PREFIX = "CN="; + + @Override + public boolean verify(String hostname, SSLSession session) { + X509Certificate peerCertificate; + try { + peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; + } catch (SSLPeerUnverifiedException e) { + throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); + } + String peerCertificateCN = getCommonName(peerCertificate); + return hostname.equals(peerCertificateCN); + } + + private String getCommonName(X509Certificate peerCertificate) { + String subjectDN = peerCertificate.getSubjectDN().getName(); + String[] dnComponents = subjectDN.split(","); + for (String dnComponent : dnComponents) { + dnComponent = dnComponent.trim(); + if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { + return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); + } + } + throw new IllegalArgumentException("The certificate has no common name."); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java b/src/test/java/redis/clients/jedis/SSLJedisClusterTest.java similarity index 87% rename from src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java rename to src/test/java/redis/clients/jedis/SSLJedisClusterTest.java index aa9671ecfb..0e5d87fdc2 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisClusterTest.java +++ b/src/test/java/redis/clients/jedis/SSLJedisClusterTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -14,20 +14,13 @@ import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.HostAndPortMapper; -import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.JedisPool; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; -import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; -import redis.clients.jedis.tests.SSLJedisTest.BasicHostnameVerifier; +import redis.clients.jedis.exceptions.JedisClusterOperationException; +import redis.clients.jedis.SSLJedisTest.BasicHostnameVerifier; public class SSLJedisClusterTest extends JedisClusterTest { private static final int DEFAULT_REDIRECTIONS = 5; - private static final JedisPoolConfig DEFAULT_POOL_CONFIG = new JedisPoolConfig(); + private static final ConnectionPoolConfig DEFAULT_POOL_CONFIG = new ConnectionPoolConfig(); private final HostAndPortMapper hostAndPortMap = (HostAndPort hostAndPort) -> { String host = hostAndPort.getHost(); @@ -57,7 +50,8 @@ public void testSSLDiscoverNodesAutomatically() { try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), DefaultJedisClientConfig.builder().password("cluster").ssl(true) .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc.getClusterNodes(); +// Map clusterNodes = jc.getClusterNodes(); + Map clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); @@ -69,7 +63,8 @@ public void testSSLDiscoverNodesAutomatically() { try (JedisCluster jc2 = new JedisCluster(new HostAndPort("localhost", 8379), DefaultJedisClientConfig.builder().password("cluster").ssl(true) .hostAndPortMapper(hostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc2.getClusterNodes(); +// Map clusterNodes = jc2.getClusterNodes(); + Map clusterNodes = jc2.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); @@ -83,7 +78,8 @@ public void testSSLWithoutPortMap() { try (JedisCluster jc = new JedisCluster(Collections.singleton(new HostAndPort("localhost", 8379)), DefaultJedisClientConfig.builder().password("cluster").ssl(true).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc.getClusterNodes(); +// Map clusterNodes = jc.getClusterNodes(); + Map clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); @@ -112,7 +108,8 @@ public void connectToNodesFailsWithSSLParametersAndNoHostMapping() { DEFAULT_POOL_CONFIG)) { jc.get("foo"); Assert.fail("It should fail after all cluster attempts."); - } catch (JedisClusterMaxAttemptsException e) { +// } catch (JedisClusterMaxAttemptsException e) { + } catch (JedisClusterOperationException e) { // initial connection to localhost works, but subsequent connections to nodes use 127.0.0.1 // and fail hostname verification assertEquals("No more cluster attempts left.", e.getMessage()); @@ -143,7 +140,8 @@ public void connectByIpAddressFailsWithSSLParameters() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.get("key"); Assert.fail("There should be no reachable node in cluster."); - } catch (JedisNoReachableClusterNodeException e) { +// } catch (JedisNoReachableClusterNodeException e) { + } catch (JedisClusterOperationException e) { assertEquals("No reachable node in cluster.", e.getMessage()); } } @@ -159,7 +157,8 @@ public void connectWithCustomHostNameVerifier() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.get("foo"); Assert.fail("It should fail after all cluster attempts."); - } catch (JedisClusterMaxAttemptsException e) { +// } catch (JedisClusterMaxAttemptsException e) { + } catch (JedisClusterOperationException e) { // initial connection made with 'localhost' but subsequent connections to nodes use 127.0.0.1 // which causes custom hostname verification to fail assertEquals("No more cluster attempts left.", e.getMessage()); @@ -171,7 +170,8 @@ public void connectWithCustomHostNameVerifier() { DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc2.get("foo"); Assert.fail("There should be no reachable node in cluster."); - } catch (JedisNoReachableClusterNodeException e) { +// } catch (JedisNoReachableClusterNodeException e) { + } catch (JedisClusterOperationException e) { // JedisNoReachableClusterNodeException exception occurs from not being able to connect // since the socket factory fails the hostname verification assertEquals("No reachable node in cluster.", e.getMessage()); @@ -206,7 +206,8 @@ public void connectWithEmptyTrustStore() throws Exception { .sslSocketFactory(sslSocketFactory).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { jc.get("key"); Assert.fail("There should be no reachable node in cluster."); - } catch (JedisNoReachableClusterNodeException e) { +// } catch (JedisNoReachableClusterNodeException e) { + } catch (JedisClusterOperationException e) { assertEquals("No reachable node in cluster.", e.getMessage()); } } @@ -219,7 +220,8 @@ public void defaultHostAndPortUsedIfMapReturnsNull() { DefaultJedisClientConfig.builder().password("cluster").ssl(false) .hostAndPortMapper(nullHostAndPortMap).build(), DEFAULT_REDIRECTIONS, DEFAULT_POOL_CONFIG)) { - Map clusterNodes = jc.getClusterNodes(); +// Map clusterNodes = jc.getClusterNodes(); + Map clusterNodes = jc.getClusterNodes(); assertEquals(3, clusterNodes.size()); assertTrue(clusterNodes.containsKey("127.0.0.1:7379")); assertTrue(clusterNodes.containsKey("127.0.0.1:7380")); diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisSentinelPoolTest.java b/src/test/java/redis/clients/jedis/SSLJedisSentinelPoolTest.java similarity index 90% rename from src/test/java/redis/clients/jedis/tests/SSLJedisSentinelPoolTest.java rename to src/test/java/redis/clients/jedis/SSLJedisSentinelPoolTest.java index da2c40cb0e..7468c9abfa 100644 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisSentinelPoolTest.java +++ b/src/test/java/redis/clients/jedis/SSLJedisSentinelPoolTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import java.util.HashSet; import java.util.Set; @@ -6,12 +6,6 @@ import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.HostAndPortMapper; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisSentinelPool; - public class SSLJedisSentinelPoolTest { private static final String MASTER_NAME = "aclmaster"; @@ -27,7 +21,7 @@ public class SSLJedisSentinelPoolTest { public static void prepare() { SSLJedisTest.setupTrustStore(); - sentinels.add(HostAndPortUtil.getSentinelServers().get(4)); + sentinels.add(HostAndPorts.getSentinelServers().get(4)); } @Test diff --git a/src/test/java/redis/clients/jedis/SSLJedisTest.java b/src/test/java/redis/clients/jedis/SSLJedisTest.java new file mode 100644 index 0000000000..5c6d22de99 --- /dev/null +++ b/src/test/java/redis/clients/jedis/SSLJedisTest.java @@ -0,0 +1,173 @@ +package redis.clients.jedis; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.io.File; +import java.io.FileInputStream; +import java.io.InputStream; +import java.net.URI; +import java.security.InvalidAlgorithmParameterException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLPeerUnverifiedException; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSocketFactory; +import javax.net.ssl.TrustManager; +import javax.net.ssl.TrustManagerFactory; +import javax.net.ssl.X509TrustManager; + +import org.junit.BeforeClass; +import org.junit.Test; + +public class SSLJedisTest { + + @BeforeClass + public static void prepare() { + setupTrustStore(); + } + + static void setupTrustStore() { + setJvmTrustStore("src/test/resources/truststore.jceks", "jceks"); + } + + private static void setJvmTrustStore(String trustStoreFilePath, String trustStoreType) { + assertTrue(String.format("Could not find trust store at '%s'.", trustStoreFilePath), + new File(trustStoreFilePath).exists()); + System.setProperty("javax.net.ssl.trustStore", trustStoreFilePath); + System.setProperty("javax.net.ssl.trustStoreType", trustStoreType); + } + + @Test + public void connectWithSsl() { + try (Jedis jedis = new Jedis("localhost", 6390, true)) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfig() { + try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig + .builder().ssl(true).build())) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + @Test + public void connectWithConfigInterface() { + try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), + new JedisClientConfig() { + @Override + public boolean isSsl() { + return true; + } + })) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + /** + * Tests opening a default SSL/TLS connection to redis using "rediss://" scheme url. + */ + @Test + public void connectWithUrl() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis("rediss://localhost:6390")) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + /** + * Tests opening a default SSL/TLS connection to redis. + */ + @Test + public void connectWithUri() { + // The "rediss" scheme instructs jedis to open a SSL/TLS connection. + try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { + jedis.auth("foobared"); + assertEquals("PONG", jedis.ping()); + } + } + + /** + * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. + */ + static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { + + KeyStore trustStore = KeyStore.getInstance("jceks"); + + try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { + trustStore.load(inputStream, null); + } + + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); + trustManagerFactory.init(trustStore); + TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, trustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. + */ + static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { + TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { + public X509Certificate[] getAcceptedIssuers() { + return new X509Certificate[0]; + } + + public void checkClientTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + + public void checkServerTrusted(X509Certificate[] chain, String authType) { + throw new RuntimeException(new InvalidAlgorithmParameterException()); + } + } }; + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(null, unTrustManagers, new SecureRandom()); + return sslContext.getSocketFactory(); + } + + /** + * Very basic hostname verifier implementation for testing. NOT recommended for production. + */ + static class BasicHostnameVerifier implements HostnameVerifier { + + private static final String COMMON_NAME_RDN_PREFIX = "CN="; + + @Override + public boolean verify(String hostname, SSLSession session) { + X509Certificate peerCertificate; + try { + peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; + } catch (SSLPeerUnverifiedException e) { + throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); + } + String peerCertificateCN = getCommonName(peerCertificate); + return hostname.equals(peerCertificateCN); + } + + private String getCommonName(X509Certificate peerCertificate) { + String subjectDN = peerCertificate.getSubjectDN().getName(); + String[] dnComponents = subjectDN.split(","); + for (String dnComponent : dnComponents) { + dnComponent = dnComponent.trim(); + if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { + return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); + } + } + throw new IllegalArgumentException("The certificate has no common name."); + } + } +} diff --git a/src/test/java/redis/clients/jedis/ShardedConnectionTest.java b/src/test/java/redis/clients/jedis/ShardedConnectionTest.java new file mode 100644 index 0000000000..e26acd6cdf --- /dev/null +++ b/src/test/java/redis/clients/jedis/ShardedConnectionTest.java @@ -0,0 +1,101 @@ +package redis.clients.jedis; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.fail; + +import java.net.URISyntaxException; +import java.util.ArrayList; +import java.util.List; +import org.apache.commons.pool2.impl.GenericObjectPoolConfig; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.exceptions.JedisDataException; + +public class ShardedConnectionTest { + + private static final HostAndPort redis1 = HostAndPorts.getRedisServers().get(0); + private static final HostAndPort redis2 = HostAndPorts.getRedisServers().get(1); + + private List shards; + private JedisClientConfig clientConfig; + + @Before + public void startUp() { + shards = new ArrayList<>(); + shards.add(redis1); + shards.add(redis2); + + clientConfig = DefaultJedisClientConfig.builder().password("foobared").build(); + + for (HostAndPort shard : shards) { + try (Jedis j = new Jedis(shard, clientConfig)) { + j.flushAll(); + } + } + } + + @Test + public void checkConnections() { + try (JedisSharding jedis = new JedisSharding(shards, clientConfig)) { + jedis.set("foo", "bar"); + assertEquals("bar", jedis.get("foo")); + } + } + + @Test + public void checkPoolWhenJedisIsBroken() { + GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig<>(); + poolConfig.setMaxTotal(1); + try (JedisSharding jedis = new JedisSharding(shards, clientConfig, poolConfig)) { + jedis.sendCommand(Protocol.Command.QUIT); + jedis.incr("foo"); + } catch (JedisConnectionException jce) { + } + } + + @Test + public void checkPoolTestOnBorrowWhenJedisIsBroken() { + GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig<>(); + poolConfig.setMaxTotal(1); + poolConfig.setTestOnBorrow(true); + try (JedisSharding jedis = new JedisSharding(shards, clientConfig, poolConfig)) { + jedis.sendCommand(Protocol.Command.QUIT); + jedis.incr("foo"); + } + } + + @Test + public void checkPoolTestOnReturnWhenJedisIsBroken() { + GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig<>(); + poolConfig.setMaxTotal(1); + poolConfig.setTestOnReturn(true); + try (JedisSharding jedis = new JedisSharding(shards, clientConfig, poolConfig)) { + jedis.sendCommand(Protocol.Command.QUIT); + jedis.incr("foo"); + } + } + + @Test + public void checkFailedJedisServer() { + try (JedisSharding jedis = new JedisSharding(shards)) { + try { + jedis.incr("foo"); + fail("Should get NOAUTH error."); + } catch (JedisDataException jde) { + assertEquals("NOAUTH Authentication required.", jde.getMessage()); + } + } + } + + @Test + public void checkResourceIsCloseable() throws URISyntaxException { + GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig<>(); + poolConfig.setMaxTotal(1); + poolConfig.setBlockWhenExhausted(false); + + try (JedisSharding jedis = new JedisSharding(shards, clientConfig, poolConfig)) { + jedis.set("hello", "jedis"); + } + } +} diff --git a/src/test/java/redis/clients/jedis/ShardingTest.java b/src/test/java/redis/clients/jedis/ShardingTest.java new file mode 100644 index 0000000000..c62dc73fd1 --- /dev/null +++ b/src/test/java/redis/clients/jedis/ShardingTest.java @@ -0,0 +1,153 @@ +package redis.clients.jedis; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static redis.clients.jedis.Protocol.Command.SET; + +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.util.Hashing; + +public class ShardingTest { + + private static final HostAndPort redis1 = HostAndPorts.getRedisServers().get(0); + private static final HostAndPort redis2 = HostAndPorts.getRedisServers().get(1); + + private JedisClientConfig clientConfig = DefaultJedisClientConfig.builder().password("foobared").build(); + + @Before + public void setUp() { + try (Jedis j = new Jedis(redis1, clientConfig)) { + j.flushAll(); + } + try (Jedis j = new Jedis(redis2, clientConfig)) { + j.flushAll(); + } + } + + @Test + public void trySharding() { + List shards = new ArrayList<>(); + shards.add(redis1); + shards.add(redis2); + try (JedisSharding jedis = new JedisSharding(shards, clientConfig)) { + for (int i = 0; i < 1000; i++) { + jedis.set("key" + i, Integer.toString(i)); + } + } + + long totalDbSize = 0; + try (Jedis j = new Jedis(redis1)) { + j.auth("foobared"); + long dbSize = j.dbSize(); + System.out.println(dbSize); + assertTrue(dbSize > 400); + totalDbSize += dbSize; + } + try (Jedis j = new Jedis(redis2)) { + j.auth("foobared"); + long dbSize = j.dbSize(); + assertTrue(dbSize > 400); + totalDbSize += dbSize; + } + assertEquals(1000, totalDbSize); + } + + @Test + public void tryShardingWithMurmur() { + List shards = new ArrayList<>(); + shards.add(redis1); + shards.add(redis2); + try (JedisSharding jedis = new JedisSharding(shards, clientConfig, Hashing.MURMUR_HASH)) { + for (int i = 0; i < 1000; i++) { + jedis.set("key" + i, Integer.toString(i)); + } + } + + long totalDbSize = 0; + try (Jedis j = new Jedis(redis1)) { + j.auth("foobared"); + long dbSize = j.dbSize(); + assertTrue(dbSize > 400); + totalDbSize += dbSize; + } + try (Jedis j = new Jedis(redis2)) { + j.auth("foobared"); + long dbSize = j.dbSize(); + assertTrue(dbSize > 400); + totalDbSize += dbSize; + } + assertEquals(1000, totalDbSize); + } + + @Test + public void tryShardingWithMD5() { + List shards = new ArrayList<>(); + shards.add(redis1); + shards.add(redis2); + try (JedisSharding jedis = new JedisSharding(shards, clientConfig, Hashing.MD5)) { + for (int i = 0; i < 1000; i++) { + jedis.set("key" + i, Integer.toString(i)); + } + } + + long totalDbSize = 0; + try (Jedis j = new Jedis(redis1)) { + j.auth("foobared"); + long dbSize = j.dbSize(); + assertTrue(dbSize > 400); + totalDbSize += dbSize; + } + try (Jedis j = new Jedis(redis2)) { + j.auth("foobared"); + long dbSize = j.dbSize(); + totalDbSize += dbSize; + } + assertEquals(1000, totalDbSize); + } + + @Test + public void checkKeyTags() { + assertNotNull(((ShardedCommandArguments) new ShardedCommandArguments(Hashing.MURMUR_HASH, SET).key("bar")).getKeyHash()); + assertNotNull(((ShardedCommandArguments) new ShardedCommandArguments(Hashing.MD5, SET).key("bar")).getKeyHash()); + assertEquals(((ShardedCommandArguments) new ShardedCommandArguments(Hashing.MURMUR_HASH, + JedisSharding.DEFAULT_KEY_TAG_PATTERN, SET).key("bar")).getKeyHash(), + ((ShardedCommandArguments) new ShardedCommandArguments(Hashing.MURMUR_HASH, + JedisSharding.DEFAULT_KEY_TAG_PATTERN, SET).key("foo{bar}")).getKeyHash()); + assertEquals(((ShardedCommandArguments) new ShardedCommandArguments(Hashing.MD5, JedisSharding.DEFAULT_KEY_TAG_PATTERN, SET).key("bar")).getKeyHash(), + ((ShardedCommandArguments) new ShardedCommandArguments(Hashing.MD5, JedisSharding.DEFAULT_KEY_TAG_PATTERN, SET).key("foo{bar}")).getKeyHash()); + } + + @Test + public void checkCloseable() { + List shards = new ArrayList<>(); + shards.add(redis1); + shards.add(redis2); + + JedisSharding jedis = new JedisSharding(shards, clientConfig); + jedis.set("closeable", "true"); + assertEquals("true", jedis.get("closeable")); + jedis.close(); + try { + jedis.get("closeable"); + fail(); + } catch (Exception ex) { + } + } + + @Test + public void testGeneralCommand() { + List shards = new ArrayList<>(); + shards.add(redis1); + shards.add(redis2); + + try (JedisSharding jedis = new JedisSharding(shards, clientConfig)) { + jedis.sendCommand("command", SET, "command", "general"); + assertEquals("general", jedis.get("command")); + } + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/TransactionV2Test.java b/src/test/java/redis/clients/jedis/TransactionV2Test.java new file mode 100644 index 0000000000..8ee48cc308 --- /dev/null +++ b/src/test/java/redis/clients/jedis/TransactionV2Test.java @@ -0,0 +1,278 @@ +package redis.clients.jedis; + +import static org.junit.Assert.*; +import static redis.clients.jedis.Protocol.Command.INCR; +import static redis.clients.jedis.Protocol.Command.GET; +import static redis.clients.jedis.Protocol.Command.SET; + +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.util.SafeEncoder; + +public class TransactionV2Test { + + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + + final byte[] bmykey = { 0x42, 0x02, 0x03, 0x04 }; + + private static final HostAndPort hnp = HostAndPorts.getRedisServers().get(0); + + private Connection conn; + private Jedis nj; + + @Before + public void setUp() throws Exception { + conn = new Connection(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); + + nj = new Jedis(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); + nj.flushAll(); + } + + @After + public void tearDown() throws Exception { + nj.close(); + conn.close(); + } + + @Test + public void multi() { + Transaction trans = new Transaction(conn); + + trans.sadd("foo", "a"); + trans.sadd("foo", "b"); + trans.scard("foo"); + + List response = trans.exec(); + + List expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); + + // Binary + trans = new Transaction(conn); + + trans.sadd(bfoo, ba); + trans.sadd(bfoo, bb); + trans.scard(bfoo); + + response = trans.exec(); + + expected = new ArrayList(); + expected.add(1L); + expected.add(1L); + expected.add(2L); + assertEquals(expected, response); + } + + @Test + public void watch() { + Transaction t = new Transaction(conn, false); + assertEquals("OK", t.watch("mykey", "somekey")); + t.multi(); + + nj.set("mykey", "bar"); + + t.set("mykey", "foo"); + List resp = t.exec(); + assertNull(resp); + assertEquals("bar", nj.get("mykey")); + + // Binary + assertEquals("OK", t.watch(bmykey, "foobar".getBytes())); + t.multi(); + + nj.set(bmykey, bbar); + + t.set(bmykey, bfoo); + resp = t.exec(); + assertNull(resp); + assertArrayEquals(bbar, nj.get(bmykey)); + } + + @Test + public void unwatch() { + Transaction t = new Transaction(conn, false); + assertEquals("OK", t.watch("mykey")); + String val = "foo"; + assertEquals("OK", t.unwatch()); + t.multi(); + + nj.set("mykey", "bar"); + + t.set("mykey", val); + List resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); + + // Binary + t.watch(bmykey); + byte[] bval = bfoo; + assertEquals("OK", t.unwatch()); + t.multi(); + + nj.set(bmykey, bbar); + + t.set(bmykey, bval); + resp = t.exec(); + assertEquals(1, resp.size()); + assertEquals("OK", resp.get(0)); + } + + @Test + public void discard() { + Transaction t = new Transaction(conn); + String status = t.discard(); + assertEquals("OK", status); + } + + @Test + public void transactionResponse() { + nj.set("string", "foo"); + nj.lpush("list", "foo"); + nj.hset("hash", "foo", "bar"); + nj.zadd("zset", 1, "foo"); + nj.sadd("set", "foo"); + + Transaction t = new Transaction(conn); + Response string = t.get("string"); + Response list = t.lpop("list"); + Response hash = t.hget("hash", "foo"); + Response> zset = t.zrange("zset", 0, -1); + Response set = t.spop("set"); + t.exec(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + } + + @Test + public void transactionResponseBinary() { + nj.set("string", "foo"); + nj.lpush("list", "foo"); + nj.hset("hash", "foo", "bar"); + nj.zadd("zset", 1, "foo"); + nj.sadd("set", "foo"); + + Transaction t = new Transaction(conn); + Response string = t.get("string".getBytes()); + Response list = t.lpop("list".getBytes()); + Response hash = t.hget("hash".getBytes(), "foo".getBytes()); + Response> zset = t.zrange("zset".getBytes(), 0, -1); + Response set = t.spop("set".getBytes()); + t.exec(); + + assertArrayEquals("foo".getBytes(), string.get()); + assertArrayEquals("foo".getBytes(), list.get()); + assertArrayEquals("bar".getBytes(), hash.get()); + assertArrayEquals("foo".getBytes(), zset.get().iterator().next()); + assertArrayEquals("foo".getBytes(), set.get()); + } + + @Test(expected = IllegalStateException.class) + public void transactionResponseWithinPipeline() { + nj.set("string", "foo"); + + Transaction t = new Transaction(conn); + Response string = t.get("string"); + string.get(); + t.exec(); + } + + @Test + public void transactionResponseWithError() { + Transaction t = new Transaction(conn); + t.set("foo", "bar"); + Response> error = t.smembers("foo"); + Response r = t.get("foo"); + List l = t.exec(); + assertSame(JedisDataException.class, l.get(1).getClass()); + try { + error.get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals("bar", r.get()); + } + + @Test + public void testCloseable() { + // we need to test with fresh instance of Jedis +// Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); +// jedis2.auth("foobared"); + + Transaction transaction = new Transaction(conn); + transaction.set("a", "1"); + transaction.set("b", "2"); + + transaction.close(); + + try { + transaction.exec(); + fail("close should discard transaction"); + } catch (IllegalStateException e) { + assertTrue(e.getMessage().contains("EXEC without MULTI")); + // pass + } + } + + @Test + public void testTransactionWithGeneralCommand() { + Transaction t = new Transaction(conn); + t.set("string", "foo"); + t.lpush("list", "foo"); + t.hset("hash", "foo", "bar"); + t.zadd("zset", 1, "foo"); + t.sendCommand(SET, "x", "1"); + t.sadd("set", "foo"); + t.sendCommand(INCR, "x"); + Response string = t.get("string"); + Response list = t.lpop("list"); + Response hash = t.hget("hash", "foo"); + Response> zset = t.zrange("zset", 0, -1); + Response set = t.spop("set"); + Response x = t.sendCommand(GET, "x"); + t.exec(); + + assertEquals("foo", string.get()); + assertEquals("foo", list.get()); + assertEquals("bar", hash.get()); + assertEquals("foo", zset.get().iterator().next()); + assertEquals("foo", set.get()); + assertEquals("2", SafeEncoder.encode((byte[]) x.get())); + } + + @Test + public void transactionResponseWithErrorWithGeneralCommand() { + Transaction t = new Transaction(conn); + t.set("foo", "bar"); + t.sendCommand(SET, "x", "1"); + Response> error = t.smembers("foo"); + Response r = t.get("foo"); + Response x = t.sendCommand(GET, "x"); + t.sendCommand(INCR, "x"); + List l = t.exec(); + assertSame(JedisDataException.class, l.get(2).getClass()); + try { + error.get(); + fail("We expect exception here!"); + } catch (JedisDataException e) { + // that is fine we should be here + } + assertEquals("bar", r.get()); + assertEquals("1", SafeEncoder.encode((byte[]) x.get())); + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/TupleSortedSetTest.java b/src/test/java/redis/clients/jedis/TupleSortedSetTest.java new file mode 100644 index 0000000000..676a19ffa5 --- /dev/null +++ b/src/test/java/redis/clients/jedis/TupleSortedSetTest.java @@ -0,0 +1,84 @@ +package redis.clients.jedis; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import org.junit.Test; +import redis.clients.jedis.resps.Tuple; +import redis.clients.jedis.commands.jedis.JedisCommandsTestBase; + +public class TupleSortedSetTest extends JedisCommandsTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + final byte[] bc = { 0x0C }; + final byte[] bd = { 0x0D }; + final byte[] be = { 0x0E }; + final byte[] bf = { 0x0F }; + + @Test + public void testBinary() { + List array = new ArrayList(); + + jedis.zadd(bfoo, 0d, ba); + array.add(new Tuple(ba, 0d)); + + jedis.zadd(bfoo, 1d, bb); + array.add(new Tuple(bb, 1d)); + + List zrange = jedis.zrangeWithScores(bfoo, 0, -1); + assertEquals(zrange, sorted(array)); + + jedis.zadd(bfoo, -0.3, bc); + array.add(new Tuple(bc, -0.3)); + + jedis.zadd(bfoo, 0.3, bf); + array.add(new Tuple(bf, 0.3)); + + jedis.zadd(bfoo, 0.3, be); + array.add(new Tuple(be, 0.3)); + + jedis.zadd(bfoo, 0.3, bd); + array.add(new Tuple(bd, 0.3)); + + zrange = jedis.zrangeWithScores(bfoo, 0, -1); + assertEquals(zrange, sorted(array)); + } + + @Test + public void testString() { + List array = new ArrayList(); + + jedis.zadd("foo", 0d, "a"); + array.add(new Tuple("a", 0d)); + + jedis.zadd("foo", 1d, "b"); + array.add(new Tuple("b", 1d)); + + List range = jedis.zrangeWithScores("foo", 0, -1); + assertEquals(range, sorted(array)); + + jedis.zadd("foo", -0.3, "c"); + array.add(new Tuple("c", -0.3)); + + jedis.zadd("foo", 0.3, "f"); + array.add(new Tuple("f", 0.3)); + + jedis.zadd("foo", 0.3, "e"); + array.add(new Tuple("e", 0.3)); + + jedis.zadd("foo", 0.3, "d"); + array.add(new Tuple("d", 0.3)); + + range = jedis.zrangeWithScores("foo", 0, -1); + assertEquals(range, sorted(array)); + } + + private List sorted(List list) { + List sort = new ArrayList<>(list); + Collections.sort(sort); + return sort; + } +} diff --git a/src/test/java/redis/clients/jedis/tests/TupleTest.java b/src/test/java/redis/clients/jedis/TupleTest.java similarity index 96% rename from src/test/java/redis/clients/jedis/tests/TupleTest.java rename to src/test/java/redis/clients/jedis/TupleTest.java index c6ea80ba27..395c905ac8 100644 --- a/src/test/java/redis/clients/jedis/tests/TupleTest.java +++ b/src/test/java/redis/clients/jedis/TupleTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -7,7 +7,7 @@ import java.util.HashSet; import org.junit.Test; -import redis.clients.jedis.Tuple; +import redis.clients.jedis.resps.Tuple; public class TupleTest { diff --git a/src/test/java/redis/clients/jedis/UdsTest.java b/src/test/java/redis/clients/jedis/UdsTest.java new file mode 100644 index 0000000000..9330c99f71 --- /dev/null +++ b/src/test/java/redis/clients/jedis/UdsTest.java @@ -0,0 +1,43 @@ +package redis.clients.jedis; + +import java.io.File; +import java.io.IOException; +import java.net.Socket; +import org.junit.Test; +import org.newsclub.net.unix.AFUNIXSocket; +import org.newsclub.net.unix.AFUNIXSocketAddress; + +//import redis.clients.jedis.HostAndPort; +//import redis.clients.jedis.Jedis; +import redis.clients.jedis.UnifiedJedis; +import redis.clients.jedis.JedisSocketFactory; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.exceptions.JedisConnectionException; + +import static org.junit.Assert.assertEquals; + +public class UdsTest { + + @Test + public void testConnectsToUds() { + try (UnifiedJedis jedis = new UnifiedJedis(new UdsJedisSocketFactory())) { +// assertEquals("PONG", jedis.ping()); + } + } + + private static class UdsJedisSocketFactory implements JedisSocketFactory { + + private static final File UDS_SOCKET = new File("/tmp/redis_uds.sock"); + + @Override + public Socket createSocket() throws JedisConnectionException { + try { + Socket socket = AFUNIXSocket.newStrictInstance(); + socket.connect(new AFUNIXSocketAddress(UDS_SOCKET), Protocol.DEFAULT_TIMEOUT); + return socket; + } catch (IOException ioe) { + throw new JedisConnectionException("Failed to create UDS connection.", ioe); + } + } + } +} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java b/src/test/java/redis/clients/jedis/UnavailableConnectionTest.java similarity index 91% rename from src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java rename to src/test/java/redis/clients/jedis/UnavailableConnectionTest.java index 937ad2b6be..d61b5e89bb 100644 --- a/src/test/java/redis/clients/jedis/tests/UnavailableConnectionTest.java +++ b/src/test/java/redis/clients/jedis/UnavailableConnectionTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertSame; @@ -62,8 +62,9 @@ public void testAvoidQuitInDestroyObjectForBrokenConnection() throws Interrupted fail("Should not get connection from pool"); } catch (Exception ex) { assertSame(JedisConnectionException.class, ex.getClass()); - assertSame(JedisConnectionException.class, ex.getCause().getClass()); - assertSame(java.net.ConnectException.class, ex.getCause().getCause().getClass()); +// assertSame(JedisConnectionException.class, ex.getCause().getClass()); +// assertSame(java.net.ConnectException.class, ex.getCause().getCause().getClass()); + assertSame(java.net.ConnectException.class, ex.getCause().getClass()); } } diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/CRC16Benchmark.java b/src/test/java/redis/clients/jedis/benchmark/CRC16Benchmark.java similarity index 72% rename from src/test/java/redis/clients/jedis/tests/benchmark/CRC16Benchmark.java rename to src/test/java/redis/clients/jedis/benchmark/CRC16Benchmark.java index d52a9cf53e..1f1b5e5022 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/CRC16Benchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/CRC16Benchmark.java @@ -1,14 +1,15 @@ -package redis.clients.jedis.tests.benchmark; +package redis.clients.jedis.benchmark; import java.util.Calendar; import redis.clients.jedis.util.JedisClusterCRC16; public class CRC16Benchmark { + private static final int TOTAL_OPERATIONS = 100000000; - private static String[] TEST_SET = { "", "123456789", "sfger132515", - "hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA", "Hello, World!" }; + private static String[] TEST_SET = {"", "123456789", "sfger132515", + "hae9Napahngaikeethievubaibogiech", "AAAAAAAAAAAAAAAAAAAAAA", "Hello, World!"}; public static void main(String[] args) { long begin = Calendar.getInstance().getTimeInMillis(); @@ -21,5 +22,4 @@ public static void main(String[] args) { System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops"); } - -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/GetSetBenchmark.java similarity index 82% rename from src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java rename to src/test/java/redis/clients/jedis/benchmark/GetSetBenchmark.java index b5921bd535..93d450abc1 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/GetSetBenchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/GetSetBenchmark.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.benchmark; +package redis.clients.jedis.benchmark; import java.io.IOException; import java.net.UnknownHostException; @@ -6,10 +6,11 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.HostAndPorts; public class GetSetBenchmark { - private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + private static HostAndPort hnp = HostAndPorts.getRedisServers().get(0); private static final int TOTAL_OPERATIONS = 100000; public static void main(String[] args) throws UnknownHostException, IOException { @@ -32,4 +33,4 @@ public static void main(String[] args) throws UnknownHostException, IOException System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); } -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/HashingBenchmark.java similarity index 92% rename from src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java rename to src/test/java/redis/clients/jedis/benchmark/HashingBenchmark.java index 05d7f39297..1d145f0618 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/ShardedBenchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/HashingBenchmark.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.benchmark; +package redis.clients.jedis.benchmark; import java.io.IOException; import java.net.UnknownHostException; @@ -6,7 +6,8 @@ import redis.clients.jedis.util.Hashing; -public class ShardedBenchmark { +public class HashingBenchmark { + private static final int TOTAL_OPERATIONS = 10000000; public static void main(String[] args) throws UnknownHostException, IOException { @@ -32,6 +33,5 @@ public static void main(String[] args) throws UnknownHostException, IOException elapsed = Calendar.getInstance().getTimeInMillis() - begin; System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " Murmur ops"); - } -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/PipelinedGetSetBenchmark.java similarity index 84% rename from src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java rename to src/test/java/redis/clients/jedis/benchmark/PipelinedGetSetBenchmark.java index 14d8b5a083..413fa55428 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PipelinedGetSetBenchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/PipelinedGetSetBenchmark.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.benchmark; +package redis.clients.jedis.benchmark; import java.io.IOException; import java.net.UnknownHostException; @@ -7,10 +7,11 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.Pipeline; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.HostAndPorts; public class PipelinedGetSetBenchmark { - private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + private static HostAndPort hnp = HostAndPorts.getRedisServers().get(0); private static final int TOTAL_OPERATIONS = 200000; public static void main(String[] args) throws UnknownHostException, IOException { @@ -35,4 +36,4 @@ public static void main(String[] args) throws UnknownHostException, IOException System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); } -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/PoolBenchmark.java similarity index 89% rename from src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java rename to src/test/java/redis/clients/jedis/benchmark/PoolBenchmark.java index 948a7fab72..2d6d0c561d 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/PoolBenchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/PoolBenchmark.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.benchmark; +package redis.clients.jedis.benchmark; import java.util.ArrayList; import java.util.List; @@ -9,10 +9,11 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.HostAndPorts; public class PoolBenchmark { - private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); + + private static HostAndPort hnp = HostAndPorts.getRedisServers().get(0); private static final int TOTAL_OPERATIONS = 100000; public static void main(String[] args) throws Exception { @@ -55,10 +56,10 @@ public void run() { hj.start(); } - for (Thread t : tds) + for (Thread t : tds) { t.join(); + } pool.destroy(); - } -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/benchmark/PooledBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/PooledBenchmark.java new file mode 100644 index 0000000000..44ebe16e47 --- /dev/null +++ b/src/test/java/redis/clients/jedis/benchmark/PooledBenchmark.java @@ -0,0 +1,59 @@ +package redis.clients.jedis.benchmark; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.HostAndPorts; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPooled; + +public class PooledBenchmark { + + private static HostAndPort hnp = HostAndPorts.getRedisServers().get(0); + private static final int TOTAL_OPERATIONS = 100000; + + public static void main(String[] args) throws Exception { + try (Jedis j = new Jedis(hnp.getHost(), hnp.getPort())) { + j.auth("foobared"); + j.flushAll(); + j.quit(); + } + long t = System.currentTimeMillis(); + withPool(); + long elapsed = System.currentTimeMillis() - t; + System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); + } + + private static void withPool() throws Exception { + final JedisPooled j = new JedisPooled(hnp.getHost(), hnp.getPort(), null, "foobared"); + List tds = new ArrayList<>(); + + final AtomicInteger ind = new AtomicInteger(); + for (int i = 0; i < 50; i++) { + Thread hj = new Thread(new Runnable() { + @Override + public void run() { + for (int i = 0; (i = ind.getAndIncrement()) < TOTAL_OPERATIONS;) { + try { + final String key = "foo" + i; + j.set(key, key); + j.get(key); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + }); + tds.add(hj); + hj.start(); + } + + for (Thread t : tds) { + t.join(); + } + + j.close(); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/ProtocolBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/ProtocolBenchmark.java similarity index 91% rename from src/test/java/redis/clients/jedis/tests/benchmark/ProtocolBenchmark.java rename to src/test/java/redis/clients/jedis/benchmark/ProtocolBenchmark.java index 99de16f329..bf0864ed76 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/ProtocolBenchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/ProtocolBenchmark.java @@ -1,8 +1,4 @@ -package redis.clients.jedis.tests.benchmark; - -import redis.clients.jedis.Protocol; -import redis.clients.jedis.util.RedisInputStream; -import redis.clients.jedis.util.RedisOutputStream; +package redis.clients.jedis.benchmark; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; @@ -10,10 +6,16 @@ import java.io.InputStream; import java.util.concurrent.TimeUnit; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.util.RedisInputStream; +import redis.clients.jedis.util.RedisOutputStream; + /** * Copyright (c) 2014 */ public class ProtocolBenchmark { + private static final int TOTAL_OPERATIONS = 500000; public static void main(String[] args) throws Exception, IOException { @@ -92,7 +94,8 @@ private static long measureCommand() throws Exception { for (int n = 0; n <= TOTAL_OPERATIONS; n++) { RedisOutputStream out = new RedisOutputStream(new ByteArrayOutputStream(8192)); long start = System.nanoTime(); - Protocol.sendCommand(out, Protocol.Command.SET, KEY, VAL); +// Protocol.sendCommand(out, Protocol.Command.SET, KEY, VAL); + Protocol.sendCommand(out, new CommandArguments(Protocol.Command.SET).key(KEY).add(VAL)); duration += (System.nanoTime() - start); } diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/SafeEncoderBenchmark.java similarity index 95% rename from src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java rename to src/test/java/redis/clients/jedis/benchmark/SafeEncoderBenchmark.java index 400655acee..cd1a762323 100644 --- a/src/test/java/redis/clients/jedis/tests/benchmark/SafeEncoderBenchmark.java +++ b/src/test/java/redis/clients/jedis/benchmark/SafeEncoderBenchmark.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.benchmark; +package redis.clients.jedis.benchmark; import java.io.IOException; import java.net.UnknownHostException; @@ -7,6 +7,7 @@ import redis.clients.jedis.util.SafeEncoder; public class SafeEncoderBenchmark { + private static final int TOTAL_OPERATIONS = 10000000; public static void main(String[] args) throws UnknownHostException, IOException { @@ -32,4 +33,4 @@ public static void main(String[] args) throws UnknownHostException, IOException System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops to build Strings"); } -} \ No newline at end of file +} diff --git a/src/test/java/redis/clients/jedis/benchmark/ShardedBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/ShardedBenchmark.java new file mode 100644 index 0000000000..633241c933 --- /dev/null +++ b/src/test/java/redis/clients/jedis/benchmark/ShardedBenchmark.java @@ -0,0 +1,50 @@ +//package redis.clients.jedis.benchmark; +// +//import java.io.IOException; +//import java.net.UnknownHostException; +//import java.util.ArrayList; +//import java.util.Calendar; +//import java.util.Collection; +//import java.util.List; +// +//import redis.clients.jedis.HostAndPort; +//import redis.clients.jedis.HostAndPorts; +//import redis.clients.jedis.Jedis; +//import redis.clients.jedis.JedisShardInfo; +//import redis.clients.jedis.ShardedJedis; +// +//public class ShardedBenchmark { +// +// private static HostAndPort hnp1 = HostAndPorts.getRedisServers().get(0); +// private static HostAndPort hnp2 = HostAndPorts.getRedisServers().get(1); +// private static final int TOTAL_OPERATIONS = 100000; +// +// public static void main(String[] args) throws UnknownHostException, IOException { +// List shards = new ArrayList(); +// JedisShardInfo shard = new JedisShardInfo(hnp1); +// shard.setPassword("foobared"); +// shards.add(shard); +// shard = new JedisShardInfo(hnp2); +// shard.setPassword("foobared"); +// shards.add(shard); +// ShardedJedis jedis = new ShardedJedis(shards); +// Collection allShards = jedis.getAllShards(); +// for (Jedis j : allShards) { +// j.flushAll(); +// } +// +// long begin = Calendar.getInstance().getTimeInMillis(); +// +// for (int n = 0; n <= TOTAL_OPERATIONS; n++) { +// String key = "foo" + n; +// jedis.set(key, "bar" + n); +// jedis.get(key); +// } +// +// long elapsed = Calendar.getInstance().getTimeInMillis() - begin; +// +// jedis.disconnect(); +// +// System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); +// } +//} diff --git a/src/test/java/redis/clients/jedis/benchmark/ShardingBenchmark.java b/src/test/java/redis/clients/jedis/benchmark/ShardingBenchmark.java new file mode 100644 index 0000000000..ea3c490bcc --- /dev/null +++ b/src/test/java/redis/clients/jedis/benchmark/ShardingBenchmark.java @@ -0,0 +1,36 @@ +package redis.clients.jedis.benchmark; + +import java.io.IOException; +import java.net.UnknownHostException; +import java.util.Arrays; +import java.util.Calendar; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.HostAndPorts; +import redis.clients.jedis.JedisSharding; + +public class ShardingBenchmark { + + private static HostAndPort hnp1 = HostAndPorts.getRedisServers().get(0); + private static HostAndPort hnp2 = HostAndPorts.getRedisServers().get(1); + private static final int TOTAL_OPERATIONS = 100000; + + public static void main(String[] args) throws UnknownHostException, IOException { + try (JedisSharding jedis = new JedisSharding(Arrays.asList(hnp1, hnp2), + DefaultJedisClientConfig.builder().password("foobared").build())) { + + long begin = Calendar.getInstance().getTimeInMillis(); + + for (int n = 0; n <= TOTAL_OPERATIONS; n++) { + String key = "foo" + n; + jedis.set(key, "bar" + n); + jedis.get(key); + } + + long elapsed = Calendar.getInstance().getTimeInMillis() - begin; + + System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); + } + } +} diff --git a/src/test/java/redis/clients/jedis/tests/collections/JedisByteHashMapTest.java b/src/test/java/redis/clients/jedis/collections/JedisByteHashMapTest.java similarity index 98% rename from src/test/java/redis/clients/jedis/tests/collections/JedisByteHashMapTest.java rename to src/test/java/redis/clients/jedis/collections/JedisByteHashMapTest.java index a4d0c3af53..40f493ece6 100644 --- a/src/test/java/redis/clients/jedis/tests/collections/JedisByteHashMapTest.java +++ b/src/test/java/redis/clients/jedis/collections/JedisByteHashMapTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.collections; +package redis.clients.jedis.collections; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; diff --git a/src/test/java/redis/clients/jedis/tests/collections/SetFromListTest.java b/src/test/java/redis/clients/jedis/collections/SetFromListTest.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/collections/SetFromListTest.java rename to src/test/java/redis/clients/jedis/collections/SetFromListTest.java index 152cfb6238..99beec911d 100644 --- a/src/test/java/redis/clients/jedis/tests/collections/SetFromListTest.java +++ b/src/test/java/redis/clients/jedis/collections/SetFromListTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.collections; +package redis.clients.jedis.collections; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -25,7 +25,8 @@ public class SetFromListTest { @BeforeClass public static void beforeClass() throws Exception { - Class clazz = Class.forName("redis.clients.jedis.BinaryJedis$SetFromList"); +// Class clazz = Class.forName("redis.clients.jedis.BinaryJedis$SetFromList"); + Class clazz = Class.forName("redis.clients.jedis.BuilderFactory$SetFromList"); method = clazz.getDeclaredMethod("of", List.class); method.setAccessible(true); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/AccessControlListCommandsTest.java similarity index 94% rename from src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/AccessControlListCommandsTest.java index 59d977a9b0..af22802acb 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AccessControlListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/AccessControlListCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.hamcrest.CoreMatchers.containsString; import static org.junit.Assert.*; @@ -7,18 +7,18 @@ import org.junit.BeforeClass; import org.junit.Test; -import redis.clients.jedis.AccessControlUser; import redis.clients.jedis.Jedis; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisAccessControlException; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.tests.utils.RedisVersionUtil; +import redis.clients.jedis.resps.AccessControlUser; +import redis.clients.jedis.util.RedisVersionUtil; import redis.clients.jedis.util.SafeEncoder; /** * TODO: properly define and test exceptions */ -public class AccessControlListCommandsTest extends JedisCommandTestBase { +public class AccessControlListCommandsTest extends JedisCommandsTestBase { public static String USER_YYY = "yyy"; public static String USER_ZZZ = "zzz"; @@ -75,8 +75,6 @@ public void aclGetUser() { // get default user information AccessControlUser userInfo = jedis.aclGetUser("default"); - System.err.println("userInfo.getFlags(): " + userInfo.getFlags()); - assertEquals(4, userInfo.getFlags().size()); assertEquals(1, userInfo.getPassword().size()); assertEquals("+@all", userInfo.getCommands()); @@ -320,7 +318,7 @@ public void aclCatTest() { @Test public void aclLogTest() { - jedis.aclLog("RESET"); + jedis.aclLogReset(); assertTrue(jedis.aclLog().isEmpty()); // create new user and cconnect @@ -346,7 +344,7 @@ public void aclLogTest() { assertEquals("get", jedis.aclLog().get(0).getObject()); // Capture similar event - jedis.aclLog("RESET"); + jedis.aclLogReset(); assertTrue(jedis.aclLog().isEmpty()); jedis.auth("antirez", "foo"); @@ -381,7 +379,7 @@ public void aclLogTest() { assertEquals("somekeynotallowed", jedis.aclLog().get(0).getObject()); assertEquals("key", jedis.aclLog().get(0).getReason()); - jedis.aclLog("RESET"); + jedis.aclLogReset(); assertTrue(jedis.aclLog().isEmpty()); jedis.auth("antirez", "foo"); @@ -422,9 +420,10 @@ public void aclLogTest() { // Binary tests assertEquals("Number of log messages ", 3, jedis.aclLogBinary().size()); assertEquals("Number of log messages ", 2, jedis.aclLogBinary(2).size()); - byte[] status = jedis.aclLog("RESET".getBytes()); - assertNotNull(status); - assertTrue(jedis.aclLog().isEmpty()); + + // RESET + String status = jedis.aclLogReset(); + assertEquals(status, "OK"); jedis.aclDelUser("antirez"); } @@ -432,11 +431,19 @@ public void aclLogTest() { @Test public void aclGenPass() { assertNotNull(jedis.aclGenPass()); + + // bit length case + assertNotNull(jedis.aclGenPassBinary(16)); + assertNotNull(jedis.aclGenPassBinary(32)); } @Test public void aclGenPassBinary() { assertNotNull(jedis.aclGenPassBinary()); + + // bit length case + assertNotNull(jedis.aclGenPassBinary(16)); + assertNotNull(jedis.aclGenPassBinary(32)); } @Test @@ -456,6 +463,14 @@ public void aclBinaryCommandsTest() { assertThat(userInfo.getCommands(), containsString("+debug|digest")); jedis.aclDelUser(USER_ZZZ.getBytes()); + + jedis.aclSetUser("TEST_USER".getBytes()); + jedis.aclSetUser("ANOTHER_TEST_USER".getBytes()); + jedis.aclSetUser("MORE_TEST_USERS".getBytes()); + assertEquals(3L, jedis.aclDelUser( + "TEST_USER".getBytes(), + "ANOTHER_TEST_USER".getBytes(), + "MORE_TEST_USERS".getBytes())); } @Test diff --git a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/AllKindOfValuesCommandsTest.java similarity index 91% rename from src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/AllKindOfValuesCommandsTest.java index aecc65a8d2..23ca33a74f 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/AllKindOfValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/AllKindOfValuesCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -7,6 +7,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; + import static redis.clients.jedis.Protocol.Command.BLPOP; import static redis.clients.jedis.Protocol.Command.HGETALL; import static redis.clients.jedis.Protocol.Command.GET; @@ -15,11 +16,11 @@ import static redis.clients.jedis.Protocol.Command.RPUSH; import static redis.clients.jedis.Protocol.Command.SET; import static redis.clients.jedis.Protocol.Command.XINFO; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; import static redis.clients.jedis.params.SetParams.setParams; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertCollectionContains; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContains; import java.util.ArrayList; import java.util.Arrays; @@ -27,24 +28,21 @@ import java.util.HashMap; import java.util.HashSet; import java.util.List; -import java.util.Map; import java.util.Set; - import org.junit.Test; + import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; - -import redis.clients.jedis.Protocol.Keyword; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; import redis.clients.jedis.StreamEntryID; import redis.clients.jedis.args.FlushMode; import redis.clients.jedis.params.RestoreParams; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.HostAndPorts; import redis.clients.jedis.util.SafeEncoder; import redis.clients.jedis.exceptions.JedisDataException; -public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { +public class AllKindOfValuesCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x0A }; final byte[] bfoo2 = { 0x01, 0x02, 0x03, 0x04, 0x0B }; @@ -61,7 +59,7 @@ public class AllKindOfValuesCommandsTest extends JedisCommandTestBase { final byte[] bnx = { 0x6E, 0x78 }; final byte[] bex = { 0x65, 0x78 }; final int expireSeconds = 2; - private static final HostAndPort lfuHnp = HostAndPortUtil.getRedisServers().get(7); + private static final HostAndPort lfuHnp = HostAndPorts.getRedisServers().get(7); @Test public void ping() { @@ -590,19 +588,14 @@ public void dumpAndRestore() { } @Test - public void restoreReplace() { + public void restoreParams() { // take a separate instance Jedis jedis2 = new Jedis(hnp.getHost(), 6380, 500); jedis2.auth("foobared"); jedis2.flushAll(); jedis2.set("foo", "bar"); - - Map map = new HashMap<>(); - map.put("a", "A"); - map.put("b", "B"); - - jedis.hset("from", map); + jedis.set("from", "a"); byte[] serialized = jedis.dump("from"); try { @@ -611,27 +604,8 @@ public void restoreReplace() { } catch (JedisDataException e) { // should be here } - assertEquals("bar", jedis2.get("foo")); - - jedis2.restoreReplace("foo", 0, serialized); - assertEquals(map, jedis2.hgetAll("foo")); - - jedis2.close(); - } - - @Test - public void restoreParams() { - // take a separate instance - Jedis jedis2 = new Jedis(hnp.getHost(), 6380, 500); - jedis2.auth("foobared"); - jedis2.flushAll(); - - jedis2.set("foo", "bar"); - jedis.set("from", "a"); - byte[] serialized = jedis.dump("from"); - try { - jedis2.restore("foo", 0, serialized, null); + jedis2.restore("foo", 0, serialized, RestoreParams.restoreParams()); fail("Simple restore on a existing key should fail"); } catch (JedisDataException e) { // should be here @@ -891,14 +865,11 @@ private ScanResult scanCompletely(String cursor) { @Test public void setNxExAndGet() { - String status = jedis.set("hello", "world", setParams().nx().ex(expireSeconds)); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); - String value = jedis.get("hello"); - assertEquals("world", value); + assertEquals("OK", jedis.set("hello", "world", setParams().nx().ex(expireSeconds))); + assertEquals("world", jedis.get("hello")); - jedis.set("hello", "bar", setParams().nx().ex(expireSeconds)); - value = jedis.get("hello"); - assertEquals("world", value); + assertNull(jedis.set("hello", "bar", setParams().nx().ex(expireSeconds))); + assertEquals("world", jedis.get("hello")); long ttl = jedis.ttl("hello"); assertTrue(ttl > 0 && ttl <= expireSeconds); @@ -907,14 +878,11 @@ public void setNxExAndGet() { byte[] bworld = { 0x77, 0x6F, 0x72, 0x6C, 0x64 }; byte[] bhello = { 0x68, 0x65, 0x6C, 0x6C, 0x6F }; - String bstatus = jedis.set(bworld, bhello, setParams().nx().ex(expireSeconds)); - assertTrue(Keyword.OK.name().equalsIgnoreCase(bstatus)); - byte[] bvalue = jedis.get(bworld); - assertArrayEquals(bhello, bvalue); + assertEquals("OK", jedis.set(bworld, bhello, setParams().nx().ex(expireSeconds))); + assertArrayEquals(bhello, jedis.get(bworld)); - jedis.set(bworld, bbar, setParams().nx().ex(expireSeconds)); - bvalue = jedis.get(bworld); - assertArrayEquals(bhello, bvalue); + assertNull(jedis.set(bworld, bbar, setParams().nx().ex(expireSeconds))); + assertArrayEquals(bhello, jedis.get(bworld)); long bttl = jedis.ttl(bworld); assertTrue(bttl > 0 && bttl <= expireSeconds); @@ -922,17 +890,15 @@ public void setNxExAndGet() { @Test public void setGetOptionTest() { - String status = jedis.set("hello", "world"); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + assertEquals("OK", jedis.set("hello", "world")); - String oldValue = jedis.set("hello", "jedis", setParams().get()); - assertEquals("world", oldValue); + // GET old value + assertEquals("world", jedis.set("hello", "jedis", setParams().get())); - String newValue = jedis.get("hello"); - assertEquals("jedis", newValue); + assertEquals("jedis", jedis.get("hello")); - String nullValue = jedis.set("key", "value", setParams().get()); - assertNull(nullValue); + // GET null value + assertNull(jedis.set("key", "value", setParams().get())); } @Test @@ -1000,7 +966,6 @@ public void encodeCompleteResponse() { assertEquals(4, encodeObj.size()); assertTrue(encodeObj.contains("foo")); assertTrue(encodeObj.contains("foo2")); - } @Test diff --git a/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/BinaryValuesCommandsTest.java similarity index 85% rename from src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/BinaryValuesCommandsTest.java index 863d1807d9..a592326a81 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/BinaryValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/BinaryValuesCommandsTest.java @@ -1,30 +1,30 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; + import static redis.clients.jedis.Protocol.Command.BLPOP; import static redis.clients.jedis.Protocol.Command.GET; import static redis.clients.jedis.Protocol.Command.LRANGE; import static redis.clients.jedis.Protocol.Command.RPUSH; import static redis.clients.jedis.Protocol.Command.SET; import static redis.clients.jedis.params.SetParams.setParams; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.Protocol.Keyword; +import redis.clients.jedis.Protocol; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.params.GetExParams; import redis.clients.jedis.util.SafeEncoder; -public class BinaryValuesCommandsTest extends JedisCommandTestBase { +public class BinaryValuesCommandsTest extends JedisCommandsTestBase { byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; byte[] bxx = { 0x78, 0x78 }; @@ -48,8 +48,7 @@ public void startUp() { @Test public void setAndGet() { - String status = jedis.set(bfoo, binaryValue); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + assertEquals("OK", jedis.set(bfoo, binaryValue)); assertArrayEquals(binaryValue, jedis.get(bfoo)); @@ -58,8 +57,8 @@ public void setAndGet() { @Test public void setNxExAndGet() { - String status = jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds)); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + assertArrayEquals(binaryValue, jedis.get(bfoo)); assertNull(jedis.get(bbar)); @@ -67,8 +66,7 @@ public void setNxExAndGet() { @Test public void setIfNotExistAndGet() { - String status = jedis.set(bfoo, binaryValue); - assertEquals(Keyword.OK.name(), status); + assertEquals("OK", jedis.set(bfoo, binaryValue)); // nx should fail if value exists assertNull(jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); @@ -79,14 +77,11 @@ public void setIfNotExistAndGet() { @Test public void setIfExistAndGet() { - String status = jedis.set(bfoo, binaryValue); - assertEquals(Keyword.OK.name(), status); + assertEquals("OK", jedis.set(bfoo, binaryValue)); // nx should fail if value exists - status = jedis.set(bfoo, binaryValue, setParams().xx().ex(expireSeconds)); - assertEquals(Keyword.OK.name(), status); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().xx().ex(expireSeconds))); - byte[] value = jedis.get(bfoo); - assertArrayEquals(binaryValue, value); + assertArrayEquals(binaryValue, jedis.get(bfoo)); assertNull(jedis.get(bbar)); } @@ -99,22 +94,22 @@ public void setFailIfNotExistAndGet() { @Test public void setAndExpireMillis() { - assertEquals(Keyword.OK.name(), jedis.set(bfoo, binaryValue, setParams().nx().px(expireMillis))); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().px(expireMillis))); long ttl = jedis.ttl(bfoo); assertTrue(ttl > 0 && ttl <= expireSeconds); } @Test public void setAndExpire() { - assertEquals(Keyword.OK.name(), jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); long ttl = jedis.ttl(bfoo); assertTrue(ttl > 0 && ttl <= expireSeconds); } @Test public void setAndKeepttl() { - assertEquals(Keyword.OK.name(), jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); - assertEquals(Keyword.OK.name(), jedis.set(bfoo, binaryValue, setParams().keepttl())); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().keepttl())); long ttl = jedis.ttl(bfoo); assertTrue(0 < ttl && ttl <= expireSeconds); jedis.set(bfoo, binaryValue); @@ -124,7 +119,7 @@ public void setAndKeepttl() { @Test public void setAndPxat() { - assertEquals(Keyword.OK.name(), jedis.set(bfoo, binaryValue, + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().pxAt(System.currentTimeMillis() + expireMillis))); long ttl = jedis.ttl(bfoo); assertTrue(ttl > 0 && ttl <= expireSeconds); @@ -132,7 +127,7 @@ public void setAndPxat() { @Test public void setAndExat() { - assertEquals(Keyword.OK.name(), jedis.set(bfoo, binaryValue, + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().exAt(System.currentTimeMillis() / 1000 + expireSeconds))); long ttl = jedis.ttl(bfoo); assertTrue(ttl > 0 && ttl <= expireSeconds); @@ -146,7 +141,7 @@ public void getSet() { @Test public void getDel() { - assertEquals(Keyword.OK.name(), jedis.set(bfoo, bbar)); + assertEquals("OK", jedis.set(bfoo, bbar)); assertArrayEquals(bbar, jedis.getDel(bfoo)); @@ -213,15 +208,14 @@ public void setnx() { @Test public void setex() { - String status = jedis.setex(bfoo, 20, binaryValue); - assertEquals(Keyword.OK.name(), status); + assertEquals("OK", jedis.setex(bfoo, 20, binaryValue)); long ttl = jedis.ttl(bfoo); assertTrue(ttl > 0 && ttl <= 20); } @Test public void mset() { - assertEquals(Keyword.OK.name(), jedis.mset(bfoo, binaryValue, bbar, bfoo)); + assertEquals("OK", jedis.mset(bfoo, binaryValue, bbar, bfoo)); assertArrayEquals(binaryValue, jedis.get(bfoo)); assertArrayEquals(bfoo, jedis.get(bbar)); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/BitCommandsTest.java similarity index 97% rename from src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/BitCommandsTest.java index 6b1ec8c6bc..64130ebd17 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/BitCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/BitCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -6,17 +6,16 @@ import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; +import java.util.List; import org.junit.Test; -import redis.clients.jedis.BitOP; -import redis.clients.jedis.BitPosParams; import redis.clients.jedis.Protocol; +import redis.clients.jedis.args.BitOP; import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.BitPosParams; import redis.clients.jedis.util.SafeEncoder; -import java.util.List; - -public class BitCommandsTest extends JedisCommandTestBase { +public class BitCommandsTest extends JedisCommandsTestBase { @Test public void setAndgetbit() { diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ClientCommandsTest.java similarity index 92% rename from src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ClientCommandsTest.java index ec045a916d..8fb3b9edad 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClientCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ClientCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -20,14 +20,13 @@ import org.junit.Before; import org.junit.Test; -import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.args.ClientType; import redis.clients.jedis.args.UnblockType; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.params.ClientKillParams; -public class ClientCommandsTest extends JedisCommandTestBase { +public class ClientCommandsTest extends JedisCommandsTestBase { private final String clientName = "fancy_jedis_name"; private final Pattern pattern = Pattern.compile("\\bname=" + clientName + "\\b"); @@ -91,6 +90,7 @@ public void clientIdReconnect() { long clientIdInitial = client.clientId(); client.disconnect(); client.connect(); + client.auth("foobared"); long clientIdAfterReconnect = client.clientId(); assertTrue(clientIdInitial < clientIdAfterReconnect); @@ -143,6 +143,13 @@ public void killTypeNormal() { assertDisconnected(client); } + @Test + public void killTypeNormal2() { + long clients = jedis.clientKill(new ClientKillParams().type(ClientType.NORMAL)); + assertTrue(clients > 0); + assertDisconnected(client); + } + @Test public void killSkipmeNo() { jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.NO)); @@ -150,6 +157,13 @@ public void killSkipmeNo() { assertDisconnected(jedis); } + @Test + public void killSkipmeNo2() { + jedis.clientKill(new ClientKillParams().type(ClientType.NORMAL).skipMe(SkipMe.NO)); + assertDisconnected(client); + assertDisconnected(jedis); + } + @Test public void killSkipmeYesNo() { jedis.clientKill(new ClientKillParams().type(Type.NORMAL).skipMe(SkipMe.YES)); @@ -209,7 +223,8 @@ public void killAddrIpPort() { Matcher matcher = Pattern.compile("\\baddr=(\\S+)\\b").matcher(info); matcher.find(); String addr = matcher.group(1); - String[] hp = HostAndPort.extractParts(addr); + int lastColon = addr.lastIndexOf(":"); + String[] hp = new String[]{addr.substring(0, lastColon), addr.substring(lastColon + 1)}; assertEquals(1, jedis.clientKill(new ClientKillParams().addr(hp[0], Integer.parseInt(hp[1])))); diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterBinaryValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ClusterBinaryValuesCommandsTest.java similarity index 98% rename from src/test/java/redis/clients/jedis/tests/commands/ClusterBinaryValuesCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ClusterBinaryValuesCommandsTest.java index 09ad266221..b53cb6f751 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterBinaryValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ClusterBinaryValuesCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ClusterCommandsTest.java similarity index 86% rename from src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ClusterCommandsTest.java index eff25dde72..e104f49475 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ClusterCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -14,17 +14,16 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ClusterReset; import redis.clients.jedis.args.ClusterResetType; -import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.utils.JedisClusterTestUtil; +import redis.clients.jedis.HostAndPorts; +import redis.clients.jedis.util.JedisClusterTestUtil; public class ClusterCommandsTest { private static Jedis node1; private static Jedis node2; - private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); - private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); + private static HostAndPort nodeInfo1 = HostAndPorts.getClusterServers().get(0); + private static HostAndPort nodeInfo2 = HostAndPorts.getClusterServers().get(1); @Before public void setUp() throws Exception { @@ -46,15 +45,21 @@ public void tearDown() { @AfterClass public static void removeSlots() throws InterruptedException { - node1.clusterReset(ClusterReset.SOFT); - node2.clusterReset(ClusterReset.SOFT); + try (Jedis node = new Jedis(nodeInfo1)) { + node.auth("cluster"); + node.clusterReset(ClusterResetType.SOFT); + } + try (Jedis node = new Jedis(nodeInfo2)) { + node.auth("cluster"); + node.clusterReset(ClusterResetType.SOFT); + } } @Test public void testClusterSoftReset() { node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); assertTrue(node1.clusterNodes().split("\n").length > 1); - node1.clusterReset(ClusterReset.SOFT); + node1.clusterReset(ClusterResetType.SOFT); assertEquals(1, node1.clusterNodes().split("\n").length); } @@ -69,7 +74,7 @@ public void testClusterSoftReset2() { @Test public void testClusterHardReset() { String nodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes()); - node1.clusterReset(ClusterReset.HARD); + node1.clusterReset(ClusterResetType.HARD); String newNodeId = JedisClusterTestUtil.getNodeId(node1.clusterNodes()); assertNotEquals(nodeId, newNodeId); } @@ -156,8 +161,7 @@ public void clusterSetSlotMigrating() { @Test public void clusterSlots() { // please see cluster slot output format from below commit - // @see: - // https://github.com/antirez/redis/commit/e14829de3025ffb0d3294e5e5a1553afd9f10b60 + // @see: https://github.com/antirez/redis/commit/e14829de3025ffb0d3294e5e5a1553afd9f10b60 String status = node1.clusterAddSlots(3000, 3001, 3002); assertEquals("OK", status); status = node2.clusterAddSlots(4000, 4001, 4002); diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterJedisCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/jedis/ClusterJedisCommandsTestBase.java similarity index 68% rename from src/test/java/redis/clients/jedis/tests/commands/ClusterJedisCommandsTestBase.java rename to src/test/java/redis/clients/jedis/commands/jedis/ClusterJedisCommandsTestBase.java index bb08d8706b..bfdbf08c62 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterJedisCommandsTestBase.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ClusterJedisCommandsTestBase.java @@ -1,4 +1,6 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; + +import static redis.clients.jedis.Protocol.CLUSTER_HASHSLOTS; import java.util.HashSet; import java.util.Set; @@ -7,11 +9,11 @@ import org.junit.AfterClass; import org.junit.Before; +import redis.clients.jedis.DefaultJedisClientConfig; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisCluster; -import redis.clients.jedis.JedisPoolConfig; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.UnifiedJedis; +import redis.clients.jedis.HostAndPorts; import redis.clients.jedis.util.JedisClusterCRC16; public abstract class ClusterJedisCommandsTestBase { @@ -19,11 +21,12 @@ public abstract class ClusterJedisCommandsTestBase { private static Jedis node2; private static Jedis node3; - private HostAndPort nodeInfo1 = HostAndPortUtil.getClusterServers().get(0); - private HostAndPort nodeInfo2 = HostAndPortUtil.getClusterServers().get(1); - private HostAndPort nodeInfo3 = HostAndPortUtil.getClusterServers().get(2); + private HostAndPort nodeInfo1 = HostAndPorts.getClusterServers().get(0); + private HostAndPort nodeInfo2 = HostAndPorts.getClusterServers().get(1); + private HostAndPort nodeInfo3 = HostAndPorts.getClusterServers().get(2); private final Set jedisClusterNode = new HashSet<>(); - JedisCluster jedisCluster; +// JedisCluster jedisCluster; + UnifiedJedis jedisCluster; @Before public void setUp() throws InterruptedException { @@ -46,11 +49,13 @@ public void setUp() throws InterruptedException { node1.clusterMeet("127.0.0.1", nodeInfo3.getPort()); // split available slots across the three nodes - int slotsPerNode = JedisCluster.HASHSLOTS / 3; +// int slotsPerNode = JedisCluster.HASHSLOTS / 3; + int slotsPerNode = CLUSTER_HASHSLOTS / 3; int[] node1Slots = new int[slotsPerNode]; int[] node2Slots = new int[slotsPerNode + 1]; int[] node3Slots = new int[slotsPerNode]; - for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) { +// for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < JedisCluster.HASHSLOTS; i++) { + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < CLUSTER_HASHSLOTS; i++) { if (i < slotsPerNode) { node1Slots[slot1++] = i; } else if (i > slotsPerNode * 2) { @@ -67,8 +72,8 @@ public void setUp() throws InterruptedException { waitForClusterReady(); jedisClusterNode.add(new HostAndPort("127.0.0.1", 7379)); - jedisCluster = new JedisCluster(jedisClusterNode, 2000, 2000, 5, "cluster", - new JedisPoolConfig()); +// jedisCluster = new JedisCluster(jedisClusterNode, 2000, 2000, 5, "cluster", new JedisPoolConfig()); + jedisCluster = new UnifiedJedis(jedisClusterNode, DefaultJedisClientConfig.builder().password("cluster").build(), 5); } @@ -85,8 +90,10 @@ public static void cleanUp() { @After public void tearDown() { // clear all slots - int[] slotsToDelete = new int[JedisCluster.HASHSLOTS]; - for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { +// int[] slotsToDelete = new int[JedisCluster.HASHSLOTS]; + int[] slotsToDelete = new int[CLUSTER_HASHSLOTS]; +// for (int i = 0; i < JedisCluster.HASHSLOTS; i++) { + for (int i = 0; i < CLUSTER_HASHSLOTS; i++) { slotsToDelete[i] = i; } node1.clusterDelSlots(slotsToDelete); diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ClusterScriptingCommandsTest.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/commands/ClusterScriptingCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ClusterScriptingCommandsTest.java index 47c293e34a..3da49f3682 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ClusterScriptingCommandsTest.java @@ -1,9 +1,10 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; +import java.util.Collections; import java.util.List; import org.junit.Test; @@ -88,9 +89,6 @@ public void testBinaryScriptExists() { byte[] byteKey = "key1".getBytes(); byte[] sha1 = jedisCluster.scriptLoad("return redis.call('get','foo')".getBytes(), byteKey); byte[][] arraySha1 = { sha1 }; - Long result = 1L; - List listResult = new ArrayList<>(); - listResult.add(result); - assertEquals(listResult, jedisCluster.scriptExists(byteKey, arraySha1)); + assertEquals(Collections.singletonList(Boolean.TRUE), jedisCluster.scriptExists(byteKey, arraySha1)); } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ClusterValuesCommandsTest.java similarity index 84% rename from src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ClusterValuesCommandsTest.java index 40a5eb6d49..ffdf59c597 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ClusterValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ClusterValuesCommandsTest.java @@ -1,6 +1,5 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; -import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import org.junit.Test; diff --git a/src/test/java/redis/clients/jedis/commands/jedis/ConnectionHandlingCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ConnectionHandlingCommandsTest.java new file mode 100644 index 0000000000..7e2ab209db --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/jedis/ConnectionHandlingCommandsTest.java @@ -0,0 +1,20 @@ +package redis.clients.jedis.commands.jedis; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.HostAndPorts; + +public class ConnectionHandlingCommandsTest { + + private static HostAndPort hnp = HostAndPorts.getRedisServers().get(0); + + @Test + public void quit() { + Jedis jedis = new Jedis(hnp); + assertEquals("OK", jedis.quit()); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ControlCommandsTest.java similarity index 90% rename from src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ControlCommandsTest.java index 0e4868bb6e..411fa6a331 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ControlCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ControlCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -16,18 +16,18 @@ import org.junit.Test; -import redis.clients.jedis.DebugParams; import redis.clients.jedis.DefaultJedisClientConfig; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisMonitor; import redis.clients.jedis.Protocol; import redis.clients.jedis.args.ClientPauseMode; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.tests.HostAndPortUtil; -import redis.clients.jedis.tests.utils.AssertUtil; +import redis.clients.jedis.HostAndPorts; +import redis.clients.jedis.util.AssertUtil; import redis.clients.jedis.util.SafeEncoder; -public class ControlCommandsTest extends JedisCommandTestBase { +public class ControlCommandsTest extends JedisCommandsTestBase { + @Test public void save() { try { @@ -93,7 +93,7 @@ public void readwrite() { @Test public void roleMaster() { - try (Jedis master = new Jedis(HostAndPortUtil.getRedisServers().get(0), + try (Jedis master = new Jedis(HostAndPorts.getRedisServers().get(0), DefaultJedisClientConfig.builder().password("foobared").build())) { List role = master.role(); @@ -111,19 +111,19 @@ public void roleMaster() { @Test public void roleSlave() { - try (Jedis slave = new Jedis(HostAndPortUtil.getRedisServers().get(4), + try (Jedis slave = new Jedis(HostAndPorts.getRedisServers().get(4), DefaultJedisClientConfig.builder().password("foobared").build())) { List role = slave.role(); assertEquals("slave", role.get(0)); - assertEquals((long) HostAndPortUtil.getRedisServers().get(0).getPort(), role.get(2)); + assertEquals((long) HostAndPorts.getRedisServers().get(0).getPort(), role.get(2)); assertEquals("connected", role.get(3)); assertTrue(role.get(4) instanceof Long); // binary List brole = slave.roleBinary(); assertArrayEquals("slave".getBytes(), (byte[]) brole.get(0)); - assertEquals((long) HostAndPortUtil.getRedisServers().get(0).getPort(), brole.get(2)); + assertEquals((long) HostAndPorts.getRedisServers().get(0).getPort(), brole.get(2)); assertArrayEquals("connected".getBytes(), (byte[]) brole.get(3)); assertTrue(brole.get(4) instanceof Long); } @@ -131,7 +131,7 @@ public void roleSlave() { @Test public void roleSentinel() { - try (Jedis sentinel = new Jedis(HostAndPortUtil.getSentinelServers().get(0))) { + try (Jedis sentinel = new Jedis(HostAndPorts.getSentinelServers().get(0))) { List role = sentinel.role(); assertEquals("sentinel", role.get(0)); @@ -205,24 +205,6 @@ public void configGetSetBinary() { assertEquals("OK", jedis.configSet(maxmemory, memory)); } - @Test - public void configGetSetBinary2() { - byte[] maxmemory = SafeEncoder.encode("maxmemory"); - List info = jedis.configGet(maxmemory); - assertArrayEquals(maxmemory, info.get(0)); - byte[] memory = info.get(1); - assertEquals("OK", jedis.configSetBinary(maxmemory, memory)); - } - - @Test - public void debug() { - jedis.set("foo", "bar"); - String resp = jedis.debug(DebugParams.OBJECT("foo")); - assertNotNull(resp); - resp = jedis.debug(DebugParams.RELOAD()); - assertNotNull(resp); - } - @Test public void waitReplicas() { assertEquals(1, jedis.waitReplicas(1, 100)); diff --git a/src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/FailoverCommandsTest.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/FailoverCommandsTest.java index f50b5095e6..08086e636b 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/FailoverCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/FailoverCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import org.junit.After; import org.junit.Before; @@ -9,7 +9,7 @@ import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.params.FailoverParams; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.HostAndPorts; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; @@ -26,8 +26,8 @@ public class FailoverCommandsTest { @BeforeClass public static void setUp() { - node1 = HostAndPortUtil.getRedisServers().get(9); - node2 = HostAndPortUtil.getRedisServers().get(10); + node1 = HostAndPorts.getRedisServers().get(9); + node2 = HostAndPorts.getRedisServers().get(10); } @Before @@ -67,7 +67,7 @@ public void failoverMaster() throws InterruptedException { // try (Jedis master = new Jedis(masterAddress)) { assertEquals("OK", master.failover()); - Thread.sleep(20); // allow some time to failover; + Thread.sleep(120); // allow some time to failover; // not too much as everything is happening in same machine assertEquals("slave", master.role().get(0)); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/GeoCommandsTest.java similarity index 95% rename from src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/GeoCommandsTest.java index 8a7d83c538..3702a89044 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/GeoCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/GeoCommandsTest.java @@ -1,28 +1,25 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Set; - import org.junit.Test; import redis.clients.jedis.GeoCoordinate; -import redis.clients.jedis.GeoRadiusResponse; -import redis.clients.jedis.GeoUnit; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.resps.GeoRadiusResponse; import redis.clients.jedis.params.GeoAddParams; import redis.clients.jedis.params.GeoRadiusParam; import redis.clients.jedis.params.GeoRadiusStoreParam; import redis.clients.jedis.util.SafeEncoder; -public class GeoCommandsTest extends JedisCommandTestBase { +public class GeoCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bA = { 0x0A }; final byte[] bB = { 0x0B }; @@ -208,7 +205,7 @@ public void georadiusStore() { GeoRadiusParam.geoRadiusParam(), GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore")); assertEquals(2, size); - Set expected = new LinkedHashSet<>(); + List expected = new ArrayList<>(); expected.add("Palermo"); expected.add("Catania"); assertEquals(expected, jedis.zrange("SicilyStore", 0, -1)); @@ -292,10 +289,10 @@ public void georadiusStoreBinary() { GeoRadiusParam.geoRadiusParam(), GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore")); assertEquals(2, size); - Set bexpected = new LinkedHashSet<>(); + List bexpected = new ArrayList<>(); bexpected.add(bA); bexpected.add(bB); - assertByteArraySetEquals(bexpected, jedis.zrange("SicilyStore".getBytes(), 0, -1)); + assertByteArrayListEquals(bexpected, jedis.zrange("SicilyStore".getBytes(), 0, -1)); } @Test @@ -368,7 +365,7 @@ public void georadiusByMemberStore() { GeoRadiusParam.geoRadiusParam(), GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore")); assertEquals(2, size); - Set expected = new LinkedHashSet<>(); + List expected = new ArrayList<>(); expected.add("Agrigento"); expected.add("Palermo"); assertEquals(expected, jedis.zrange("SicilyStore", 0, -1)); @@ -436,10 +433,10 @@ public void georadiusByMemberStoreBinary() { assertEquals(2, jedis.georadiusByMemberStore(bfoo, bA, 100, GeoUnit.KM, GeoRadiusParam.geoRadiusParam(), GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore"))); - Set bexpected = new LinkedHashSet<>(); + List bexpected = new ArrayList<>(); bexpected.add(bA); bexpected.add(bB); - assertByteArraySetEquals(bexpected, jedis.zrange("SicilyStore".getBytes(), 0, -1)); + assertByteArrayListEquals(bexpected, jedis.zrange("SicilyStore".getBytes(), 0, -1)); } @Test @@ -483,9 +480,4 @@ private void prepareGeoData() { assertEquals(3, jedis.geoadd(bfoo, bcoordinateMap)); } - - private boolean equalsWithinEpsilon(double d1, double d2) { - double epsilon = 1E-5; - return Math.abs(d1 - d2) < epsilon; - } } diff --git a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/HashesCommandsTest.java similarity index 96% rename from src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/HashesCommandsTest.java index 817a185d29..52aef2c4a7 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HashesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/HashesCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -6,11 +6,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertCollectionContains; + +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContains; import java.util.ArrayList; import java.util.Collections; @@ -25,11 +26,11 @@ import redis.clients.jedis.Pipeline; import redis.clients.jedis.Response; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; import redis.clients.jedis.util.JedisByteHashMap; -public class HashesCommandsTest extends JedisCommandTestBase { +public class HashesCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; diff --git a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/HyperLogLogCommandsTest.java similarity index 96% rename from src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/HyperLogLogCommandsTest.java index 300268d38f..9b989cf9e1 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/HyperLogLogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/HyperLogLogCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; @@ -6,7 +6,7 @@ import redis.clients.jedis.util.SafeEncoder; -public class HyperLogLogCommandsTest extends JedisCommandTestBase { +public class HyperLogLogCommandsTest extends JedisCommandsTestBase { @Test public void pfadd() { diff --git a/src/test/java/redis/clients/jedis/commands/jedis/JedisCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/jedis/JedisCommandsTestBase.java new file mode 100644 index 0000000000..994a058880 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/jedis/JedisCommandsTestBase.java @@ -0,0 +1,35 @@ +package redis.clients.jedis.commands.jedis; + +import org.junit.After; +import org.junit.Before; + +import redis.clients.jedis.DefaultJedisClientConfig; +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.HostAndPorts; + +public abstract class JedisCommandsTestBase { + + protected static final HostAndPort hnp = HostAndPorts.getRedisServers().get(0); + + protected Jedis jedis; + + public JedisCommandsTestBase() { + super(); + } + + @Before + public void setUp() throws Exception { + jedis = new Jedis(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); + jedis.flushAll(); + } + + @After + public void tearDown() throws Exception { + jedis.close(); + } + + protected Jedis createJedis() { + return new Jedis(hnp, DefaultJedisClientConfig.builder().password("foobared").build()); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ListCommandsTest.java similarity index 99% rename from src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ListCommandsTest.java index 6eae8d8a1e..d22619a431 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ListCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ListCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -6,7 +6,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.util.ArrayList; import java.util.Arrays; @@ -19,13 +19,13 @@ import org.junit.Test; import redis.clients.jedis.Jedis; -import redis.clients.jedis.ListPosition; +import redis.clients.jedis.args.ListPosition; import redis.clients.jedis.args.ListDirection; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.params.LPosParams; import redis.clients.jedis.resps.KeyedListElement; -public class ListCommandsTest extends JedisCommandTestBase { +public class ListCommandsTest extends JedisCommandsTestBase { private static final Logger logger = LogManager.getLogger(); diff --git a/src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java b/src/test/java/redis/clients/jedis/commands/jedis/MigrateTest.java similarity index 98% rename from src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/MigrateTest.java index f4e7ffb641..1a0f7a0b6e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/MigrateTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/MigrateTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -15,7 +15,7 @@ import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.params.MigrateParams; -public class MigrateTest extends JedisCommandTestBase { +public class MigrateTest extends JedisCommandsTestBase { private static final byte[] bfoo = { 0x01, 0x02, 0x03 }; private static final byte[] bbar = { 0x04, 0x05, 0x06 }; diff --git a/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ObjectCommandsTest.java similarity index 91% rename from src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ObjectCommandsTest.java index 8847aa6867..4187c952e9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ObjectCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ObjectCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -13,16 +13,16 @@ import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; import redis.clients.jedis.exceptions.JedisDataException; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.HostAndPorts; import redis.clients.jedis.util.SafeEncoder; import java.util.List; -public class ObjectCommandsTest extends JedisCommandTestBase { +public class ObjectCommandsTest extends JedisCommandsTestBase { private String key = "mylist"; private byte[] binaryKey = SafeEncoder.encode(key); - private static final HostAndPort lfuHnp = HostAndPortUtil.getRedisServers().get(7); + private static final HostAndPort lfuHnp = HostAndPorts.getRedisServers().get(7); private Jedis lfuJedis; @Before diff --git a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/PublishSubscribeCommandsTest.java similarity index 97% rename from src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/PublishSubscribeCommandsTest.java index 17964e8f5d..a45877e419 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/PublishSubscribeCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/PublishSubscribeCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -24,7 +24,7 @@ import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.util.SafeEncoder; -public class PublishSubscribeCommandsTest extends JedisCommandTestBase { +public class PublishSubscribeCommandsTest extends JedisCommandsTestBase { private void publishOne(final String channel, final String message) { Thread t = new Thread(new Runnable() { public void run() { @@ -195,9 +195,9 @@ public void onPSubscribe(String pattern, int subscribedChannels) { @Test public void pubSubNumSub() { - final Map expectedNumSub = new HashMap(); - expectedNumSub.put("testchannel2", "1"); - expectedNumSub.put("testchannel1", "1"); + final Map expectedNumSub = new HashMap<>(); + expectedNumSub.put("testchannel2", 1L); + expectedNumSub.put("testchannel1", 1L); jedis.subscribe(new JedisPubSub() { private int count = 0; @@ -206,7 +206,7 @@ public void onSubscribe(String channel, int subscribedChannels) { count++; if (count == 2) { Jedis otherJedis = createJedis(); - Map numSub = otherJedis.pubsubNumSub("testchannel1", "testchannel2"); + Map numSub = otherJedis.pubsubNumSub("testchannel1", "testchannel2"); assertEquals(expectedNumSub, numSub); unsubscribe(); } @@ -504,8 +504,6 @@ public void onMessage(String channel, String message) { try { // wait 0.5 secs to slow down subscribe and // client-output-buffer exceed - // System.out.println("channel - " + channel + - // " / message - " + message); Thread.sleep(100); } catch (Exception e) { try { diff --git a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/ScriptingCommandsTest.java similarity index 91% rename from src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/ScriptingCommandsTest.java index 3c50e5f2fb..d2ec2a0eb0 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/ScriptingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/ScriptingCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.hamcrest.CoreMatchers.equalTo; import static org.junit.Assert.assertArrayEquals; @@ -16,16 +16,15 @@ import org.hamcrest.Matcher; import org.junit.Test; -import redis.clients.jedis.BinaryJedis; import redis.clients.jedis.Jedis; import redis.clients.jedis.args.FlushMode; import redis.clients.jedis.exceptions.JedisConnectionException; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisNoScriptException; -import redis.clients.jedis.tests.utils.ClientKillerUtil; +import redis.clients.jedis.util.ClientKillerUtil; import redis.clients.jedis.util.SafeEncoder; -public class ScriptingCommandsTest extends JedisCommandTestBase { +public class ScriptingCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x0A }; @@ -73,19 +72,13 @@ public void evalMultiBulkWithBinaryJedis() { args.add("second".getBytes()); args.add("third".getBytes()); - BinaryJedis binaryJedis = new BinaryJedis(hnp.getHost(), hnp.getPort(), 500); - binaryJedis.connect(); - binaryJedis.auth("foobared"); - - List responses = (List) binaryJedis.eval(script.getBytes(), keys, args); + List responses = (List) jedis.eval(script.getBytes(), keys, args); assertEquals(5, responses.size()); assertEquals("key1", new String(responses.get(0))); assertEquals("key2", new String(responses.get(1))); assertEquals("first", new String(responses.get(2))); assertEquals("second", new String(responses.get(3))); assertEquals("third", new String(responses.get(4))); - - binaryJedis.close(); } @Test @@ -186,11 +179,11 @@ public void scriptExists() { @Test public void scriptExistsBinary() { jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')")); - List exists = jedis.scriptExists( + List exists = jedis.scriptExists( SafeEncoder.encode("ffffffffffffffffffffffffffffffffffffffff"), SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); - assertEquals(new Long(0), exists.get(0)); - assertEquals(new Long(1), exists.get(1)); + assertFalse(exists.get(0)); + assertTrue(exists.get(1)); } @Test @@ -202,9 +195,9 @@ public void scriptLoad() { @Test public void scriptLoadBinary() { jedis.scriptLoad(SafeEncoder.encode("return redis.call('get','foo')")); - Long exists = jedis + Boolean exists = jedis .scriptExists(SafeEncoder.encode("6b1bf486c81ceb7edf3c093f4c48582e38c0e791")); - assertEquals((Long) 1L, exists); + assertTrue(exists); } @Test @@ -269,8 +262,7 @@ public void scriptEvalShaReturnValuesBinary() { @Test public void scriptExistsWithBrokenConnection() { - Jedis deadClient = new Jedis(jedis.getClient().getHost(), jedis.getClient().getPort()); - deadClient.auth("foobared"); + Jedis deadClient = createJedis(); deadClient.clientSetname("DEAD"); diff --git a/src/test/java/redis/clients/jedis/tests/commands/SentinelCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/SentinelCommandsTest.java similarity index 60% rename from src/test/java/redis/clients/jedis/tests/commands/SentinelCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/SentinelCommandsTest.java index 66111a62cb..accdaceaed 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SentinelCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/SentinelCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -7,26 +7,26 @@ import org.junit.Test; import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.tests.HostAndPortUtil; +import redis.clients.jedis.Sentinel; +import redis.clients.jedis.HostAndPorts; public class SentinelCommandsTest { - protected static HostAndPort master2 = HostAndPortUtil.getRedisServers().get(2); - protected static HostAndPort replica2 = HostAndPortUtil.getRedisServers().get(3); + protected static HostAndPort master2 = HostAndPorts.getRedisServers().get(2); + protected static HostAndPort replica2 = HostAndPorts.getRedisServers().get(3); - protected static HostAndPort sentinel2_1 = HostAndPortUtil.getSentinelServers().get(1); - protected static HostAndPort sentinel2_2 = HostAndPortUtil.getSentinelServers().get(3); + protected static HostAndPort sentinel2_1 = HostAndPorts.getSentinelServers().get(1); + protected static HostAndPort sentinel2_2 = HostAndPorts.getSentinelServers().get(3); @Test public void myIdSentinels() { String id1; - try (Jedis sentinel = new Jedis(sentinel2_1)) { + try (Sentinel sentinel = new Sentinel(sentinel2_1)) { id1 = sentinel.sentinelMyId(); assertTrue(id1.matches("[0-9a-f]+")); } - try (Jedis sentinel2 = new Jedis(sentinel2_2)) { + try (Sentinel sentinel2 = new Sentinel(sentinel2_2)) { Map details1 = sentinel2.sentinelSentinels("mymaster").get(0); assertEquals(id1, details1.get("runid")); } @@ -35,13 +35,13 @@ public void myIdSentinels() { @Test public void masterMasters() { String runId; - try (Jedis sentinel = new Jedis(sentinel2_1)) { + try (Sentinel sentinel = new Sentinel(sentinel2_1)) { Map details = sentinel.sentinelMaster("mymaster"); assertEquals("mymaster", details.get("name")); runId = details.get("runid"); } - try (Jedis sentinel2 = new Jedis(sentinel2_2)) { + try (Sentinel sentinel2 = new Sentinel(sentinel2_2)) { Map details = sentinel2.sentinelMasters().get(0); assertEquals("mymaster", details.get("name")); assertEquals(runId, details.get("runid")); @@ -50,7 +50,7 @@ public void masterMasters() { @Test public void replicas() { - try (Jedis sentinel = new Jedis(sentinel2_1)) { + try (Sentinel sentinel = new Sentinel(sentinel2_1)) { Map details = sentinel.sentinelReplicas("mymaster").get(0); assertEquals(Integer.toString(replica2.getPort()), details.get("port")); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/SetCommandsTest.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/SetCommandsTest.java index 4f7987e40b..c9847d6583 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/SetCommandsTest.java @@ -1,16 +1,17 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayCollectionContainsAll; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertCollectionContainsAll; -import static redis.clients.jedis.tests.utils.ByteArrayUtil.byteArrayCollectionRemoveAll; + +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayCollectionContainsAll; +import static redis.clients.jedis.util.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContainsAll; +import static redis.clients.jedis.util.ByteArrayUtil.byteArrayCollectionRemoveAll; import java.util.Arrays; import java.util.Comparator; @@ -20,10 +21,10 @@ import org.junit.Test; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; -public class SetCommandsTest extends JedisCommandTestBase { +public class SetCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; @@ -476,12 +477,12 @@ public void sdiffstore() { jedis.sadd("car", "d"); Set expected = new HashSet(); - expected.add("d"); - expected.add("a"); + expected.add("x"); + expected.add("b"); long status = jedis.sdiffstore("tar", "foo", "bar", "car"); assertEquals(2, status); - assertEquals(expected, jedis.smembers("car")); + assertEquals(expected, jedis.smembers("tar")); // Binary jedis.sadd(bfoo, bx); @@ -495,12 +496,12 @@ public void sdiffstore() { jedis.sadd(bcar, bd); Set bexpected = new HashSet(); - bexpected.add(bd); - bexpected.add(ba); + bexpected.add(bx); + bexpected.add(bb); long bstatus = jedis.sdiffstore("tar".getBytes(), bfoo, bbar, bcar); assertEquals(2, bstatus); - assertByteArraySetEquals(bexpected, jedis.smembers(bcar)); + assertByteArraySetEquals(bexpected, jedis.smembers("tar".getBytes())); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/SlowlogCommandsTest.java similarity index 93% rename from src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/SlowlogCommandsTest.java index 4c3e0bf24b..fa95e6eb9e 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SlowlogCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/SlowlogCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -11,10 +11,10 @@ import org.junit.Test; import redis.clients.jedis.Protocol; +import redis.clients.jedis.resps.Slowlog; import redis.clients.jedis.util.SafeEncoder; -import redis.clients.jedis.util.Slowlog; -public class SlowlogCommandsTest extends JedisCommandTestBase { +public class SlowlogCommandsTest extends JedisCommandsTestBase { private static final String SLOWLOG_TIME_PARAM = "slowlog-log-slower-than"; private static final String ZERO = "0"; @@ -58,7 +58,8 @@ public void slowlog() { assertNotNull(log1); assertNotNull(blog1); - assertEquals(7, jedis.slowlogLen()); +// assertEquals(7, jedis.slowlogLen()); + assertTrue(jedis.slowlogLen() > 5 && jedis.slowlogLen() < 12); } @Test diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/SortedSetCommandsTest.java similarity index 83% rename from src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/SortedSetCommandsTest.java index 95dd0cc399..73d8a396a3 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortedSetCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/SortedSetCommandsTest.java @@ -1,13 +1,14 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.*; -import static org.junit.Assert.assertNotNull; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START; -import static redis.clients.jedis.ScanParams.SCAN_POINTER_START_BINARY; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertCollectionContains; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContains; import java.util.Arrays; +import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; @@ -19,16 +20,16 @@ import org.junit.Test; import redis.clients.jedis.BuilderFactory; -import redis.clients.jedis.ScanParams; -import redis.clients.jedis.ScanResult; -import redis.clients.jedis.Tuple; -import redis.clients.jedis.ZParams; +import redis.clients.jedis.params.ScanParams; import redis.clients.jedis.params.ZAddParams; import redis.clients.jedis.params.ZIncrByParams; +import redis.clients.jedis.params.ZParams; import redis.clients.jedis.resps.KeyedZSetElement; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; import redis.clients.jedis.util.SafeEncoder; -public class SortedSetCommandsTest extends JedisCommandTestBase { +public class SortedSetCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; @@ -146,11 +147,11 @@ public void zrange() { jedis.zadd("foo", 0.1d, "c"); jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("c"); expected.add("a"); - Set range = jedis.zrange("foo", 0, 1); + List range = jedis.zrange("foo", 0, 1); assertEquals(expected, range); expected.add("b"); @@ -163,16 +164,16 @@ public void zrange() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(bc); bexpected.add(ba); - Set brange = jedis.zrange(bfoo, 0, 1); - assertByteArraySetEquals(bexpected, brange); + List brange = jedis.zrange(bfoo, 0, 1); + assertByteArrayListEquals(bexpected, brange); bexpected.add(bb); brange = jedis.zrange(bfoo, 0, 100); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); } @Test @@ -182,7 +183,7 @@ public void zrangeByLex() { jedis.zadd("foo", 1, "bb"); jedis.zadd("foo", 1, "d"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("bb"); expected.add("c"); @@ -204,17 +205,17 @@ public void zrangeByLexBinary() { jedis.zadd(bfoo, 1, bc); jedis.zadd(bfoo, 1, bb); - Set bExpected = new LinkedHashSet(); + List bExpected = new ArrayList(); bExpected.add(bb); - assertByteArraySetEquals(bExpected, jedis.zrangeByLex(bfoo, bInclusiveB, bExclusiveC)); + assertByteArrayListEquals(bExpected, jedis.zrangeByLex(bfoo, bInclusiveB, bExclusiveC)); bExpected.clear(); bExpected.add(ba); bExpected.add(bb); // with LIMIT - assertByteArraySetEquals(bExpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf, 0, 2)); + assertByteArrayListEquals(bExpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf, 0, 2)); } @Test @@ -224,7 +225,7 @@ public void zrevrangeByLex() { jedis.zadd("foo", 1, "bb"); jedis.zadd("foo", 1, "d"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("c"); expected.add("bb"); @@ -246,17 +247,17 @@ public void zrevrangeByLexBinary() { jedis.zadd(bfoo, 1, bc); jedis.zadd(bfoo, 1, bb); - Set bExpected = new LinkedHashSet(); + List bExpected = new ArrayList(); bExpected.add(bb); - assertByteArraySetEquals(bExpected, jedis.zrevrangeByLex(bfoo, bExclusiveC, bInclusiveB)); + assertByteArrayListEquals(bExpected, jedis.zrevrangeByLex(bfoo, bExclusiveC, bInclusiveB)); bExpected.clear(); + bExpected.add(bc); bExpected.add(bb); - bExpected.add(ba); // with LIMIT - assertByteArraySetEquals(bExpected, jedis.zrevrangeByLex(bfoo, bLexPlusInf, bLexMinusInf, 0, 2)); + assertByteArrayListEquals(bExpected, jedis.zrevrangeByLex(bfoo, bLexPlusInf, bLexMinusInf, 0, 2)); } @Test @@ -266,11 +267,11 @@ public void zrevrange() { jedis.zadd("foo", 0.1d, "c"); jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("b"); expected.add("a"); - Set range = jedis.zrevrange("foo", 0, 1); + List range = jedis.zrevrange("foo", 0, 1); assertEquals(expected, range); expected.add("c"); @@ -283,16 +284,16 @@ public void zrevrange() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(bb); bexpected.add(ba); - Set brange = jedis.zrevrange(bfoo, 0, 1); - assertByteArraySetEquals(bexpected, brange); + List brange = jedis.zrevrange(bfoo, 0, 1); + assertByteArrayListEquals(bexpected, brange); bexpected.add(bc); brange = jedis.zrevrange(bfoo, 0, 100); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); } @Test @@ -302,7 +303,7 @@ public void zrem() { assertEquals(1, jedis.zrem("foo", "a")); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("b"); assertEquals(expected, jedis.zrange("foo", 0, 100)); @@ -315,10 +316,10 @@ public void zrem() { assertEquals(1, jedis.zrem(bfoo, ba)); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(bb); - assertByteArraySetEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); assertEquals(0, jedis.zrem(bfoo, bbar)); } @@ -330,9 +331,9 @@ public void zincrby() { assertEquals(3d, jedis.zincrby("foo", 2d, "a"), 0); - Set expected = new LinkedHashSet(); - expected.add("a"); + List expected = new ArrayList(); expected.add("b"); + expected.add("a"); assertEquals(expected, jedis.zrange("foo", 0, 100)); @@ -342,11 +343,11 @@ public void zincrby() { assertEquals(3d, jedis.zincrby(bfoo, 2d, ba), 0); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(bb); bexpected.add(ba); - assertByteArraySetEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @Test @@ -431,11 +432,11 @@ public void zrangeWithScores() { jedis.zadd("foo", 0.1d, "c"); jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("c", 0.1d)); expected.add(new Tuple("a", 2d)); - Set range = jedis.zrangeWithScores("foo", 0, 1); + List range = jedis.zrangeWithScores("foo", 0, 1); assertEquals(expected, range); expected.add(new Tuple("b", 10d)); @@ -448,11 +449,11 @@ public void zrangeWithScores() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(new Tuple(bc, 0.1d)); bexpected.add(new Tuple(ba, 2d)); - Set brange = jedis.zrangeWithScores(bfoo, 0, 1); + List brange = jedis.zrangeWithScores(bfoo, 0, 1); assertEquals(bexpected, brange); bexpected.add(new Tuple(bb, 10d)); @@ -468,11 +469,11 @@ public void zrevrangeWithScores() { jedis.zadd("foo", 0.1d, "c"); jedis.zadd("foo", 2d, "a"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("b", 10d)); expected.add(new Tuple("a", 2d)); - Set range = jedis.zrevrangeWithScores("foo", 0, 1); + List range = jedis.zrevrangeWithScores("foo", 0, 1); assertEquals(expected, range); expected.add(new Tuple("c", 0.1d)); @@ -485,11 +486,11 @@ public void zrevrangeWithScores() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(new Tuple(bb, 10d)); bexpected.add(new Tuple(ba, 2d)); - Set brange = jedis.zrevrangeWithScores(bfoo, 0, 1); + List brange = jedis.zrevrangeWithScores(bfoo, 0, 1); assertEquals(bexpected, brange); bexpected.add(new Tuple(bc, 0.1d)); @@ -622,10 +623,10 @@ public void zpopmaxWithCount() { jedis.zadd("foo", 2d, "d"); jedis.zadd("foo", 0.03, "e"); - Set actual = jedis.zpopmax("foo", 2); + List actual = jedis.zpopmax("foo", 2); assertEquals(2, actual.size()); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("b", 10d)); expected.add(new Tuple("d", 2d)); assertEquals(expected, actual); @@ -682,9 +683,9 @@ public void zpopmin() { jedis.zadd("foo", 0.1d, "c", ZAddParams.zAddParams().nx()); jedis.zadd("foo", 2d, "a", ZAddParams.zAddParams().nx()); - Set range = jedis.zpopmin("foo", 2); + List range = jedis.zpopmin("foo", 2); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("c", 0.1d)); expected.add(new Tuple("a", 1d)); @@ -699,9 +700,9 @@ public void zpopmin() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zpopmin(bfoo, 2); + List brange = jedis.zpopmin(bfoo, 2); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(new Tuple(bc, 0.1d)); bexpected.add(new Tuple(ba, 2d)); @@ -767,9 +768,9 @@ public void zrangebyscore() { jedis.zadd("foo", 0.1d, "c"); jedis.zadd("foo", 2d, "a"); - Set range = jedis.zrangeByScore("foo", 0d, 2d); + List range = jedis.zrangeByScore("foo", 0d, 2d); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("c"); expected.add("a"); @@ -777,16 +778,16 @@ public void zrangebyscore() { range = jedis.zrangeByScore("foo", 0d, 2d, 0, 1); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add("c"); assertEquals(expected, range); range = jedis.zrangeByScore("foo", 0d, 2d, 1, 1); - Set range2 = jedis.zrangeByScore("foo", "-inf", "(2"); + List range2 = jedis.zrangeByScore("foo", "-inf", "(2"); assertEquals(expected, range2); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add("a"); assertEquals(expected, range); @@ -797,30 +798,30 @@ public void zrangebyscore() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrangeByScore(bfoo, 0d, 2d); + List brange = jedis.zrangeByScore(bfoo, 0d, 2d); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(bc); bexpected.add(ba); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); brange = jedis.zrangeByScore(bfoo, 0d, 2d, 0, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(bc); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1); - Set brange2 = jedis.zrangeByScore(bfoo, SafeEncoder.encode("-inf"), + List brange2 = jedis.zrangeByScore(bfoo, SafeEncoder.encode("-inf"), SafeEncoder.encode("(2")); - assertByteArraySetEquals(bexpected, brange2); + assertByteArrayListEquals(bexpected, brange2); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(ba); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); } @@ -832,27 +833,27 @@ public void zrevrangebyscore() { jedis.zadd("foo", 4.0d, "d"); jedis.zadd("foo", 5.0d, "e"); - Set range = jedis.zrevrangeByScore("foo", 3d, Double.NEGATIVE_INFINITY, 0, 1); - Set expected = new LinkedHashSet(); + List range = jedis.zrevrangeByScore("foo", 3d, Double.NEGATIVE_INFINITY, 0, 1); + List expected = new ArrayList(); expected.add("c"); assertEquals(expected, range); range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, 0, 2); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add("c"); expected.add("b"); assertEquals(expected, range); range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, 1, 1); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add("b"); assertEquals(expected, range); range = jedis.zrevrangeByScore("foo", 4d, 2d); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add("d"); expected.add("c"); expected.add("b"); @@ -860,7 +861,7 @@ public void zrevrangebyscore() { assertEquals(expected, range); range = jedis.zrevrangeByScore("foo", "+inf", "(4"); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add("e"); assertEquals(expected, range); @@ -871,34 +872,34 @@ public void zrevrangebyscore() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrevrangeByScore(bfoo, 2d, 0d); + List brange = jedis.zrevrangeByScore(bfoo, 2d, 0d); - Set bexpected = new LinkedHashSet(); - bexpected.add(bc); + List bexpected = new ArrayList(); bexpected.add(ba); + bexpected.add(bc); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 0, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(ba); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); - Set brange2 = jedis.zrevrangeByScore(bfoo, SafeEncoder.encode("+inf"), + List brange2 = jedis.zrevrangeByScore(bfoo, SafeEncoder.encode("+inf"), SafeEncoder.encode("(2")); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(bb); - assertByteArraySetEquals(bexpected, brange2); + assertByteArrayListEquals(bexpected, brange2); brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 1, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(bc); - assertByteArraySetEquals(bexpected, brange); + assertByteArrayListEquals(bexpected, brange); } @Test @@ -908,9 +909,9 @@ public void zrangebyscoreWithScores() { jedis.zadd("foo", 0.1d, "c"); jedis.zadd("foo", 2d, "a"); - Set range = jedis.zrangeByScoreWithScores("foo", 0d, 2d); + List range = jedis.zrangeByScoreWithScores("foo", 0d, 2d); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("c", 0.1d)); expected.add(new Tuple("a", 2d)); @@ -918,14 +919,14 @@ public void zrangebyscoreWithScores() { range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 0, 1); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add(new Tuple("c", 0.1d)); assertEquals(expected, range); range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 1, 1); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add(new Tuple("a", 2d)); assertEquals(expected, range); @@ -937,9 +938,9 @@ public void zrangebyscoreWithScores() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d); + List brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(new Tuple(bc, 0.1d)); bexpected.add(new Tuple(ba, 2d)); @@ -947,14 +948,14 @@ public void zrangebyscoreWithScores() { brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 0, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(new Tuple(bc, 0.1d)); assertEquals(bexpected, brange); brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 1, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(new Tuple(ba, 2d)); assertEquals(bexpected, brange); @@ -969,27 +970,27 @@ public void zrevrangebyscoreWithScores() { jedis.zadd("foo", 4.0d, "d"); jedis.zadd("foo", 5.0d, "e"); - Set range = jedis.zrevrangeByScoreWithScores("foo", 3d, Double.NEGATIVE_INFINITY, 0, 1); - Set expected = new LinkedHashSet(); + List range = jedis.zrevrangeByScoreWithScores("foo", 3d, Double.NEGATIVE_INFINITY, 0, 1); + List expected = new ArrayList(); expected.add(new Tuple("c", 3.0d)); assertEquals(expected, range); range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, Double.NEGATIVE_INFINITY, 0, 2); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add(new Tuple("c", 3.0d)); expected.add(new Tuple("b", 2.0d)); assertEquals(expected, range); range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, Double.NEGATIVE_INFINITY, 1, 1); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add(new Tuple("b", 2.0d)); assertEquals(expected, range); range = jedis.zrevrangeByScoreWithScores("foo", 4d, 2d); - expected = new LinkedHashSet(); + expected = new ArrayList(); expected.add(new Tuple("d", 4.0d)); expected.add(new Tuple("c", 3.0d)); expected.add(new Tuple("b", 2.0d)); @@ -1002,24 +1003,24 @@ public void zrevrangebyscoreWithScores() { jedis.zadd(bfoo, 0.1d, bc); jedis.zadd(bfoo, 2d, ba); - Set brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d); + List brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bc, 0.1d)); + List bexpected = new ArrayList(); bexpected.add(new Tuple(ba, 2d)); + bexpected.add(new Tuple(bc, 0.1d)); assertEquals(bexpected, brange); brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 0, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(new Tuple(ba, 2d)); assertEquals(bexpected, brange); brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 1, 1); - bexpected = new LinkedHashSet(); + bexpected = new ArrayList(); bexpected.add(new Tuple(bc, 0.1d)); assertEquals(bexpected, brange); @@ -1034,7 +1035,7 @@ public void zremrangeByRank() { assertEquals(1, jedis.zremrangeByRank("foo", 0, 0)); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("a"); expected.add("b"); @@ -1048,11 +1049,11 @@ public void zremrangeByRank() { assertEquals(1, jedis.zremrangeByRank(bfoo, 0, 0)); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(ba); bexpected.add(bb); - assertByteArraySetEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @@ -1065,7 +1066,7 @@ public void zremrangeByScore() { assertEquals(2, jedis.zremrangeByScore("foo", 0, 2)); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("b"); assertEquals(expected, jedis.zrange("foo", 0, 100)); @@ -1078,10 +1079,10 @@ public void zremrangeByScore() { assertEquals(2, jedis.zremrangeByScore(bfoo, 0, 2)); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(bb); - assertByteArraySetEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); } @Test @@ -1109,7 +1110,7 @@ public void zremrangeByLex() { assertEquals(2, jedis.zremrangeByLex("foo", "[aa", "(c")); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("a"); expected.add("c"); @@ -1124,11 +1125,11 @@ public void zremrangeByLexBinary() { assertEquals(1, jedis.zremrangeByLex(bfoo, bInclusiveB, bExclusiveC)); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(ba); bexpected.add(bc); - assertByteArraySetEquals(bexpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf)); + assertByteArrayListEquals(bexpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf)); } @Test @@ -1180,9 +1181,9 @@ public void zunionstore() { assertEquals(2, jedis.zunionstore("dst", "foo", "bar")); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("b", new Double(4))); + List expected = new ArrayList(); expected.add(new Tuple("a", new Double(3))); + expected.add(new Tuple("b", new Double(4))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); @@ -1194,9 +1195,9 @@ public void zunionstore() { assertEquals(2, jedis.zunionstore(SafeEncoder.encode("dst"), bfoo, bbar)); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bb, new Double(4))); + List bexpected = new ArrayList(); bexpected.add(new Tuple(ba, new Double(3))); + bexpected.add(new Tuple(bb, new Double(4))); assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); } @@ -1214,9 +1215,9 @@ public void zunionstoreParams() { assertEquals(2, jedis.zunionstore("dst", params, "foo", "bar")); - Set expected = new LinkedHashSet(); - expected.add(new Tuple("b", new Double(9))); + List expected = new ArrayList(); expected.add(new Tuple("a", new Double(7))); + expected.add(new Tuple("b", new Double(9))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); @@ -1232,9 +1233,9 @@ public void zunionstoreParams() { assertEquals(2, jedis.zunionstore(SafeEncoder.encode("dst"), bparams, bfoo, bbar)); - Set bexpected = new LinkedHashSet(); - bexpected.add(new Tuple(bb, new Double(9))); + List bexpected = new ArrayList(); bexpected.add(new Tuple(ba, new Double(7))); + bexpected.add(new Tuple(bb, new Double(9))); assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); } @@ -1275,7 +1276,7 @@ public void zinterstore() { assertEquals(1, jedis.zinterstore("dst", "foo", "bar")); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("a", new Double(3))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); @@ -1287,7 +1288,7 @@ public void zinterstore() { assertEquals(1, jedis.zinterstore(SafeEncoder.encode("dst"), bfoo, bbar)); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(new Tuple(ba, new Double(3))); assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); @@ -1305,7 +1306,7 @@ public void zintertoreParams() { assertEquals(1, jedis.zinterstore("dst", params, "foo", "bar")); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add(new Tuple("a", new Double(7))); assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); @@ -1321,7 +1322,7 @@ public void zintertoreParams() { assertEquals(1, jedis.zinterstore(SafeEncoder.encode("dst"), bparams, bfoo, bbar)); - Set bexpected = new LinkedHashSet(); + List bexpected = new ArrayList(); bexpected.add(new Tuple(ba, new Double(7))); assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); @@ -1410,7 +1411,7 @@ public void infinity() { assertEquals(Double.NEGATIVE_INFINITY, jedis.zscore("key", "neg"), 0d); jedis.zadd("key", 0d, "zero"); - Set set = jedis.zrangeWithScores("key", 0, -1); + List set = jedis.zrangeWithScores("key", 0, -1); Iterator itr = set.iterator(); assertEquals(Double.NEGATIVE_INFINITY, itr.next().getScore(), 0d); assertEquals(0d, itr.next().getScore(), 0d); @@ -1484,7 +1485,7 @@ public void zdiffStore() { assertEquals(0, jedis.zdiffStore("bar3", "bar1", "bar2")); assertEquals(1, jedis.zdiffStore("bar3", "foo", "bar")); - assertEquals(Collections.singleton("b"), jedis.zrange("bar3", 0, -1)); + assertEquals(Collections.singletonList("b"), jedis.zrange("bar3", 0, -1)); // binary @@ -1494,15 +1495,15 @@ public void zdiffStore() { assertEquals(0, jedis.zdiffStore(bbar3, bbar1, bbar2)); assertEquals(1, jedis.zdiffStore(bbar3, bfoo, bbar)); - Set bactual = jedis.zrange(bbar3, 0, -1); + List bactual = jedis.zrange(bbar3, 0, -1); assertArrayEquals(bb, bactual.iterator().next()); } @Test public void zrandmember() { assertNull(jedis.zrandmember("foo")); - assertEquals(Collections.emptySet(), jedis.zrandmember("foo", 1)); - assertEquals(Collections.emptySet(), jedis.zrandmemberWithScores("foo", 1)); + assertEquals(Collections.emptyList(), jedis.zrandmember("foo", 1)); + assertEquals(Collections.emptyList(), jedis.zrandmemberWithScores("foo", 1)); Map hash = new HashMap<>(); hash.put("bar1", 1d); @@ -1513,7 +1514,7 @@ public void zrandmember() { assertTrue(hash.containsKey(jedis.zrandmember("foo"))); assertEquals(2, jedis.zrandmember("foo", 2).size()); - Set actual = jedis.zrandmemberWithScores("foo", 2); + List actual = jedis.zrandmemberWithScores("foo", 2); assertNotNull(actual); assertEquals(2, actual.size()); Tuple tuple = actual.iterator().next(); @@ -1521,8 +1522,8 @@ public void zrandmember() { // Binary assertNull(jedis.zrandmember(bfoo)); - assertEquals(Collections.emptySet(), jedis.zrandmember(bfoo, 1)); - assertEquals(Collections.emptySet(), jedis.zrandmemberWithScores(bfoo, 1)); + assertEquals(Collections.emptyList(), jedis.zrandmember(bfoo, 1)); + assertEquals(Collections.emptyList(), jedis.zrandmemberWithScores(bfoo, 1)); Map bhash = new HashMap<>(); bhash.put(bbar1, 1d); @@ -1533,9 +1534,9 @@ public void zrandmember() { assertCollectionContains(bhash.keySet(), jedis.zrandmember(bfoo)); assertEquals(2, jedis.zrandmember(bfoo, 2).size()); - Set bactual = jedis.zrandmemberWithScores(bfoo, 2); - assertNotNull(actual); - assertEquals(2, actual.size()); + List bactual = jedis.zrandmemberWithScores(bfoo, 2); + assertNotNull(bactual); + assertEquals(2, bactual.size()); tuple = bactual.iterator().next(); assertEquals(getScoreFromByteMap(bhash, tuple.getBinaryElement()), Double.valueOf(tuple.getScore())); } diff --git a/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/SortingCommandsTest.java similarity index 96% rename from src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/SortingCommandsTest.java index 0d916a4653..a6850d6787 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/SortingCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/SortingCommandsTest.java @@ -1,16 +1,16 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.util.ArrayList; import java.util.List; import org.junit.Test; -import redis.clients.jedis.SortingParams; +import redis.clients.jedis.params.SortingParams; -public class SortingCommandsTest extends JedisCommandTestBase { +public class SortingCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bfoodest = { 0x01, 0x02, 0x03, 0x04, 0x05 }; final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, '1' }; diff --git a/src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/StreamsCommandsTest.java similarity index 72% rename from src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/StreamsCommandsTest.java index 924b8097f6..18218d579a 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/StreamsCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/StreamsCommandsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -6,9 +6,9 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; -import static redis.clients.jedis.StreamGroupInfo.*; -import static redis.clients.jedis.StreamInfo.*; -import static redis.clients.jedis.StreamConsumersInfo.IDLE; +import static redis.clients.jedis.resps.StreamGroupInfo.*; +import static redis.clients.jedis.resps.StreamInfo.*; +import static redis.clients.jedis.resps.StreamConsumersInfo.IDLE; import java.time.Duration; import java.util.AbstractMap; @@ -19,22 +19,21 @@ import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; - import org.junit.Test; -import redis.clients.jedis.*; -import redis.clients.jedis.Protocol.Keyword; + +import redis.clients.jedis.BuilderFactory; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Pipeline; +import redis.clients.jedis.Response; +import redis.clients.jedis.StreamEntryID; +import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.exceptions.JedisException; -import redis.clients.jedis.params.XAddParams; -import redis.clients.jedis.params.XAutoClaimParams; -import redis.clients.jedis.params.XClaimParams; -import redis.clients.jedis.params.XPendingParams; -import redis.clients.jedis.params.XReadGroupParams; -import redis.clients.jedis.params.XReadParams; -import redis.clients.jedis.params.XTrimParams; +import redis.clients.jedis.params.*; +import redis.clients.jedis.resps.*; import redis.clients.jedis.util.SafeEncoder; -public class StreamsCommandsTest extends JedisCommandTestBase { +public class StreamsCommandsTest extends JedisCommandsTestBase { @Test public void xadd() { @@ -76,13 +75,13 @@ public void xadd() { map5.put("f5", "v5"); StreamEntryID id5 = jedis.xadd("xadd-stream2", null, map5); assertTrue(id5.compareTo(id4) > 0); - - Map map6 = new HashMap<>(); - map6.put("f4", "v4"); - map6.put("f5", "v5"); - StreamEntryID id6 = jedis.xadd("xadd-stream2", null, map6, 3, false); - assertTrue(id6.compareTo(id5) > 0); - assertEquals(3L, jedis.xlen("xadd-stream2")); +// +// Map map6 = new HashMap<>(); +// map6.put("f4", "v4"); +// map6.put("f5", "v5"); +// StreamEntryID id6 = jedis.xadd("xadd-stream2", null, map6, 3, false); +// assertTrue(id6.compareTo(id5) > 0); +// assertEquals(3L, jedis.xlen("xadd-stream2")); } @Test @@ -205,40 +204,6 @@ public void xrange() { List range8 = jedis.xrange("xrange-stream", null, null); assertEquals(3, range8.size()); - - // count parameter - backward compatibility - List cRange = jedis.xrange("xrange-stream".getBytes(), id1.toString().getBytes(), - id2.toString().getBytes(), 10L + Integer.MAX_VALUE); - assertEquals(2, cRange.size()); - } - - @Test - public void xread() { - - Entry streamQeury1 = new AbstractMap.SimpleImmutableEntry<>( - "xread-stream1", new StreamEntryID()); - - // Empty Stream - List>> range = jedis.xread(1, 1L, streamQeury1); - assertEquals(0, range.size()); - - Map map = new HashMap<>(); - map.put("f1", "v1"); - jedis.xadd("xread-stream1", null, map); - jedis.xadd("xread-stream2", null, map); - - // Read only a single Stream - List>> streams1 = jedis.xread(1, 1L, streamQeury1); - assertEquals(1, streams1.size()); - - // Read from two Streams - Entry streamQuery2 = new AbstractMap.SimpleImmutableEntry<>( - "xread-stream1", new StreamEntryID()); - Entry streamQuery3 = new AbstractMap.SimpleImmutableEntry<>( - "xread-stream2", new StreamEntryID()); - List>> streams2 = jedis.xread(2, 1L, streamQuery2, streamQuery3); - assertEquals(2, streams2.size()); - } @Test @@ -370,67 +335,17 @@ public void xgroup() { map.put("f1", "v1"); StreamEntryID id1 = jedis.xadd("xgroup-stream", null, map); - String status = jedis.xgroupCreate("xgroup-stream", "consumer-group-name", null, false); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + assertEquals("OK", jedis.xgroupCreate("xgroup-stream", "consumer-group-name", null, false)); - status = jedis.xgroupSetID("xgroup-stream", "consumer-group-name", id1); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + assertEquals("OK", jedis.xgroupSetID("xgroup-stream", "consumer-group-name", id1)); - status = jedis.xgroupCreate("xgroup-stream", "consumer-group-name1", StreamEntryID.LAST_ENTRY, - false); - assertTrue(Keyword.OK.name().equalsIgnoreCase(status)); + assertEquals("OK", jedis.xgroupCreate("xgroup-stream", "consumer-group-name1", StreamEntryID.LAST_ENTRY, false)); jedis.xgroupDestroy("xgroup-stream", "consumer-group-name"); assertEquals(0L, jedis.xgroupDelConsumer("xgroup-stream", "consumer-group-name1","myconsumer1")); } - @Test - public void xreadGroup() { - - // Simple xreadGroup with NOACK - Map map = new HashMap<>(); - map.put("f1", "v1"); - jedis.xadd("xreadGroup-stream1", null, map); - jedis.xgroupCreate("xreadGroup-stream1", "xreadGroup-group", null, false); - Entry streamQeury1 = new AbstractMap.SimpleImmutableEntry<>( - "xreadGroup-stream1", StreamEntryID.UNRECEIVED_ENTRY); - List>> range = jedis.xreadGroup("xreadGroup-group", - "xreadGroup-consumer", 1, 0, true, streamQeury1); - assertEquals(1, range.size()); - assertEquals(1, range.get(0).getValue().size()); - - jedis.xadd("xreadGroup-stream1", null, map); - jedis.xadd("xreadGroup-stream2", null, map); - jedis.xgroupCreate("xreadGroup-stream2", "xreadGroup-group", null, false); - - // Read only a single Stream - Entry streamQeury11 = new AbstractMap.SimpleImmutableEntry<>( - "xreadGroup-stream1", StreamEntryID.UNRECEIVED_ENTRY); - List>> streams1 = jedis.xreadGroup("xreadGroup-group", - "xreadGroup-consumer", 1, 1L, true, streamQeury11); - assertEquals(1, streams1.size()); - assertEquals(1, streams1.get(0).getValue().size()); - - // Read from two Streams - Entry streamQuery2 = new AbstractMap.SimpleImmutableEntry( - "xreadGroup-stream1", new StreamEntryID()); - Entry streamQuery3 = new AbstractMap.SimpleImmutableEntry( - "xreadGroup-stream2", new StreamEntryID()); - List>> streams2 = jedis.xreadGroup("xreadGroup-group", - "xreadGroup-consumer", 1, 1L, true, streamQuery2, streamQuery3); - assertEquals(2, streams2.size()); - - // Read only fresh messages - StreamEntryID id4 = jedis.xadd("xreadGroup-stream1", null, map); - Entry streamQeuryFresh = new AbstractMap.SimpleImmutableEntry( - "xreadGroup-stream1", StreamEntryID.UNRECEIVED_ENTRY); - List>> streams3 = jedis.xreadGroup("xreadGroup-group", - "xreadGroup-consumer", 4, 100L, true, streamQeuryFresh); - assertEquals(1, streams3.size()); - assertEquals(id4, streams3.get(0).getValue().get(0).getID()); - } - @Test public void xreadGroupWithParams() { @@ -494,68 +409,6 @@ public void xack() { jedis.xack("xack-stream", "xack-group", range.get(0).getValue().get(0).getID())); } - @Test - public void xpending() { - Map map = new HashMap(); - map.put("f1", "v1"); - StreamEntryID id1 = jedis.xadd("xpendeing-stream", null, map); - - assertEquals("OK", jedis.xgroupCreate("xpendeing-stream", "xpendeing-group", null, false)); - - Entry streamQeury1 = new AbstractMap.SimpleImmutableEntry<>( - "xpendeing-stream", StreamEntryID.UNRECEIVED_ENTRY); - - // Read the event from Stream put it on pending - List>> range = jedis.xreadGroup("xpendeing-group", - "xpendeing-consumer", 1, 1L, false, streamQeury1); - assertEquals(1, range.size()); - assertEquals(1, range.get(0).getValue().size()); - assertEquals(map, range.get(0).getValue().get(0).getFields()); - - // Get the summary about the pending messages - StreamPendingSummary pendingSummary = jedis.xpending("xpendeing-stream", "xpendeing-group"); - assertEquals(1, pendingSummary.getTotal()); - assertEquals(id1, pendingSummary.getMinId()); - assertEquals(1l, pendingSummary.getConsumerMessageCount().get("xpendeing-consumer").longValue()); - - // Get the pending event - List pendingRange = jedis.xpending("xpendeing-stream", "xpendeing-group", - null, null, 3, "xpendeing-consumer"); - assertEquals(1, pendingRange.size()); - assertEquals(id1, pendingRange.get(0).getID()); - assertEquals(1, pendingRange.get(0).getDeliveredTimes()); - assertEquals("xpendeing-consumer", pendingRange.get(0).getConsumerName()); - - // Without consumer - pendingRange = jedis.xpending("xpendeing-stream", "xpendeing-group", null, null, 3, null); - assertEquals(1, pendingRange.size()); - assertEquals(id1, pendingRange.get(0).getID()); - assertEquals(1, pendingRange.get(0).getDeliveredTimes()); - assertEquals("xpendeing-consumer", pendingRange.get(0).getConsumerName()); - - // Sleep for 1000ms so we can claim events pending for more than 500ms - try { - Thread.sleep(1000); - } catch (InterruptedException e) { - e.printStackTrace(); - } - - List claimRange = jedis.xclaim("xpendeing-stream", "xpendeing-group", - "xpendeing-consumer2", 500, 0, 0, false, id1); - assertEquals(1, claimRange.size()); - - // Deleted events should return as null on XClaim - assertEquals(1, jedis.xdel("xpendeing-stream", id1)); - List claimRangeDel = jedis.xclaim("xpendeing-stream", "xpendeing-group", - "xpendeing-consumer2", 0, 0, 0, false, id1); - assertEquals(1, claimRangeDel.size()); - assertNull(claimRangeDel.get(0)); - - Long pendingMessageNum = jedis.xgroupDelConsumer("xpendeing-stream", "xpendeing-group", - "xpendeing-consumer2"); - assertEquals(1L, pendingMessageNum.longValue()); - } - @Test public void xpendingWithParams() { Map map = new HashMap<>(); @@ -844,7 +697,7 @@ public void xinfo() throws InterruptedException { // Consumer info test assertEquals(MY_CONSUMER, - consumersInfo.get(0).getConsumerInfo().get(redis.clients.jedis.StreamConsumersInfo.NAME)); + consumersInfo.get(0).getConsumerInfo().get(redis.clients.jedis.resps.StreamConsumersInfo.NAME)); assertEquals(0L, consumersInfo.get(0).getConsumerInfo().get(StreamConsumersInfo.PENDING)); assertTrue((Long) consumersInfo.get(0).getConsumerInfo().get(IDLE) > 0); @@ -875,83 +728,6 @@ public void xinfo() throws InterruptedException { } - @Test - public void xinfoBinary() throws InterruptedException { - - final String STREAM_NAME = "xadd-stream1"; - final String F1 = "f1"; - final String V1 = "v1"; - final String V2 = "v2"; - final String G1 = "G1"; - final String G2 = "G2"; - final String MY_CONSUMER = "myConsumer"; - final String MY_CONSUMER2 = "myConsumer2"; - - Map map1 = new HashMap<>(); - map1.put(F1, V1); - StreamEntryID id1 = jedis.xadd(STREAM_NAME, null, map1); - map1.put(F1, V2); - StreamEntryID id2 = jedis.xadd(STREAM_NAME, null, map1); - assertNotNull(id1); - StreamInfo streamInfo = jedis.xinfoStream(SafeEncoder.encode(STREAM_NAME)); - assertNotNull(id2); - - jedis.xgroupCreate(STREAM_NAME, G1, StreamEntryID.LAST_ENTRY, false); - Entry streamQeury11 = new AbstractMap.SimpleImmutableEntry<>( - STREAM_NAME, new StreamEntryID("0-0")); - jedis.xreadGroup(G1, MY_CONSUMER, 1, 0, false, streamQeury11); - - Thread.sleep(1); - - List groupInfo = jedis.xinfoGroup(SafeEncoder.encode(STREAM_NAME)); - List consumersInfo = jedis.xinfoConsumers(SafeEncoder.encode(STREAM_NAME), - SafeEncoder.encode(G1)); - - // Stream info test - assertEquals(2L, streamInfo.getStreamInfo().get(LENGTH)); - assertEquals(1L, streamInfo.getStreamInfo().get(RADIX_TREE_KEYS)); - assertEquals(2L, streamInfo.getStreamInfo().get(RADIX_TREE_NODES)); - assertEquals(0L, streamInfo.getStreamInfo().get(GROUPS)); - assertEquals(V1, ((StreamEntry) streamInfo.getStreamInfo().get(FIRST_ENTRY)).getFields() - .get(F1)); - assertEquals(V2, ((StreamEntry) streamInfo.getStreamInfo().get(LAST_ENTRY)).getFields().get(F1)); - assertEquals(id2, streamInfo.getStreamInfo().get(LAST_GENERATED_ID)); - - // Group info test - assertEquals(1, groupInfo.size()); - assertEquals(G1, groupInfo.get(0).getGroupInfo().get(NAME)); - assertEquals(1L, groupInfo.get(0).getGroupInfo().get(CONSUMERS)); - assertEquals(0L, groupInfo.get(0).getGroupInfo().get(PENDING)); - assertEquals(id2, groupInfo.get(0).getGroupInfo().get(LAST_DELIVERED)); - - // Consumer info test - assertEquals(MY_CONSUMER, - consumersInfo.get(0).getConsumerInfo().get(redis.clients.jedis.StreamConsumersInfo.NAME)); - assertEquals(0L, consumersInfo.get(0).getConsumerInfo().get(StreamConsumersInfo.PENDING)); - assertTrue((Long) consumersInfo.get(0).getConsumerInfo().get(IDLE) > 0); - - // test with more groups and consumers - jedis.xgroupCreate(STREAM_NAME, G2, StreamEntryID.LAST_ENTRY, false); - jedis.xreadGroup(G1, MY_CONSUMER2, 1, 0, false, streamQeury11); - jedis.xreadGroup(G2, MY_CONSUMER, 1, 0, false, streamQeury11); - jedis.xreadGroup(G2, MY_CONSUMER2, 1, 0, false, streamQeury11); - - List manyGroupsInfo = jedis.xinfoGroup(STREAM_NAME); - List manyConsumersInfo = jedis.xinfoConsumers(STREAM_NAME, G2); - - assertEquals(2, manyGroupsInfo.size()); - assertEquals(2, manyConsumersInfo.size()); - - // Not existing key - redis cli return error so we expect exception - try { - jedis.xinfoStream(SafeEncoder.encode("random")); - fail("Command should fail"); - } catch (JedisException e) { - assertEquals("ERR no such key", e.getMessage()); - } - - } - @Test public void pipeline() { Map map = new HashMap<>(); diff --git a/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/StringValuesCommandsTest.java similarity index 94% rename from src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/StringValuesCommandsTest.java index efbd794bd1..e6893cf1bd 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/StringValuesCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/StringValuesCommandsTest.java @@ -1,8 +1,10 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.assertNull; +import static org.junit.Assume.assumeFalse; +import static redis.clients.jedis.util.RedisVersionUtil.checkRedisMajorVersionNumber; import java.util.ArrayList; import java.util.List; @@ -15,7 +17,7 @@ import redis.clients.jedis.params.GetExParams; import redis.clients.jedis.params.StrAlgoLCSParams; -public class StringValuesCommandsTest extends JedisCommandTestBase { +public class StringValuesCommandsTest extends JedisCommandsTestBase { @Test public void setAndGet() { String status = jedis.set("foo", "bar"); @@ -241,6 +243,7 @@ public void psetex() { @Test public void strAlgoLcsWithLen() { + assumeFalse(checkRedisMajorVersionNumber(7)); LCSMatchResult stringMatchResult = jedis.strAlgoLCSStrings("ohmytext", "mynewtext", StrAlgoLCSParams.StrAlgoLCSParams().len()); assertEquals(stringMatchResult.getLen(), 6); @@ -248,6 +251,7 @@ public void strAlgoLcsWithLen() { @Test public void strAlgoLcs() { + assumeFalse(checkRedisMajorVersionNumber(7)); LCSMatchResult stringMatchResult = jedis.strAlgoLCSStrings("ohmytext", "mynewtext", StrAlgoLCSParams.StrAlgoLCSParams()); assertEquals(stringMatchResult.getMatchString(), "mytext"); @@ -255,6 +259,7 @@ public void strAlgoLcs() { @Test public void strAlgoLcsWithIdx() { + assumeFalse(checkRedisMajorVersionNumber(7)); LCSMatchResult stringMatchResult = jedis.strAlgoLCSStrings("ohmytext", "mynewtext", StrAlgoLCSParams.StrAlgoLCSParams().idx().withMatchLen()); assertEquals(stringMatchResult.getLen(), 6); @@ -277,15 +282,17 @@ public void strAlgoLcsWithIdx() { @Test public void strAlgoLcsWithKey() { + assumeFalse(checkRedisMajorVersionNumber(7)); jedis.mset("key1", "ohmytext", "key2", "mynewtext"); LCSMatchResult stringMatchResult = jedis.strAlgoLCSKeys("key1", "key2", StrAlgoLCSParams.StrAlgoLCSParams()); - assertEquals(stringMatchResult.getMatchString(), "mytext"); + assertEquals("mytext", stringMatchResult.getMatchString()); } @Test public void strAlgoLcsWithKeyAndIdx() { + assumeFalse(checkRedisMajorVersionNumber(7)); jedis.mset("key1", "ohmytext", "key2", "mynewtext"); LCSMatchResult stringMatchResult = jedis.strAlgoLCSKeys( "key1", "key2", diff --git a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/TransactionCommandsTest.java similarity index 73% rename from src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/TransactionCommandsTest.java index aafbcec553..b703e472d8 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/TransactionCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/TransactionCommandsTest.java @@ -1,13 +1,10 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static redis.clients.jedis.Protocol.Command.*; +import static org.junit.Assert.*; + +import static redis.clients.jedis.Protocol.Command.INCR; +import static redis.clients.jedis.Protocol.Command.GET; +import static redis.clients.jedis.Protocol.Command.SET; import java.io.IOException; import java.net.UnknownHostException; @@ -15,19 +12,17 @@ import java.util.List; import java.util.Set; import org.junit.After; - import org.junit.Before; import org.junit.Test; +import redis.clients.jedis.DefaultJedisClientConfig; import redis.clients.jedis.Jedis; -import redis.clients.jedis.Pipeline; -import redis.clients.jedis.Protocol.Keyword; import redis.clients.jedis.Response; import redis.clients.jedis.Transaction; import redis.clients.jedis.exceptions.JedisDataException; import redis.clients.jedis.util.SafeEncoder; -public class TransactionCommandsTest extends JedisCommandTestBase { +public class TransactionCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] ba = { 0x0A }; @@ -42,10 +37,7 @@ public class TransactionCommandsTest extends JedisCommandTestBase { public void setUp() throws Exception { super.setUp(); - nj = new Jedis(hnp.getHost(), hnp.getPort(), 500); - nj.connect(); - nj.auth("foobared"); - nj.flushAll(); + nj = new Jedis(hnp, DefaultJedisClientConfig.builder().timeoutMillis(500).password("foobared").build()); } @After @@ -93,10 +85,7 @@ public void watch() throws UnknownHostException, IOException { jedis.watch("mykey", "somekey"); Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); nj.set("mykey", "bar"); - nj.disconnect(); t.set("mykey", "foo"); List resp = t.exec(); @@ -107,10 +96,7 @@ public void watch() throws UnknownHostException, IOException { jedis.watch(bmykey, "foobar".getBytes()); t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); nj.set(bmykey, bbar); - nj.disconnect(); t.set(bmykey, bfoo); resp = t.exec(); @@ -123,14 +109,10 @@ public void unwatch() { jedis.watch("mykey"); jedis.get("mykey"); String val = "foo"; - String status = jedis.unwatch(); - assertEquals("OK", status); + assertEquals("OK", jedis.unwatch()); Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); nj.set("mykey", "bar"); - nj.disconnect(); t.set("mykey", val); List resp = t.exec(); @@ -141,14 +123,10 @@ public void unwatch() { jedis.watch(bmykey); jedis.get(bmykey); byte[] bval = bfoo; - status = jedis.unwatch(); - assertEquals(Keyword.OK.name(), status); + assertEquals("OK", jedis.unwatch()); t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); nj.set(bmykey, bbar); - nj.disconnect(); t.set(bmykey, bval); resp = t.exec(); @@ -181,7 +159,7 @@ public void transactionResponse() { Response string = t.get("string"); Response list = t.lpop("list"); Response hash = t.hget("hash", "foo"); - Response> zset = t.zrange("zset", 0, -1); + Response> zset = t.zrange("zset", 0, -1); Response set = t.spop("set"); t.exec(); @@ -204,7 +182,7 @@ public void transactionResponseBinary() { Response string = t.get("string".getBytes()); Response list = t.lpop("list".getBytes()); Response hash = t.hget("hash".getBytes(), "foo".getBytes()); - Response> zset = t.zrange("zset".getBytes(), 0, -1); + Response> zset = t.zrange("zset".getBytes(), 0, -1); Response set = t.spop("set".getBytes()); t.exec(); @@ -241,64 +219,60 @@ public void transactionResponseWithError() { } assertEquals("bar", r.get()); } - - @Test - public void execGetResponse() { - Transaction t = jedis.multi(); - - t.set("foo", "bar"); - t.smembers("foo"); - t.get("foo"); - - List> lr = t.execGetResponse(); - try { - lr.get(1).get(); - fail("We expect exception here!"); - } catch (JedisDataException e) { - // that is fine we should be here - } - assertEquals("bar", lr.get(2).get()); - } - - @Test - public void select() { - jedis.select(1); - jedis.set("foo", "bar"); - jedis.watch("foo"); - Transaction t = jedis.multi(); - t.select(0); - t.set("bar", "foo"); - - Jedis jedis2 = createJedis(); - jedis2.select(1); - jedis2.set("foo", "bar2"); - - List results = t.exec(); - assertNull(results); - } +// +// @Test +// public void execGetResponse() { +// Transaction t = jedis.multi(); +// +// t.set("foo", "bar"); +// t.smembers("foo"); +// t.get("foo"); +// +// List> lr = t.execGetResponse(); +// try { +// lr.get(1).get(); +// fail("We expect exception here!"); +// } catch (JedisDataException e) { +// // that is fine we should be here +// } +// assertEquals("bar", lr.get(2).get()); +// } +// +// @Test +// public void select() { +// jedis.select(1); +// jedis.set("foo", "bar"); +// jedis.watch("foo"); +// Transaction t = jedis.multi(); +// t.select(0); +// t.set("bar", "foo"); +// +// Jedis jedis2 = createJedis(); +// jedis2.select(1); +// jedis2.set("foo", "bar2"); +// +// List results = t.exec(); +// assertNull(results); +// } @Test public void testResetStateWhenInMulti() { - jedis.auth("foobared"); - Transaction t = jedis.multi(); t.set("foooo", "barrr"); jedis.resetState(); assertNull(jedis.get("foooo")); } - - @Test - public void testResetStateWhenInMultiWithinPipeline() { - jedis.auth("foobared"); - - Pipeline p = jedis.pipelined(); - p.multi(); - p.set("foooo", "barrr"); - - jedis.resetState(); - assertNull(jedis.get("foooo")); - } +// +// @Test +// public void testResetStateWhenInMultiWithinPipeline() { +// Pipeline p = jedis.pipelined(); +// p.multi(); +// p.set("foooo", "barrr"); +// +// jedis.resetState(); +// assertNull(jedis.get("foooo")); +// } @Test public void testResetStateWhenInWatch() { @@ -309,10 +283,7 @@ public void testResetStateWhenInWatch() { Transaction t = jedis.multi(); - nj.connect(); - nj.auth("foobared"); nj.set("mykey", "bar"); - nj.disconnect(); t.set("mykey", "foo"); List resp = t.exec(); @@ -323,7 +294,7 @@ public void testResetStateWhenInWatch() { @Test public void testResetStateWithFullyExecutedTransaction() { - Jedis jedis2 = new Jedis(jedis.getClient().getHost(), jedis.getClient().getPort()); + Jedis jedis2 = createJedis(); jedis2.auth("foobared"); Transaction t = jedis2.multi(); @@ -339,7 +310,7 @@ public void testResetStateWithFullyExecutedTransaction() { } @Test - public void testCloseable() throws IOException { + public void testCloseable() { // we need to test with fresh instance of Jedis Jedis jedis2 = new Jedis(hnp.getHost(), hnp.getPort(), 500); jedis2.auth("foobared"); @@ -353,7 +324,7 @@ public void testCloseable() throws IOException { try { transaction.exec(); fail("close should discard transaction"); - } catch (JedisDataException e) { + } catch (IllegalStateException e) { assertTrue(e.getMessage().contains("EXEC without MULTI")); // pass } @@ -372,7 +343,7 @@ public void testTransactionWithGeneralCommand() { Response string = t.get("string"); Response list = t.lpop("list"); Response hash = t.hget("hash", "foo"); - Response> zset = t.zrange("zset", 0, -1); + Response> zset = t.zrange("zset", 0, -1); Response set = t.spop("set"); Response x = t.sendCommand(GET, "x"); t.exec(); @@ -405,21 +376,4 @@ public void transactionResponseWithErrorWithGeneralCommand() { assertEquals("bar", r.get()); assertEquals("1", SafeEncoder.encode((byte[]) x.get())); } - - @Test - public void unwatchWithinMulti() { - final String key = "foo"; - final String val = "bar"; - jedis.set(key, val); - jedis.watch(key); - - List exp = new ArrayList<>(); - Transaction t = jedis.multi(); - t.get(key); exp.add(val); - t.unwatch(); exp.add("OK"); - t.get(key); exp.add(val); - List res = t.exec(); - assertEquals(exp, res); - } - } \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java b/src/test/java/redis/clients/jedis/commands/jedis/VariadicCommandsTest.java similarity index 89% rename from src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java rename to src/test/java/redis/clients/jedis/commands/jedis/VariadicCommandsTest.java index 449a248f28..35c3127cc9 100644 --- a/src/test/java/redis/clients/jedis/tests/commands/VariadicCommandsTest.java +++ b/src/test/java/redis/clients/jedis/commands/jedis/VariadicCommandsTest.java @@ -1,20 +1,16 @@ -package redis.clients.jedis.tests.commands; +package redis.clients.jedis.commands.jedis; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArrayListEquals; -import static redis.clients.jedis.tests.utils.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; import java.util.ArrayList; import java.util.HashMap; -import java.util.LinkedHashSet; import java.util.List; import java.util.Map; -import java.util.Set; - import org.junit.Test; -public class VariadicCommandsTest extends JedisCommandTestBase { +public class VariadicCommandsTest extends JedisCommandsTestBase { final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; @@ -160,7 +156,7 @@ public void zrem() { long status = jedis.zrem("foo", "bar", "car"); - Set expected = new LinkedHashSet(); + List expected = new ArrayList(); expected.add("foo1"); assertEquals(2, status); @@ -179,11 +175,11 @@ public void zrem() { status = jedis.zrem(bfoo, bbar, bcar); - Set bexpected = new LinkedHashSet(); - bexpected.add(bfoo); + List bexpected = new ArrayList(); + bexpected.add(bfoo1); assertEquals(2, status); - assertByteArraySetEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); status = jedis.zrem(bfoo, bbar, bcar); assertEquals(0, status); diff --git a/src/test/java/redis/clients/jedis/commands/unified/AllKindOfValuesCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/AllKindOfValuesCommandsTestBase.java new file mode 100644 index 0000000000..5981aa2009 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/AllKindOfValuesCommandsTestBase.java @@ -0,0 +1,801 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; + +import static redis.clients.jedis.Protocol.Command.BLPOP; +import static redis.clients.jedis.Protocol.Command.GET; +import static redis.clients.jedis.Protocol.Command.HGETALL; +import static redis.clients.jedis.Protocol.Command.LRANGE; +import static redis.clients.jedis.Protocol.Command.PING; +import static redis.clients.jedis.Protocol.Command.RPUSH; +import static redis.clients.jedis.Protocol.Command.SET; +import static redis.clients.jedis.Protocol.Command.XINFO; +import static redis.clients.jedis.util.SafeEncoder.encode; +import static redis.clients.jedis.util.SafeEncoder.encodeObject; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.params.SetParams.setParams; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContains; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import org.junit.Test; + +import redis.clients.jedis.StreamEntryID; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.params.RestoreParams; +import redis.clients.jedis.exceptions.JedisDataException; + +public abstract class AllKindOfValuesCommandsTestBase extends UnifiedJedisCommandsTestBase { + + protected final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + protected final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x0A }; + protected final byte[] bfoo2 = { 0x01, 0x02, 0x03, 0x04, 0x0B }; + protected final byte[] bfoo3 = { 0x01, 0x02, 0x03, 0x04, 0x0C }; + protected final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + protected final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + protected final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + protected final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + + protected final byte[] bfoobar = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08 }; + protected final byte[] bfoostar = { 0x01, 0x02, 0x03, 0x04, '*' }; + protected final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + + protected final byte[] bnx = { 0x6E, 0x78 }; + protected final byte[] bex = { 0x65, 0x78 }; + final int expireSeconds = 2; + + @Test + public void exists() { + String status = jedis.set("foo", "bar"); + assertEquals("OK", status); + + status = jedis.set(bfoo, bbar); + assertEquals("OK", status); + + assertTrue(jedis.exists("foo")); + + assertTrue(jedis.exists(bfoo)); + + assertEquals(1L, jedis.del("foo")); + + assertEquals(1L, jedis.del(bfoo)); + + assertFalse(jedis.exists("foo")); + + assertFalse(jedis.exists(bfoo)); + } + + @Test + public void existsMany() { + String status = jedis.set("foo1", "bar1"); + assertEquals("OK", status); + + status = jedis.set("foo2", "bar2"); + assertEquals("OK", status); + + assertEquals(2L, jedis.exists("foo1", "foo2")); + + assertEquals(1L, jedis.del("foo1")); + + assertEquals(1L, jedis.exists("foo1", "foo2")); + } + + @Test + public void del() { + jedis.set("foo1", "bar1"); + jedis.set("foo2", "bar2"); + jedis.set("foo3", "bar3"); + + assertEquals(3L, jedis.del("foo1", "foo2", "foo3")); + + assertFalse(jedis.exists("foo1")); + assertFalse(jedis.exists("foo2")); + assertFalse(jedis.exists("foo3")); + + jedis.set("foo1", "bar1"); + + assertEquals(1L, jedis.del("foo1", "foo2")); + + assertEquals(0L, jedis.del("foo1", "foo2")); + + // Binary ... + jedis.set(bfoo1, bbar1); + jedis.set(bfoo2, bbar2); + jedis.set(bfoo3, bbar3); + + assertEquals(3L, jedis.del(bfoo1, bfoo2, bfoo3)); + + assertFalse(jedis.exists(bfoo1)); + assertFalse(jedis.exists(bfoo2)); + assertFalse(jedis.exists(bfoo3)); + + jedis.set(bfoo1, bbar1); + + assertEquals(1, jedis.del(bfoo1, bfoo2)); + + assertEquals(0, jedis.del(bfoo1, bfoo2)); + } + + @Test + public void unlink() { + jedis.set("foo1", "bar1"); + jedis.set("foo2", "bar2"); + jedis.set("foo3", "bar3"); + + assertEquals(3, jedis.unlink("foo1", "foo2", "foo3")); + + assertEquals(0, jedis.exists("foo1", "foo2", "foo3")); + + jedis.set("foo1", "bar1"); + + assertEquals(1, jedis.unlink("foo1", "foo2")); + + assertEquals(0, jedis.unlink("foo1", "foo2")); + + jedis.set("foo", "bar"); + assertEquals(1, jedis.unlink("foo")); + assertFalse(jedis.exists("foo")); + + // Binary + jedis.set(bfoo1, bbar1); + jedis.set(bfoo2, bbar2); + jedis.set(bfoo3, bbar3); + + assertEquals(3, jedis.unlink(bfoo1, bfoo2, bfoo3)); + + assertEquals(0, jedis.exists(bfoo1, bfoo2, bfoo3)); + + jedis.set(bfoo1, bbar1); + + assertEquals(1, jedis.unlink(bfoo1, bfoo2)); + + assertEquals(0, jedis.unlink(bfoo1, bfoo2)); + + jedis.set(bfoo, bbar); + assertEquals(1, jedis.unlink(bfoo)); + assertFalse(jedis.exists(bfoo)); + } + + @Test + public void type() { + jedis.set("foo", "bar"); + assertEquals("string", jedis.type("foo")); + + // Binary + jedis.set(bfoo, bbar); + assertEquals("string", jedis.type(bfoo)); + } + + @Test + public void keys() { + jedis.set("foo", "bar"); + jedis.set("foobar", "bar"); + + Set keys = jedis.keys("foo*"); + Set expected = new HashSet<>(); + expected.add("foo"); + expected.add("foobar"); + assertEquals(expected, keys); + + expected = new HashSet<>(); + keys = jedis.keys("bar*"); + + assertEquals(expected, keys); + + // Binary + jedis.set(bfoo, bbar); + jedis.set(bfoobar, bbar); + + Set bkeys = jedis.keys(bfoostar); + assertEquals(2, bkeys.size()); + assertCollectionContains(bkeys, bfoo); + assertCollectionContains(bkeys, bfoobar); + + bkeys = jedis.keys(bbarstar); + + assertEquals(0, bkeys.size()); + } + + @Test + public void randomKey() { + assertNull(jedis.randomKey()); + + for (int i = 0; i < 100; i++) { + jedis.set("foo" + i, "bar"+i); + } + + String key = jedis.randomKey(); + assertNotNull(key); + assertTrue(key.startsWith("foo")); + assertEquals(key.replace("foo", "bar"), jedis.get(key)); + } + + @Test + public void rename() { + jedis.set("foo", "bar"); + String status = jedis.rename("foo", "bar"); + assertEquals("OK", status); + + assertNull(jedis.get("foo")); + + assertEquals("bar", jedis.get("bar")); + + // Binary + jedis.set(bfoo, bbar); + String bstatus = jedis.rename(bfoo, bbar); + assertEquals("OK", bstatus); + + assertNull(jedis.get(bfoo)); + + assertArrayEquals(bbar, jedis.get(bbar)); + } + + @Test + public void renameOldAndNewAreTheSame() { + assertEquals("OK", jedis.set("foo", "bar")); + assertEquals("OK", jedis.rename("foo", "foo")); + + // Binary + assertEquals("OK", jedis.set(bfoo, bbar)); + assertEquals("OK", jedis.rename(bfoo, bfoo)); + } + + @Test + public void renamenx() { + jedis.set("foo", "bar"); + assertEquals(1, jedis.renamenx("foo", "bar")); + + jedis.set("foo", "bar"); + assertEquals(0, jedis.renamenx("foo", "bar")); + + // Binary + jedis.set(bfoo, bbar); + assertEquals(1, jedis.renamenx(bfoo, bbar)); + + jedis.set(bfoo, bbar); + assertEquals(0, jedis.renamenx(bfoo, bbar)); + } + + @Test + public void dbSize() { + assertEquals(0, jedis.dbSize()); + + jedis.set("foo", "bar"); + assertEquals(1, jedis.dbSize()); + + // Binary + jedis.set(bfoo, bbar); + assertEquals(2, jedis.dbSize()); + } + + @Test + public void expire() { + assertEquals(0, jedis.expire("foo", 20L)); + + jedis.set("foo", "bar"); + assertEquals(1, jedis.expire("foo", 20L)); + + // Binary + assertEquals(0, jedis.expire(bfoo, 20L)); + + jedis.set(bfoo, bbar); + assertEquals(1, jedis.expire(bfoo, 20L)); + } + + @Test + public void expireAt() { + long unixTime = (System.currentTimeMillis() / 1000L) + 20; + + assertEquals(0, jedis.expireAt("foo", unixTime)); + + jedis.set("foo", "bar"); + unixTime = (System.currentTimeMillis() / 1000L) + 20; + assertEquals(1, jedis.expireAt("foo", unixTime)); + + // Binary + assertEquals(0, jedis.expireAt(bfoo, unixTime)); + + jedis.set(bfoo, bbar); + unixTime = (System.currentTimeMillis() / 1000L) + 20; + assertEquals(1, jedis.expireAt(bfoo, unixTime)); + } + + @Test + public void ttl() { + assertEquals(-2, jedis.ttl("foo")); + + jedis.set("foo", "bar"); + assertEquals(-1, jedis.ttl("foo")); + + jedis.expire("foo", 20); + long ttl = jedis.ttl("foo"); + assertTrue(ttl >= 0 && ttl <= 20); + + // Binary + assertEquals(-2, jedis.ttl(bfoo)); + + jedis.set(bfoo, bbar); + assertEquals(-1, jedis.ttl(bfoo)); + + jedis.expire(bfoo, 20); + long bttl = jedis.ttl(bfoo); + assertTrue(bttl >= 0 && bttl <= 20); + } + + @Test + public void touch() throws Exception { + assertEquals(0, jedis.touch("foo1", "foo2", "foo3")); + + jedis.set("foo1", "bar1"); + + Thread.sleep(1100); // little over 1 sec + assertTrue(jedis.objectIdletime("foo1") > 0); + + assertEquals(1, jedis.touch("foo1")); + assertEquals(0L, jedis.objectIdletime("foo1").longValue()); + + assertEquals(1, jedis.touch("foo1", "foo2", "foo3")); + + jedis.set("foo2", "bar2"); + + jedis.set("foo3", "bar3"); + + assertEquals(3, jedis.touch("foo1", "foo2", "foo3")); + + // Binary + assertEquals(0, jedis.touch(bfoo1, bfoo2, bfoo3)); + + jedis.set(bfoo1, bbar1); + + Thread.sleep(1100); // little over 1 sec + assertTrue(jedis.objectIdletime(bfoo1) > 0); + + assertEquals(1, jedis.touch(bfoo1)); + assertEquals(0L, jedis.objectIdletime(bfoo1).longValue()); + + assertEquals(1, jedis.touch(bfoo1, bfoo2, bfoo3)); + + jedis.set(bfoo2, bbar2); + + jedis.set(bfoo3, bbar3); + + assertEquals(3, jedis.touch(bfoo1, bfoo2, bfoo3)); + } + + @Test + public void persist() { + jedis.setex("foo", 60 * 60, "bar"); + assertTrue(jedis.ttl("foo") > 0); + assertEquals(1, jedis.persist("foo")); + assertEquals(-1, jedis.ttl("foo")); + + // Binary + jedis.setex(bfoo, 60 * 60, bbar); + assertTrue(jedis.ttl(bfoo) > 0); + assertEquals(1, jedis.persist(bfoo)); + assertEquals(-1, jedis.ttl(bfoo)); + } + + @Test + public void dumpAndRestore() { + jedis.set("foo1", "bar"); + byte[] sv = jedis.dump("foo1"); + jedis.restore("foo2", 0, sv); + assertEquals("bar", jedis.get("foo2")); + + jedis.set(bfoo1, bbar); + sv = jedis.dump(bfoo1); + jedis.restore(bfoo2, 0, sv); + assertArrayEquals(bbar, jedis.get(bfoo2)); + } + + @Test + public void restoreParams() { + jedis.set("foo", "bar"); + jedis.set("from", "a"); + byte[] serialized = jedis.dump("from"); + + try { + jedis.restore("foo", 0, serialized); + fail("Simple restore on a existing key should fail"); + } catch (JedisDataException e) { + // should be here + } + try { + jedis.restore("foo", 0, serialized, RestoreParams.restoreParams()); + fail("Simple restore on a existing key should fail"); + } catch (JedisDataException e) { + // should be here + } + assertEquals("bar", jedis.get("foo")); + + jedis.restore("foo", 1000, serialized, RestoreParams.restoreParams().replace()); + assertEquals("a", jedis.get("foo")); + assertTrue(jedis.pttl("foo") <= 1000); + + jedis.restore("bar", System.currentTimeMillis() + 1000, serialized, RestoreParams.restoreParams().replace().absTtl()); + assertTrue(jedis.pttl("bar") <= 1000); + + jedis.restore("bar1", 1000, serialized, RestoreParams.restoreParams().replace().idleTime(1000)); + assertEquals(1000, jedis.objectIdletime("bar1").longValue()); + } + + @Test + public void pexpire() { + assertEquals(0, jedis.pexpire("foo", 10000)); + + jedis.set("foo1", "bar1"); + assertEquals(1, jedis.pexpire("foo1", 10000)); + + jedis.set("foo2", "bar2"); + assertEquals(1, jedis.pexpire("foo2", 200000000000L)); + + long pttl = jedis.pttl("foo2"); + assertTrue(pttl > 100000000000L); + + // Binary + assertEquals(0, jedis.pexpire(bfoo, 10000)); + + jedis.set(bfoo, bbar); + assertEquals(1, jedis.pexpire(bfoo, 10000)); + } + + @Test + public void pexpireAt() { + long unixTime = (System.currentTimeMillis()) + 10000; + + assertEquals(0, jedis.pexpireAt("foo", unixTime)); + + jedis.set("foo", "bar"); + assertEquals(1, jedis.pexpireAt("foo", unixTime)); + + // Binary + assertEquals(0, jedis.pexpireAt(bfoo, unixTime)); + + jedis.set(bfoo, bbar); + assertEquals(1, jedis.pexpireAt(bfoo, unixTime)); + } + + @Test + public void pttl() { + assertEquals(-2, jedis.pttl("foo")); + + jedis.set("foo", "bar"); + assertEquals(-1, jedis.pttl("foo")); + + jedis.pexpire("foo", 20000); + long pttl = jedis.pttl("foo"); + assertTrue(pttl >= 0 && pttl <= 20000); + + // Binary + assertEquals(-2, jedis.pttl(bfoo)); + + jedis.set(bfoo, bbar); + assertEquals(-1, jedis.pttl(bfoo)); + + jedis.pexpire(bfoo, 20000); + pttl = jedis.pttl(bfoo); + assertTrue(pttl >= 0 && pttl <= 20000); + } + + @Test + public void psetex() { + long pttl; + + jedis.psetex("foo", 200000000000L, "bar"); + pttl = jedis.pttl("foo"); + assertTrue(pttl > 100000000000L); + + // Binary + jedis.psetex(bfoo, 200000000000L, bbar); + pttl = jedis.pttl(bfoo); + assertTrue(pttl > 100000000000L); + } + + @Test + public void scan() { + jedis.set("b", "b"); + jedis.set("a", "a"); + + ScanResult result = jedis.scan(SCAN_POINTER_START); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void scanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.set("b", "b"); + jedis.set("a", "a"); + jedis.set("aa", "aa"); + ScanResult result = jedis.scan(SCAN_POINTER_START, params); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bfoostar); + + jedis.set(bfoo1, bbar); + jedis.set(bfoo2, bbar); + jedis.set(bfoo3, bbar); + + ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void scanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + for (int i = 0; i < 10; i++) { + jedis.set("a" + i, "a" + i); + } + + ScanResult result = jedis.scan(SCAN_POINTER_START, params); + + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.set(bfoo1, bbar); + jedis.set(bfoo2, bbar); + jedis.set(bfoo3, bbar); + + ScanResult bResult = jedis.scan(SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void scanType() { + ScanParams noParams = new ScanParams(); + ScanParams pagingParams = new ScanParams().count(4); + + jedis.set("a", "a"); + jedis.hset("b", "b", "b"); + jedis.set("c", "c"); + jedis.sadd("d", "d"); + jedis.set("e", "e"); + jedis.zadd("f", 0d, "f"); + jedis.set("g", "g"); + + // string + ScanResult scanResult; + + scanResult = jedis.scan(SCAN_POINTER_START, pagingParams, "string"); + assertFalse(scanResult.isCompleteIteration()); + int page1Count = scanResult.getResult().size(); + scanResult = jedis.scan(scanResult.getCursor(), pagingParams, "string"); + assertTrue(scanResult.isCompleteIteration()); + int page2Count = scanResult.getResult().size(); + assertEquals(4, page1Count + page2Count); + + + scanResult = jedis.scan(SCAN_POINTER_START, noParams, "hash"); + assertEquals(Collections.singletonList("b"), scanResult.getResult()); + scanResult = jedis.scan(SCAN_POINTER_START, noParams, "set"); + assertEquals(Collections.singletonList("d"), scanResult.getResult()); + scanResult = jedis.scan(SCAN_POINTER_START, noParams, "zset"); + assertEquals(Collections.singletonList("f"), scanResult.getResult()); + + // binary + final byte[] string = "string".getBytes(); + final byte[] hash = "hash".getBytes(); + final byte[] set = "set".getBytes(); + final byte[] zset = "zset".getBytes(); + + ScanResult binaryResult; + + jedis.set("a", "a"); + jedis.hset("b", "b", "b"); + jedis.set("c", "c"); + jedis.sadd("d", "d"); + jedis.set("e", "e"); + jedis.zadd("f", 0d, "f"); + jedis.set("g", "g"); + + binaryResult = jedis.scan(SCAN_POINTER_START_BINARY, pagingParams, string); + assertFalse(binaryResult.isCompleteIteration()); + page1Count = binaryResult.getResult().size(); + binaryResult = jedis.scan(binaryResult.getCursorAsBytes(), pagingParams, string); + assertTrue(binaryResult.isCompleteIteration()); + page2Count = binaryResult.getResult().size(); + assertEquals(4, page1Count + page2Count); + + binaryResult = jedis.scan(SCAN_POINTER_START_BINARY, noParams, hash); + assertByteArrayListEquals(Collections.singletonList(new byte[]{98}), binaryResult.getResult()); + binaryResult = jedis.scan(SCAN_POINTER_START_BINARY, noParams, set); + assertByteArrayListEquals(Collections.singletonList(new byte[]{100}), binaryResult.getResult()); + binaryResult = jedis.scan(SCAN_POINTER_START_BINARY, noParams, zset); + assertByteArrayListEquals(Collections.singletonList(new byte[]{102}), binaryResult.getResult()); + } + + @Test + public void scanIsCompleteIteration() { + for (int i = 0; i < 100; i++) { + jedis.set("a" + i, "a" + i); + } + + ScanResult result = jedis.scan(SCAN_POINTER_START); + // note: in theory Redis would be allowed to already return all results on the 1st scan, + // but in practice this never happens for data sets greater than a few tens + // see: https://redis.io/commands/scan#number-of-elements-returned-at-every-scan-call + assertFalse(result.isCompleteIteration()); + + result = scanCompletely(result.getCursor()); + + assertNotNull(result); + assertTrue(result.isCompleteIteration()); + } + + private ScanResult scanCompletely(String cursor) { + ScanResult scanResult; + do { + scanResult = jedis.scan(cursor); + cursor = scanResult.getCursor(); + } while (!SCAN_POINTER_START.equals(scanResult.getCursor())); + + return scanResult; + } + + @Test + public void setNxExAndGet() { + assertEquals("OK", jedis.set("hello", "world", setParams().nx().ex(expireSeconds))); + assertEquals("world", jedis.get("hello")); + + assertNull(jedis.set("hello", "bar", setParams().nx().ex(expireSeconds))); + assertEquals("world", jedis.get("hello")); + + long ttl = jedis.ttl("hello"); + assertTrue(ttl > 0 && ttl <= expireSeconds); + + // binary + byte[] bworld = { 0x77, 0x6F, 0x72, 0x6C, 0x64 }; + byte[] bhello = { 0x68, 0x65, 0x6C, 0x6C, 0x6F }; + + assertEquals("OK", jedis.set(bworld, bhello, setParams().nx().ex(expireSeconds))); + assertArrayEquals(bhello, jedis.get(bworld)); + + assertNull(jedis.set(bworld, bbar, setParams().nx().ex(expireSeconds))); + assertArrayEquals(bhello, jedis.get(bworld)); + + long bttl = jedis.ttl(bworld); + assertTrue(bttl > 0 && bttl <= expireSeconds); + } + + @Test + public void setGetOptionTest() { + assertEquals("OK", jedis.set("hello", "world")); + + // GET old value + assertEquals("world", jedis.set("hello", "jedis", setParams().get())); + + assertEquals("jedis", jedis.get("hello")); + + // GET null value + assertNull(jedis.set("key", "value", setParams().get())); + } + + @Test + public void sendCommandTest() { + Object obj = jedis.sendCommand(SET, "x", "1"); + String returnValue = encode((byte[]) obj); + assertEquals("OK", returnValue); + obj = jedis.sendCommand(GET, "x"); + returnValue = encode((byte[]) obj); + assertEquals("1", returnValue); + + jedis.sendCommand(RPUSH, "foo", "a"); + jedis.sendCommand(RPUSH, "foo", "b"); + jedis.sendCommand(RPUSH, "foo", "c"); + + obj = jedis.sendCommand(LRANGE, "foo", "0", "2"); + List list = (List) obj; + List expected = new ArrayList<>(3); + expected.add("a".getBytes()); + expected.add("b".getBytes()); + expected.add("c".getBytes()); + for (int i = 0; i < 3; i++) + assertArrayEquals(expected.get(i), list.get(i)); + + assertEquals("PONG", encode((byte[]) jedis.sendCommand(PING))); + } + + @Test + public void sendBlockingCommandTest() { + assertNull(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L))); + + jedis.sendCommand(RPUSH, "foo", "bar"); + assertEquals(Arrays.asList("foo", "bar"), + encodeObject(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L)))); + + assertNull(jedis.sendBlockingCommand(BLPOP, "foo", Long.toString(1L))); + } + + @Test + public void encodeCompleteResponse() { + HashMap entry = new HashMap<>(); + entry.put("foo", "bar"); + jedis.xadd("mystream", StreamEntryID.NEW_ENTRY, entry); + String status = jedis.xgroupCreate("mystream", "mygroup", null, false); + + Object obj = jedis.sendCommand(XINFO, "STREAM", "mystream"); + List encodeObj = (List) encodeObject(obj); + + assertEquals(14, encodeObj.size()); + assertEquals("length", encodeObj.get(0)); + assertEquals(1L, encodeObj.get(1)); + + List entryAsList = new ArrayList<>(2); + entryAsList.add("foo"); + entryAsList.add("bar"); + + assertEquals(entryAsList, ((List) encodeObj.get(11)).get(1)); + + assertEquals("PONG", encodeObject(jedis.sendCommand(PING))); + + entry.put("foo2", "bar2"); + jedis.hset("hash:test:encode", entry); + encodeObj = (List) encodeObject(jedis.sendCommand(HGETALL, "hash:test:encode")); + + assertEquals(4, encodeObj.size()); + assertTrue(encodeObj.contains("foo")); + assertTrue(encodeObj.contains("foo2")); + } + + @Test + public void copy() { + assertFalse(jedis.copy("unknown", "foo", false)); + + jedis.set("foo1", "bar"); + assertTrue(jedis.copy("foo1", "foo2", false)); + assertEquals("bar", jedis.get("foo2")); + + // replace + jedis.set("foo1", "bar1"); + assertTrue(jedis.copy("foo1", "foo2", true)); + assertEquals("bar1", jedis.get("foo2")); + + // Binary + assertFalse(jedis.copy(bfoobar, bfoo, false)); + + jedis.set(bfoo1, bbar); + assertTrue(jedis.copy(bfoo1, bfoo2, false)); + assertArrayEquals(bbar, jedis.get(bfoo2)); + + // replace + jedis.set(bfoo1, bbar1); + assertTrue(jedis.copy(bfoo1, bfoo2, true)); + assertArrayEquals(bbar1, jedis.get(bfoo2)); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/BinaryValuesCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/BinaryValuesCommandsTestBase.java new file mode 100644 index 0000000000..1c5f14b266 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/BinaryValuesCommandsTestBase.java @@ -0,0 +1,363 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import static redis.clients.jedis.Protocol.Command.BLPOP; +import static redis.clients.jedis.Protocol.Command.GET; +import static redis.clients.jedis.Protocol.Command.LRANGE; +import static redis.clients.jedis.Protocol.Command.RPUSH; +import static redis.clients.jedis.Protocol.Command.SET; +import static redis.clients.jedis.params.SetParams.setParams; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import redis.clients.jedis.Protocol; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.GetExParams; +import redis.clients.jedis.util.SafeEncoder; + +public abstract class BinaryValuesCommandsTestBase extends UnifiedJedisCommandsTestBase { + protected byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + protected byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + protected byte[] bxx = { 0x78, 0x78 }; + protected byte[] bnx = { 0x6E, 0x78 }; + protected byte[] bex = { 0x65, 0x78 }; + protected byte[] bpx = { 0x70, 0x78 }; + protected int expireSeconds = 2; + protected long expireMillis = expireSeconds * 1000; + protected byte[] binaryValue; + + @Before + public void startUp() { + StringBuilder sb = new StringBuilder(); + + for (int n = 0; n < 1000; n++) { + sb.append("A"); + } + + binaryValue = sb.toString().getBytes(); + } + + @Test + public void setAndGet() { + assertEquals("OK", jedis.set(bfoo, binaryValue)); + + assertArrayEquals(binaryValue, jedis.get(bfoo)); + + assertNull(jedis.get(bbar)); + } + + @Test + public void setNxExAndGet() { + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + + assertArrayEquals(binaryValue, jedis.get(bfoo)); + + assertNull(jedis.get(bbar)); + } + + @Test + public void setIfNotExistAndGet() { + assertEquals("OK", jedis.set(bfoo, binaryValue)); + // nx should fail if value exists + assertNull(jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + + assertArrayEquals(binaryValue, jedis.get(bfoo)); + + assertNull(jedis.get(bbar)); + } + + @Test + public void setIfExistAndGet() { + assertEquals("OK", jedis.set(bfoo, binaryValue)); + // nx should fail if value exists + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().xx().ex(expireSeconds))); + + byte[] value = jedis.get(bfoo); + assertArrayEquals(binaryValue, value); + + assertNull(jedis.get(bbar)); + } + + @Test + public void setFailIfNotExistAndGet() { + // xx should fail if value does NOT exists + assertNull(jedis.set(bfoo, binaryValue, setParams().xx().ex(expireSeconds))); + } + + @Test + public void setAndExpireMillis() { + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().px(expireMillis))); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= expireSeconds); + } + + @Test + public void setAndExpire() { + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= expireSeconds); + } + + @Test + public void setAndKeepttl() { + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().nx().ex(expireSeconds))); + assertEquals("OK", jedis.set(bfoo, binaryValue, setParams().keepttl())); + long ttl = jedis.ttl(bfoo); + assertTrue(0 < ttl && ttl <= expireSeconds); + jedis.set(bfoo, binaryValue); + ttl = jedis.ttl(bfoo); + assertTrue(ttl < 0); + } + + @Test + public void setAndPxat() { + assertEquals("OK", jedis.set(bfoo, binaryValue, + setParams().nx().pxAt(System.currentTimeMillis() + expireMillis))); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= expireSeconds); + } + + @Test + public void setAndExat() { + assertEquals("OK", jedis.set(bfoo, binaryValue, + setParams().nx().exAt(System.currentTimeMillis() / 1000 + expireSeconds))); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= expireSeconds); + } + + @Test + public void getSet() { + assertNull(jedis.getSet(bfoo, binaryValue)); + assertArrayEquals(binaryValue, jedis.get(bfoo)); + } + + @Test + public void getDel() { + assertEquals("OK", jedis.set(bfoo, bbar)); + + assertArrayEquals(bbar, jedis.getDel(bfoo)); + + assertNull(jedis.get(bfoo)); + } + + @Test + public void getEx() { + assertNull(jedis.getEx(bfoo, GetExParams.getExParams().ex(1))); + jedis.set(bfoo, bbar); + + assertArrayEquals(bbar, jedis.getEx(bfoo, GetExParams.getExParams().ex(10))); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= 10); + + assertArrayEquals(bbar, jedis.getEx(bfoo, GetExParams.getExParams().px(20000l))); + ttl = jedis.ttl(bfoo); + assertTrue(ttl > 10 && ttl <= 20); + + assertArrayEquals(bbar, jedis.getEx(bfoo, GetExParams.getExParams().exAt(System.currentTimeMillis() / 1000 + 30))); + ttl = jedis.ttl(bfoo); + assertTrue(ttl > 20 && ttl <= 30); + + assertArrayEquals(bbar, jedis.getEx(bfoo, GetExParams.getExParams().pxAt(System.currentTimeMillis() + 40000l))); + ttl = jedis.ttl(bfoo); + assertTrue(ttl > 30 && ttl <= 40); + + assertArrayEquals(bbar, jedis.getEx(bfoo, GetExParams.getExParams().persist())); + assertEquals(-1L, jedis.ttl(bfoo)); + } + + @Test + public void mget() { + List values = jedis.mget(bfoo, bbar); + List expected = new ArrayList<>(); + expected.add(null); + expected.add(null); + + assertByteArrayListEquals(expected, values); + + jedis.set(bfoo, binaryValue); + + expected = new ArrayList<>(); + expected.add(binaryValue); + expected.add(null); + assertByteArrayListEquals(expected, jedis.mget(bfoo, bbar)); + + jedis.set(bbar, bfoo); + + expected = new ArrayList<>(); + expected.add(binaryValue); + expected.add(bfoo); + assertByteArrayListEquals(expected, jedis.mget(bfoo, bbar)); + } + + @Test + public void setnx() { + assertEquals(1, jedis.setnx(bfoo, binaryValue)); + assertArrayEquals(binaryValue, jedis.get(bfoo)); + + assertEquals(0, jedis.setnx(bfoo, bbar)); + assertArrayEquals(binaryValue, jedis.get(bfoo)); + } + + @Test + public void setex() { + assertEquals("OK", jedis.setex(bfoo, 20, binaryValue)); + long ttl = jedis.ttl(bfoo); + assertTrue(ttl > 0 && ttl <= 20); + } + + @Test + public void mset() { + assertEquals("OK", jedis.mset(bfoo, binaryValue, bbar, bfoo)); + assertArrayEquals(binaryValue, jedis.get(bfoo)); + assertArrayEquals(bfoo, jedis.get(bbar)); + } + + @Test + public void msetnx() { + assertEquals(1, jedis.msetnx(bfoo, binaryValue, bbar, bfoo)); + assertArrayEquals(binaryValue, jedis.get(bfoo)); + assertArrayEquals(bfoo, jedis.get(bbar)); + + assertEquals(0, jedis.msetnx(bfoo, bbar, "bar2".getBytes(), "foo2".getBytes())); + assertArrayEquals(binaryValue, jedis.get(bfoo)); + assertArrayEquals(bfoo, jedis.get(bbar)); + } + + @Test + public void incr() { + assertEquals(1, jedis.incr(bfoo)); + assertEquals(2, jedis.incr(bfoo)); + } + + @Test(expected = JedisDataException.class) + public void incrWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.incr(bfoo); + } + + @Test + public void incrBy() { + assertEquals(2, jedis.incrBy(bfoo, 2)); + assertEquals(4, jedis.incrBy(bfoo, 2)); + } + + @Test(expected = JedisDataException.class) + public void incrByWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.incrBy(bfoo, 2); + } + + @Test + public void incrByFloat() { + assertEquals(10.5, jedis.incrByFloat(bfoo, 10.5), 0.0); + assertEquals(10.6, jedis.incrByFloat(bfoo, 0.1), 0.0); + } + + @Test + public void decr() { + assertEquals(-1, jedis.decr(bfoo)); + assertEquals(-2, jedis.decr(bfoo)); + } + + @Test(expected = JedisDataException.class) + public void decrWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.decr(bfoo); + } + + @Test + public void decrBy() { + assertEquals(-2, jedis.decrBy(bfoo, 2)); + assertEquals(-4, jedis.decrBy(bfoo, 2)); + } + + @Test(expected = JedisDataException.class) + public void decrByWrongValue() { + jedis.set(bfoo, binaryValue); + jedis.decrBy(bfoo, 2); + } + + @Test + public void append() { + byte[] first512 = new byte[512]; + System.arraycopy(binaryValue, 0, first512, 0, 512); + assertEquals(512, jedis.append(bfoo, first512)); + assertArrayEquals(first512, jedis.get(bfoo)); + + byte[] rest = new byte[binaryValue.length - 512]; + System.arraycopy(binaryValue, 512, rest, 0, binaryValue.length - 512); + assertEquals(binaryValue.length, jedis.append(bfoo, rest)); + + assertArrayEquals(binaryValue, jedis.get(bfoo)); + } + + @Test + public void substr() { + jedis.set(bfoo, binaryValue); + + byte[] first512 = new byte[512]; + System.arraycopy(binaryValue, 0, first512, 0, 512); + byte[] rfirst512 = jedis.substr(bfoo, 0, 511); + assertArrayEquals(first512, rfirst512); + + byte[] last512 = new byte[512]; + System.arraycopy(binaryValue, binaryValue.length - 512, last512, 0, 512); + assertArrayEquals(last512, jedis.substr(bfoo, -512, -1)); + + assertArrayEquals(binaryValue, jedis.substr(bfoo, 0, -1)); + + assertArrayEquals(last512, jedis.substr(bfoo, binaryValue.length - 512, 100000)); + } + + @Test + public void strlen() { + jedis.set(bfoo, binaryValue); + assertEquals(binaryValue.length, jedis.strlen(bfoo)); + } + + @Test + public void sendCommandTest() { + Object obj = jedis.sendCommand(SET, "x".getBytes(), "1".getBytes()); + String returnValue = SafeEncoder.encode((byte[]) obj); + assertEquals("OK", returnValue); + obj = jedis.sendCommand(GET, "x".getBytes()); + returnValue = SafeEncoder.encode((byte[]) obj); + assertEquals("1", returnValue); + + jedis.sendCommand(RPUSH, "foo".getBytes(), "a".getBytes()); + jedis.sendCommand(RPUSH, "foo".getBytes(), "b".getBytes()); + jedis.sendCommand(RPUSH, "foo".getBytes(), "c".getBytes()); + + obj = jedis.sendCommand(LRANGE, "foo".getBytes(), "0".getBytes(), "2".getBytes()); + List list = (List) obj; + List expected = new ArrayList<>(3); + expected.add("a".getBytes()); + expected.add("b".getBytes()); + expected.add("c".getBytes()); + for (int i = 0; i < 3; i++) + assertArrayEquals(expected.get(i), list.get(i)); + } + + @Test + public void sendBlockingCommandTest() { + assertNull(jedis.sendBlockingCommand(BLPOP, bfoo, Protocol.toByteArray(1L))); + + jedis.sendCommand(RPUSH, bfoo, bbar); + List blpop = (List) jedis.sendBlockingCommand(BLPOP, bfoo, + Protocol.toByteArray(1L)); + assertEquals(2, blpop.size()); + assertArrayEquals(bfoo, blpop.get(0)); + assertArrayEquals(bbar, blpop.get(1)); + + assertNull(jedis.sendBlockingCommand(BLPOP, bfoo, Protocol.toByteArray(1L))); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/BitCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/BitCommandsTestBase.java new file mode 100644 index 0000000000..9b42061f0a --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/BitCommandsTestBase.java @@ -0,0 +1,258 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +import java.util.List; +import org.junit.Test; + +import redis.clients.jedis.Protocol; +import redis.clients.jedis.args.BitOP; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.BitPosParams; +import redis.clients.jedis.util.SafeEncoder; + +public abstract class BitCommandsTestBase extends UnifiedJedisCommandsTestBase { + + @Test + public void setAndgetbit() { + assertFalse(jedis.setbit("foo", 0, true)); + + assertTrue(jedis.getbit("foo", 0)); + + // Binary + assertFalse(jedis.setbit("bfoo".getBytes(), 0, true)); + + assertTrue(jedis.getbit("bfoo".getBytes(), 0)); + } + + @Test + public void bitpos() { + String foo = "foo"; + + jedis.set(foo, String.valueOf(0)); + + jedis.setbit(foo, 3, true); + jedis.setbit(foo, 7, true); + jedis.setbit(foo, 13, true); + jedis.setbit(foo, 39, true); + + /* + * byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 / 00000001 + */ + long offset = jedis.bitpos(foo, true); + assertEquals(2, offset); + offset = jedis.bitpos(foo, false); + assertEquals(0, offset); + + offset = jedis.bitpos(foo, true, new BitPosParams(1)); + assertEquals(13, offset); + offset = jedis.bitpos(foo, false, new BitPosParams(1)); + assertEquals(8, offset); + + offset = jedis.bitpos(foo, true, new BitPosParams(2, 3)); + assertEquals(-1, offset); + offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); + assertEquals(16, offset); + + offset = jedis.bitpos(foo, true, new BitPosParams(3, 4)); + assertEquals(39, offset); + } + + @Test + public void bitposBinary() { + // binary + byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + + jedis.set(bfoo, Protocol.toByteArray(0)); + + jedis.setbit(bfoo, 3, true); + jedis.setbit(bfoo, 7, true); + jedis.setbit(bfoo, 13, true); + jedis.setbit(bfoo, 39, true); + + /* + * byte: 0 1 2 3 4 bit: 00010001 / 00000100 / 00000000 / 00000000 / 00000001 + */ + long offset = jedis.bitpos(bfoo, true); + assertEquals(2, offset); + offset = jedis.bitpos(bfoo, false); + assertEquals(0, offset); + + offset = jedis.bitpos(bfoo, true, new BitPosParams(1)); + assertEquals(13, offset); + offset = jedis.bitpos(bfoo, false, new BitPosParams(1)); + assertEquals(8, offset); + + offset = jedis.bitpos(bfoo, true, new BitPosParams(2, 3)); + assertEquals(-1, offset); + offset = jedis.bitpos(bfoo, false, new BitPosParams(2, 3)); + assertEquals(16, offset); + + offset = jedis.bitpos(bfoo, true, new BitPosParams(3, 4)); + assertEquals(39, offset); + } + + @Test + public void bitposWithNoMatchingBitExist() { + String foo = "foo"; + + jedis.set(foo, String.valueOf(0)); + for (int idx = 0; idx < 8; idx++) { + jedis.setbit(foo, idx, true); + } + + /* + * byte: 0 bit: 11111111 + */ + long offset = jedis.bitpos(foo, false); + // offset should be last index + 1 + assertEquals(8, offset); + } + + @Test + public void bitposWithNoMatchingBitExistWithinRange() { + String foo = "foo"; + + jedis.set(foo, String.valueOf(0)); + for (int idx = 0; idx < 8 * 5; idx++) { + jedis.setbit(foo, idx, true); + } + + /* + * byte: 0 1 2 3 4 bit: 11111111 / 11111111 / 11111111 / 11111111 / 11111111 + */ + long offset = jedis.bitpos(foo, false, new BitPosParams(2, 3)); + // offset should be -1 + assertEquals(-1, offset); + } + + @Test + public void setAndgetrange() { + jedis.set("key1", "Hello World"); + assertEquals(11, jedis.setrange("key1", 6, "Jedis")); + + assertEquals("Hello Jedis", jedis.get("key1")); + + assertEquals("Hello", jedis.getrange("key1", 0, 4)); + assertEquals("Jedis", jedis.getrange("key1", 6, 11)); + } + + @Test + public void bitCount() { + jedis.setbit("foo", 16, true); + jedis.setbit("foo", 24, true); + jedis.setbit("foo", 40, true); + jedis.setbit("foo", 56, true); + + assertEquals(4, (long) jedis.bitcount("foo")); + assertEquals(4, (long) jedis.bitcount("foo".getBytes())); + + assertEquals(3, (long) jedis.bitcount("foo", 2L, 5L)); + assertEquals(3, (long) jedis.bitcount("foo".getBytes(), 2L, 5L)); + } + + @Test + public void bitOp() { + jedis.set("key1", "\u0060"); + jedis.set("key2", "\u0044"); + + jedis.bitop(BitOP.AND, "resultAnd", "key1", "key2"); + String resultAnd = jedis.get("resultAnd"); + assertEquals("\u0040", resultAnd); + + jedis.bitop(BitOP.OR, "resultOr", "key1", "key2"); + String resultOr = jedis.get("resultOr"); + assertEquals("\u0064", resultOr); + + jedis.bitop(BitOP.XOR, "resultXor", "key1", "key2"); + String resultXor = jedis.get("resultXor"); + assertEquals("\u0024", resultXor); + } + + @Test + public void bitOpNot() { + jedis.setbit("key", 0, true); + jedis.setbit("key", 4, true); + + jedis.bitop(BitOP.NOT, "resultNot", "key"); + String resultNot = jedis.get("resultNot"); + assertEquals("\u0077", resultNot); + } + + @Test + public void bitOpBinary() { + byte[] dest = {0x0}; + byte[] key1 = {0x1}; + byte[] key2 = {0x2}; + + jedis.set(key1, new byte[]{0x6}); + jedis.set(key2, new byte[]{0x3}); + + jedis.bitop(BitOP.AND, dest, key1, key2); + assertArrayEquals(new byte[]{0x2}, jedis.get(dest)); + + jedis.bitop(BitOP.OR, dest, key1, key2); + assertArrayEquals(new byte[]{0x7}, jedis.get(dest)); + + jedis.bitop(BitOP.XOR, dest, key1, key2); + assertArrayEquals(new byte[]{0x5}, jedis.get(dest)); + + jedis.setbit(key1, 0, true); + jedis.bitop(BitOP.NOT, dest, key1); + assertArrayEquals(new byte[]{0x79}, jedis.get(dest)); + } + + @Test(expected = JedisDataException.class) + public void bitOpNotMultiSourceShouldFail() { + jedis.bitop(BitOP.NOT, "dest", "src1", "src2"); + } + + @Test + public void testBitfield() { + List responses = jedis.bitfield("mykey", "INCRBY", "i5", "100", "1", "GET", "u4", "0"); + assertEquals(1L, responses.get(0).longValue()); + assertEquals(0L, responses.get(1).longValue()); + } + + @Test + public void testBitfieldReadonly() { + List responses = jedis.bitfield("mykey", "INCRBY", "i5", "100", "1", "GET", "u4", "0"); + assertEquals(1L, responses.get(0).longValue()); + assertEquals(0L, responses.get(1).longValue()); + + List responses2 = jedis.bitfieldReadonly("mykey", "GET", "i5", "100"); + assertEquals(1L, responses2.get(0).longValue()); + + try { + jedis.bitfieldReadonly("mykey", "INCRBY", "i5", "100", "1", "GET", "u4", "0"); + fail("Readonly command shouldn't allow INCRBY"); + } catch (JedisDataException e) { + } + } + + @Test + public void testBinaryBitfield() { + List responses = jedis.bitfield(SafeEncoder.encode("mykey"), + SafeEncoder.encode("INCRBY"), SafeEncoder.encode("i5"), SafeEncoder.encode("100"), + SafeEncoder.encode("1"), SafeEncoder.encode("GET"), SafeEncoder.encode("u4"), + SafeEncoder.encode("0")); + assertEquals(1L, responses.get(0).longValue()); + assertEquals(0L, responses.get(1).longValue()); + } + + @Test + public void testBinaryBitfieldReadonly() { + List responses = jedis.bitfield("mykey", "INCRBY", "i5", "100", "1", "GET", "u4", "0"); + assertEquals(1L, responses.get(0).longValue()); + assertEquals(0L, responses.get(1).longValue()); + + List responses2 = jedis.bitfieldReadonly(SafeEncoder.encode("mykey"), + SafeEncoder.encode("GET"), SafeEncoder.encode("i5"), SafeEncoder.encode("100")); + assertEquals(1L, responses2.get(0).longValue()); + } + +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/GeoCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/GeoCommandsTestBase.java new file mode 100644 index 0000000000..ba78f30399 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/GeoCommandsTestBase.java @@ -0,0 +1,483 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.Test; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.resps.GeoRadiusResponse; +import redis.clients.jedis.params.GeoAddParams; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.util.SafeEncoder; + +public abstract class GeoCommandsTestBase extends UnifiedJedisCommandsTestBase { + protected final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + protected final byte[] bA = { 0x0A }; + protected final byte[] bB = { 0x0B }; + protected final byte[] bC = { 0x0C }; + protected final byte[] bD = { 0x0D }; + protected final byte[] bNotexist = { 0x0F }; + + private static final double EPSILON = 1e-5; + + @Test + public void geoadd() { + assertEquals(1, jedis.geoadd("foo", 1, 2, "a")); + assertEquals(0, jedis.geoadd("foo", 2, 3, "a")); + + Map coordinateMap = new HashMap<>(); + coordinateMap.put("a", new GeoCoordinate(3, 4)); + coordinateMap.put("b", new GeoCoordinate(2, 3)); + coordinateMap.put("c", new GeoCoordinate(3.314, 2.3241)); + + assertEquals(2, jedis.geoadd("foo", coordinateMap)); + + // binary + assertEquals(1, jedis.geoadd(bfoo, 1, 2, bA)); + assertEquals(0, jedis.geoadd(bfoo, 2, 3, bA)); + + Map bcoordinateMap = new HashMap<>(); + bcoordinateMap.put(bA, new GeoCoordinate(3, 4)); + bcoordinateMap.put(bB, new GeoCoordinate(2, 3)); + bcoordinateMap.put(bC, new GeoCoordinate(3.314, 2.3241)); + + assertEquals(2, jedis.geoadd(bfoo, bcoordinateMap)); + } + + @Test + public void geoaddWithParams() { + assertEquals(1, jedis.geoadd("foo", 1, 2, "a")); + + Map coordinateMap = new HashMap<>(); + coordinateMap.put("a", new GeoCoordinate(3, 4)); + assertEquals(0, jedis.geoadd("foo", GeoAddParams.geoAddParams().nx(), coordinateMap)); + assertEquals(1, jedis.geoadd("foo", GeoAddParams.geoAddParams().xx().ch(), coordinateMap)); + + coordinateMap.clear(); + coordinateMap.put("b", new GeoCoordinate(6, 7)); + // never add elements. + assertEquals(0, jedis.geoadd("foo", GeoAddParams.geoAddParams().xx(), coordinateMap)); + assertEquals(1, jedis.geoadd("foo", GeoAddParams.geoAddParams().nx(), coordinateMap)); + + // binary + assertEquals(1, jedis.geoadd(bfoo, 1, 2, bA)); + + Map bcoordinateMap = new HashMap<>(); + bcoordinateMap.put(bA, new GeoCoordinate(3, 4)); + assertEquals(0, jedis.geoadd(bfoo, GeoAddParams.geoAddParams().nx(), bcoordinateMap)); + assertEquals(1, jedis.geoadd(bfoo, GeoAddParams.geoAddParams().xx().ch(), bcoordinateMap)); + + bcoordinateMap.clear(); + bcoordinateMap.put(bB, new GeoCoordinate(6, 7)); + // never add elements. + assertEquals(0, jedis.geoadd(bfoo, GeoAddParams.geoAddParams().xx(), bcoordinateMap)); + assertEquals(1, jedis.geoadd(bfoo, GeoAddParams.geoAddParams().nx(), bcoordinateMap)); + } + + @Test + public void geodist() { + prepareGeoData(); + + Double dist = jedis.geodist("foo", "a", "b"); + assertEquals(157149, dist.intValue()); + + dist = jedis.geodist("foo", "a", "b", GeoUnit.KM); + assertEquals(157, dist.intValue()); + + dist = jedis.geodist("foo", "a", "b", GeoUnit.MI); + assertEquals(97, dist.intValue()); + + dist = jedis.geodist("foo", "a", "b", GeoUnit.FT); + assertEquals(515583, dist.intValue()); + + // binary + dist = jedis.geodist(bfoo, bA, bB); + assertEquals(157149, dist.intValue()); + + dist = jedis.geodist(bfoo, bA, bB, GeoUnit.KM); + assertEquals(157, dist.intValue()); + + dist = jedis.geodist(bfoo, bA, bB, GeoUnit.MI); + assertEquals(97, dist.intValue()); + + dist = jedis.geodist(bfoo, bA, bB, GeoUnit.FT); + assertEquals(515583, dist.intValue()); + } + + @Test + public void geohash() { + prepareGeoData(); + + List hashes = jedis.geohash("foo", "a", "b", "notexist"); + assertEquals(3, hashes.size()); + assertEquals("s0dnu20t9j0", hashes.get(0)); + assertEquals("s093jd0k720", hashes.get(1)); + assertNull(hashes.get(2)); + + // binary + List bhashes = jedis.geohash(bfoo, bA, bB, bNotexist); + assertEquals(3, bhashes.size()); + assertArrayEquals(SafeEncoder.encode("s0dnu20t9j0"), bhashes.get(0)); + assertArrayEquals(SafeEncoder.encode("s093jd0k720"), bhashes.get(1)); + assertNull(bhashes.get(2)); + } + + @Test + public void geopos() { + prepareGeoData(); + + List coordinates = jedis.geopos("foo", "a", "b", "notexist"); + assertEquals(3, coordinates.size()); + assertEquals(3.0, coordinates.get(0).getLongitude(), EPSILON); + assertEquals(4.0, coordinates.get(0).getLatitude(), EPSILON); + assertEquals(2.0, coordinates.get(1).getLongitude(), EPSILON); + assertEquals(3.0, coordinates.get(1).getLatitude(), EPSILON); + assertNull(coordinates.get(2)); + + List bcoordinates = jedis.geopos(bfoo, bA, bB, bNotexist); + assertEquals(3, bcoordinates.size()); + assertEquals(3.0, bcoordinates.get(0).getLongitude(), EPSILON); + assertEquals(4.0, bcoordinates.get(0).getLatitude(), EPSILON); + assertEquals(2.0, bcoordinates.get(1).getLongitude(), EPSILON); + assertEquals(3.0, bcoordinates.get(1).getLatitude(), EPSILON); + assertNull(bcoordinates.get(2)); + } + + @Test + public void georadius() { + // prepare datas + Map coordinateMap = new HashMap<>(); + coordinateMap.put("Palermo", new GeoCoordinate(13.361389, 38.115556)); + coordinateMap.put("Catania", new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd("Sicily", coordinateMap); + + List members = jedis.georadius("Sicily", 15, 37, 200, GeoUnit.KM); + assertEquals(2, members.size()); + + // sort + members = jedis.georadius("Sicily", 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending()); + assertEquals(2, members.size()); + assertEquals("Catania", members.get(0).getMemberByString()); + assertEquals("Palermo", members.get(1).getMemberByString()); + + // sort, count 1 + members = jedis.georadius("Sicily", 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending().count(1)); + assertEquals(1, members.size()); + + // sort, count 1, withdist, withcoord + members = jedis.georadius("Sicily", 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending().count(1).withCoord().withDist().withHash()); + assertEquals(1, members.size()); + GeoRadiusResponse response = members.get(0); + assertEquals(56.4413, response.getDistance(), EPSILON); + assertEquals(15.087269, response.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.502669, response.getCoordinate().getLatitude(), EPSILON); + assertEquals(3479447370796909L, response.getRawScore()); + + // sort, count 1, with hash + members = jedis.georadius("Sicily", 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending().count(1).withHash()); + assertEquals(1, members.size()); + response = members.get(0); + assertEquals(3479447370796909L, response.getRawScore()); + } + + @Test + public void georadiusStore() { + // prepare datas + Map coordinateMap = new HashMap<>(); + coordinateMap.put("Palermo", new GeoCoordinate(13.361389, 38.115556)); + coordinateMap.put("Catania", new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd("Sicily", coordinateMap); + + long size = jedis.georadiusStore("Sicily", 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore")); + assertEquals(2, size); + List expected = new ArrayList<>(); + expected.add("Palermo"); + expected.add("Catania"); + assertEquals(expected, jedis.zrange("SicilyStore", 0, -1)); + } + + @Test + public void georadiusReadonly() { + // prepare datas + Map coordinateMap = new HashMap<>(); + coordinateMap.put("Palermo", new GeoCoordinate(13.361389, 38.115556)); + coordinateMap.put("Catania", new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd("Sicily", coordinateMap); + + List members = jedis.georadiusReadonly("Sicily", 15, 37, 200, GeoUnit.KM); + assertEquals(2, members.size()); + + // sort + members = jedis.georadiusReadonly("Sicily", 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending()); + assertEquals(2, members.size()); + assertEquals("Catania", members.get(0).getMemberByString()); + assertEquals("Palermo", members.get(1).getMemberByString()); + + // sort, count 1 + members = jedis.georadiusReadonly("Sicily", 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1)); + assertEquals(1, members.size()); + + // sort, count 1, withdist, withcoord + members = jedis.georadiusReadonly("Sicily", 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + GeoRadiusResponse response = members.get(0); + assertEquals(56.4413, response.getDistance(), EPSILON); + assertEquals(15.087269, response.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.502669, response.getCoordinate().getLatitude(), EPSILON); + } + + @Test + public void georadiusBinary() { + // prepare datas + Map bcoordinateMap = new HashMap<>(); + bcoordinateMap.put(bA, new GeoCoordinate(13.361389, 38.115556)); + bcoordinateMap.put(bB, new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd(bfoo, bcoordinateMap); + + List members = jedis.georadius(bfoo, 15, 37, 200, GeoUnit.KM); + assertEquals(2, members.size()); + + // sort + members = jedis.georadius(bfoo, 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending()); + assertEquals(2, members.size()); + assertArrayEquals(bB, members.get(0).getMember()); + assertArrayEquals(bA, members.get(1).getMember()); + + // sort, count 1 + members = jedis.georadius(bfoo, 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending().count(1)); + assertEquals(1, members.size()); + + // sort, count 1, withdist, withcoord + members = jedis.georadius(bfoo, 15, 37, 200, GeoUnit.KM, GeoRadiusParam.geoRadiusParam() + .sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + GeoRadiusResponse response = members.get(0); + assertEquals(56.4413, response.getDistance(), EPSILON); + assertEquals(15.087269, response.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.502669, response.getCoordinate().getLatitude(), EPSILON); + } + + @Test + public void georadiusStoreBinary() { + // prepare datas + Map bcoordinateMap = new HashMap<>(); + bcoordinateMap.put(bA, new GeoCoordinate(13.361389, 38.115556)); + bcoordinateMap.put(bB, new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd(bfoo, bcoordinateMap); + + long size = jedis.georadiusStore(bfoo, 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore")); + assertEquals(2, size); + List bexpected = new ArrayList<>(); + bexpected.add(bA); + bexpected.add(bB); + assertByteArrayListEquals(bexpected, jedis.zrange("SicilyStore".getBytes(), 0, -1)); + } + + @Test + public void georadiusReadonlyBinary() { + // prepare datas + Map bcoordinateMap = new HashMap<>(); + bcoordinateMap.put(bA, new GeoCoordinate(13.361389, 38.115556)); + bcoordinateMap.put(bB, new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd(bfoo, bcoordinateMap); + + List members = jedis.georadiusReadonly(bfoo, 15, 37, 200, GeoUnit.KM); + assertEquals(2, members.size()); + + // sort + members = jedis.georadiusReadonly(bfoo, 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending()); + assertEquals(2, members.size()); + assertArrayEquals(bB, members.get(0).getMember()); + assertArrayEquals(bA, members.get(1).getMember()); + + // sort, count 1 + members = jedis.georadiusReadonly(bfoo, 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1)); + assertEquals(1, members.size()); + + // sort, count 1, withdist, withcoord + members = jedis.georadiusReadonly(bfoo, 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + GeoRadiusResponse response = members.get(0); + assertEquals(56.4413, response.getDistance(), EPSILON); + assertEquals(15.087269, response.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.502669, response.getCoordinate().getLatitude(), EPSILON); + } + + @Test + public void georadiusByMember() { + jedis.geoadd("Sicily", 13.583333, 37.316667, "Agrigento"); + jedis.geoadd("Sicily", 13.361389, 38.115556, "Palermo"); + jedis.geoadd("Sicily", 15.087269, 37.502669, "Catania"); + + List members = jedis.georadiusByMember("Sicily", "Agrigento", 100, + GeoUnit.KM); + assertEquals(2, members.size()); + + members = jedis.georadiusByMember("Sicily", "Agrigento", 100, GeoUnit.KM, GeoRadiusParam + .geoRadiusParam().sortAscending()); + assertEquals(2, members.size()); + assertEquals("Agrigento", members.get(0).getMemberByString()); + assertEquals("Palermo", members.get(1).getMemberByString()); + + members = jedis.georadiusByMember("Sicily", "Agrigento", 100, GeoUnit.KM, GeoRadiusParam + .geoRadiusParam().sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + + GeoRadiusResponse member = members.get(0); + assertEquals("Agrigento", member.getMemberByString()); + assertEquals(0, member.getDistance(), EPSILON); + assertEquals(13.583333, member.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.316667, member.getCoordinate().getLatitude(), EPSILON); + } + + @Test + public void georadiusByMemberStore() { + jedis.geoadd("Sicily", 13.583333, 37.316667, "Agrigento"); + jedis.geoadd("Sicily", 13.361389, 38.115556, "Palermo"); + jedis.geoadd("Sicily", 15.087269, 37.502669, "Catania"); + + long size = jedis.georadiusByMemberStore("Sicily", "Agrigento", 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore")); + assertEquals(2, size); + List expected = new ArrayList<>(); + expected.add("Agrigento"); + expected.add("Palermo"); + assertEquals(expected, jedis.zrange("SicilyStore", 0, -1)); + } + + @Test + public void georadiusByMemberReadonly() { + jedis.geoadd("Sicily", 13.583333, 37.316667, "Agrigento"); + jedis.geoadd("Sicily", 13.361389, 38.115556, "Palermo"); + jedis.geoadd("Sicily", 15.087269, 37.502669, "Catania"); + + List members = jedis.georadiusByMemberReadonly("Sicily", "Agrigento", 100, + GeoUnit.KM); + assertEquals(2, members.size()); + + members = jedis.georadiusByMemberReadonly("Sicily", "Agrigento", 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending()); + assertEquals(2, members.size()); + assertEquals("Agrigento", members.get(0).getMemberByString()); + assertEquals("Palermo", members.get(1).getMemberByString()); + + members = jedis.georadiusByMemberReadonly("Sicily", "Agrigento", 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + + GeoRadiusResponse member = members.get(0); + assertEquals("Agrigento", member.getMemberByString()); + assertEquals(0, member.getDistance(), EPSILON); + assertEquals(13.583333, member.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.316667, member.getCoordinate().getLatitude(), EPSILON); + } + + @Test + public void georadiusByMemberBinary() { + jedis.geoadd(bfoo, 13.583333, 37.316667, bA); + jedis.geoadd(bfoo, 13.361389, 38.115556, bB); + jedis.geoadd(bfoo, 15.087269, 37.502669, bC); + + List members = jedis.georadiusByMember(bfoo, bA, 100, GeoUnit.KM); + assertEquals(2, members.size()); + + members = jedis.georadiusByMember(bfoo, bA, 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending()); + assertEquals(2, members.size()); + assertArrayEquals(bA, members.get(0).getMember()); + assertArrayEquals(bB, members.get(1).getMember()); + + members = jedis.georadiusByMember(bfoo, bA, 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + + GeoRadiusResponse member = members.get(0); + assertArrayEquals(bA, member.getMember()); + assertEquals(0, member.getDistance(), EPSILON); + assertEquals(13.583333, member.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.316667, member.getCoordinate().getLatitude(), EPSILON); + } + + @Test + public void georadiusByMemberStoreBinary() { + jedis.geoadd(bfoo, 13.583333, 37.316667, bA); + jedis.geoadd(bfoo, 13.361389, 38.115556, bB); + jedis.geoadd(bfoo, 15.087269, 37.502669, bC); + + assertEquals(2, jedis.georadiusByMemberStore(bfoo, bA, 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("SicilyStore"))); + List bexpected = new ArrayList<>(); + bexpected.add(bA); + bexpected.add(bB); + assertByteArrayListEquals(bexpected, jedis.zrange("SicilyStore".getBytes(), 0, -1)); + } + + @Test + public void georadiusByMemberReadonlyBinary() { + jedis.geoadd(bfoo, 13.583333, 37.316667, bA); + jedis.geoadd(bfoo, 13.361389, 38.115556, bB); + jedis.geoadd(bfoo, 15.087269, 37.502669, bC); + + List members = jedis.georadiusByMemberReadonly(bfoo, bA, 100, GeoUnit.KM); + assertEquals(2, members.size()); + + members = jedis.georadiusByMemberReadonly(bfoo, bA, 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending()); + assertEquals(2, members.size()); + assertArrayEquals(bA, members.get(0).getMember()); + assertArrayEquals(bB, members.get(1).getMember()); + + members = jedis.georadiusByMemberReadonly(bfoo, bA, 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam().sortAscending().count(1).withCoord().withDist()); + assertEquals(1, members.size()); + + GeoRadiusResponse member = members.get(0); + assertArrayEquals(bA, member.getMember()); + assertEquals(0, member.getDistance(), EPSILON); + assertEquals(13.583333, member.getCoordinate().getLongitude(), EPSILON); + assertEquals(37.316667, member.getCoordinate().getLatitude(), EPSILON); + } + + private void prepareGeoData() { + Map coordinateMap = new HashMap<>(); + coordinateMap.put("a", new GeoCoordinate(3, 4)); + coordinateMap.put("b", new GeoCoordinate(2, 3)); + coordinateMap.put("c", new GeoCoordinate(3.314, 2.3241)); + + assertEquals(3, jedis.geoadd("foo", coordinateMap)); + + Map bcoordinateMap = new HashMap<>(); + bcoordinateMap.put(bA, new GeoCoordinate(3, 4)); + bcoordinateMap.put(bB, new GeoCoordinate(2, 3)); + bcoordinateMap.put(bC, new GeoCoordinate(3.314, 2.3241)); + + assertEquals(3, jedis.geoadd(bfoo, bcoordinateMap)); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/HashesCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/HashesCommandsTestBase.java new file mode 100644 index 0000000000..d6c6036c5c --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/HashesCommandsTestBase.java @@ -0,0 +1,463 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNull; + +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContains; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Test; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.util.JedisByteHashMap; + +public abstract class HashesCommandsTestBase extends UnifiedJedisCommandsTestBase { + + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + + @Test + public void hset() { + assertEquals(1, jedis.hset("foo", "bar", "car")); + assertEquals(0, jedis.hset("foo", "bar", "foo")); + + // Binary + assertEquals(1, jedis.hset(bfoo, bbar, bcar)); + assertEquals(0, jedis.hset(bfoo, bbar, bfoo)); + } + + @Test + public void hget() { + jedis.hset("foo", "bar", "car"); + assertNull(jedis.hget("bar", "foo")); + assertNull(jedis.hget("foo", "car")); + assertEquals("car", jedis.hget("foo", "bar")); + + // Binary + jedis.hset(bfoo, bbar, bcar); + assertNull(jedis.hget(bbar, bfoo)); + assertNull(jedis.hget(bfoo, bcar)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + } + + @Test + public void hsetnx() { + assertEquals(1, jedis.hsetnx("foo", "bar", "car")); + assertEquals("car", jedis.hget("foo", "bar")); + + assertEquals(0, jedis.hsetnx("foo", "bar", "foo")); + assertEquals("car", jedis.hget("foo", "bar")); + + assertEquals(1, jedis.hsetnx("foo", "car", "bar")); + assertEquals("bar", jedis.hget("foo", "car")); + + // Binary + assertEquals(1, jedis.hsetnx(bfoo, bbar, bcar)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + + assertEquals(0, jedis.hsetnx(bfoo, bbar, bfoo)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + + assertEquals(1, jedis.hsetnx(bfoo, bcar, bbar)); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); + } + + @Test + public void hmset() { + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + assertEquals("OK", jedis.hmset("foo", hash)); + assertEquals("car", jedis.hget("foo", "bar")); + assertEquals("bar", jedis.hget("foo", "car")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + assertEquals("OK", jedis.hmset(bfoo, bhash)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); + } + + @Test + public void hsetVariadic() { + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + assertEquals(2, jedis.hset("foo", hash)); + assertEquals("car", jedis.hget("foo", "bar")); + assertEquals("bar", jedis.hget("foo", "car")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + assertEquals(2, jedis.hset(bfoo, bhash)); + assertArrayEquals(bcar, jedis.hget(bfoo, bbar)); + assertArrayEquals(bbar, jedis.hget(bfoo, bcar)); + } + + @Test + public void hmget() { + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + List values = jedis.hmget("foo", "bar", "car", "foo"); + List expected = new ArrayList(); + expected.add("car"); + expected.add("bar"); + expected.add(null); + + assertEquals(expected, values); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + List bvalues = jedis.hmget(bfoo, bbar, bcar, bfoo); + List bexpected = new ArrayList(); + bexpected.add(bcar); + bexpected.add(bbar); + bexpected.add(null); + + assertByteArrayListEquals(bexpected, bvalues); + } + + @Test + public void hincrBy() { + assertEquals(1, jedis.hincrBy("foo", "bar", 1)); + assertEquals(0, jedis.hincrBy("foo", "bar", -1)); + assertEquals(-10, jedis.hincrBy("foo", "bar", -10)); + + // Binary + assertEquals(1, jedis.hincrBy(bfoo, bbar, 1)); + assertEquals(0, jedis.hincrBy(bfoo, bbar, -1)); + assertEquals(-10, jedis.hincrBy(bfoo, bbar, -10)); + } + + @Test + public void hincrByFloat() { + assertEquals(1.5d, jedis.hincrByFloat("foo", "bar", 1.5d), 0); + assertEquals(0d, jedis.hincrByFloat("foo", "bar", -1.5d), 0); + assertEquals(-10.7d, jedis.hincrByFloat("foo", "bar", -10.7d), 0); + + // Binary + assertEquals(1.5d, jedis.hincrByFloat(bfoo, bbar, 1.5d), 0d); + assertEquals(0d, jedis.hincrByFloat(bfoo, bbar, -1.5d), 0d); + assertEquals(-10.7d, jedis.hincrByFloat(bfoo, bbar, -10.7d), 0d); + } + + @Test + public void hexists() { + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + assertFalse(jedis.hexists("bar", "foo")); + assertFalse(jedis.hexists("foo", "foo")); + assertTrue(jedis.hexists("foo", "bar")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + assertFalse(jedis.hexists(bbar, bfoo)); + assertFalse(jedis.hexists(bfoo, bfoo)); + assertTrue(jedis.hexists(bfoo, bbar)); + } + + @Test + public void hdel() { + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + assertEquals(0, jedis.hdel("bar", "foo")); + assertEquals(0, jedis.hdel("foo", "foo")); + assertEquals(1, jedis.hdel("foo", "bar")); + assertNull(jedis.hget("foo", "bar")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + assertEquals(0, jedis.hdel(bbar, bfoo)); + assertEquals(0, jedis.hdel(bfoo, bfoo)); + assertEquals(1, jedis.hdel(bfoo, bbar)); + assertNull(jedis.hget(bfoo, bbar)); + } + + @Test + public void hlen() { + Map hash = new HashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + assertEquals(0, jedis.hlen("bar")); + assertEquals(2, jedis.hlen("foo")); + + // Binary + Map bhash = new HashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + assertEquals(0, jedis.hlen(bbar)); + assertEquals(2, jedis.hlen(bfoo)); + } + + @Test + public void hkeys() { + Map hash = new LinkedHashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + Set keys = jedis.hkeys("foo"); + Set expected = new LinkedHashSet(); + expected.add("bar"); + expected.add("car"); + assertEquals(expected, keys); + + // Binary + Map bhash = new LinkedHashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + Set bkeys = jedis.hkeys(bfoo); + Set bexpected = new LinkedHashSet(); + bexpected.add(bbar); + bexpected.add(bcar); + assertByteArraySetEquals(bexpected, bkeys); + } + + @Test + public void hvals() { + Map hash = new LinkedHashMap(); + hash.put("bar", "car"); + hash.put("car", "bar"); + jedis.hmset("foo", hash); + + List vals = jedis.hvals("foo"); + assertEquals(2, vals.size()); + assertTrue(vals.contains("bar")); + assertTrue(vals.contains("car")); + + // Binary + Map bhash = new LinkedHashMap(); + bhash.put(bbar, bcar); + bhash.put(bcar, bbar); + jedis.hmset(bfoo, bhash); + + List bvals = jedis.hvals(bfoo); + + assertEquals(2, bvals.size()); + assertCollectionContains(bvals, bbar); + assertCollectionContains(bvals, bcar); + } + + @Test + public void hgetAll() { + Map h = new HashMap(); + h.put("bar", "car"); + h.put("car", "bar"); + jedis.hmset("foo", h); + + Map hash = jedis.hgetAll("foo"); + assertEquals(2, hash.size()); + assertEquals("car", hash.get("bar")); + assertEquals("bar", hash.get("car")); + + // Binary + Map bh = new HashMap(); + bh.put(bbar, bcar); + bh.put(bcar, bbar); + jedis.hmset(bfoo, bh); + Map bhash = jedis.hgetAll(bfoo); + + assertEquals(2, bhash.size()); + assertArrayEquals(bcar, bhash.get(bbar)); + assertArrayEquals(bbar, bhash.get(bcar)); + } + + @Test + public void hscan() { + jedis.hset("foo", "b", "b"); + jedis.hset("foo", "a", "a"); + + ScanResult> result = jedis.hscan("foo", SCAN_POINTER_START); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + jedis.hset(bfoo, bbar, bcar); + + ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void hscanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.hset("foo", "b", "b"); + jedis.hset("foo", "a", "a"); + jedis.hset("foo", "aa", "aa"); + ScanResult> result = jedis.hscan("foo", SCAN_POINTER_START, params); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bbarstar); + + jedis.hset(bfoo, bbar, bcar); + jedis.hset(bfoo, bbar1, bcar); + jedis.hset(bfoo, bbar2, bcar); + jedis.hset(bfoo, bbar3, bcar); + + ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, + params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void hscanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + for (int i = 0; i < 10; i++) { + jedis.hset("foo", "a" + i, "a" + i); + } + + ScanResult> result = jedis.hscan("foo", SCAN_POINTER_START, params); + + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.hset(bfoo, bbar, bcar); + jedis.hset(bfoo, bbar1, bcar); + jedis.hset(bfoo, bbar2, bcar); + jedis.hset(bfoo, bbar3, bcar); + + ScanResult> bResult = jedis.hscan(bfoo, SCAN_POINTER_START_BINARY, + params); + + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void testHstrLen_EmptyHash() { + Long response = jedis.hstrlen("myhash", "k1"); + assertEquals(0l, response.longValue()); + } + + @Test + public void testHstrLen() { + Map values = new HashMap<>(); + values.put("key", "value"); + jedis.hmset("myhash", values); + Long response = jedis.hstrlen("myhash", "key"); + assertEquals(5l, response.longValue()); + + } + + @Test + public void testBinaryHstrLen() { + Map values = new HashMap<>(); + values.put(bbar, bcar); + jedis.hmset(bfoo, values); + Long response = jedis.hstrlen(bfoo, bbar); + assertEquals(4l, response.longValue()); + } + + @Test + public void hrandfield() { + assertNull(jedis.hrandfield("foo")); + assertEquals(Collections.emptyList(), jedis.hrandfield("foo", 1)); + assertEquals(Collections.emptyMap(), jedis.hrandfieldWithValues("foo", 1)); + + Map hash = new LinkedHashMap<>(); + hash.put("bar", "bar"); + hash.put("car", "car"); + hash.put("bar1", "bar1"); + + jedis.hset("foo", hash); + + assertTrue(hash.containsKey(jedis.hrandfield("foo"))); + assertEquals(2, jedis.hrandfield("foo", 2).size()); + + Map actual = jedis.hrandfieldWithValues("foo", 2); + assertNotNull(actual); + assertEquals(2, actual.size()); + Map.Entry entry = actual.entrySet().iterator().next(); + assertEquals(hash.get(entry.getKey()), entry.getValue()); + + // binary + assertNull(jedis.hrandfield(bfoo)); + assertEquals(Collections.emptyList(), jedis.hrandfield(bfoo, 1)); + assertEquals(Collections.emptyMap(), jedis.hrandfieldWithValues(bfoo, 1)); + + Map bhash = new JedisByteHashMap(); + bhash.put(bbar, bbar); + bhash.put(bcar, bcar); + bhash.put(bbar1, bbar1); + + jedis.hset(bfoo, bhash); + + assertTrue(bhash.containsKey(jedis.hrandfield(bfoo))); + assertEquals(2, jedis.hrandfield(bfoo, 2).size()); + + Map bactual = jedis.hrandfieldWithValues(bfoo, 2); + assertNotNull(bactual); + assertEquals(2, bactual.size()); + Map.Entry bentry = bactual.entrySet().iterator().next(); + assertArrayEquals(bhash.get(bentry.getKey()), (byte[]) bentry.getValue()); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/HyperLogLogCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/HyperLogLogCommandsTestBase.java new file mode 100644 index 0000000000..79a82f69f2 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/HyperLogLogCommandsTestBase.java @@ -0,0 +1,131 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertEquals; + +import org.junit.Test; + +import redis.clients.jedis.util.SafeEncoder; + +public abstract class HyperLogLogCommandsTestBase extends UnifiedJedisCommandsTestBase { + + @Test + public void pfadd() { + long status = jedis.pfadd("foo", "a"); + assertEquals(1, status); + + status = jedis.pfadd("foo", "a"); + assertEquals(0, status); + } + + @Test + public void pfaddBinary() { + byte[] bFoo = SafeEncoder.encode("foo"); + byte[] bBar = SafeEncoder.encode("bar"); + byte[] bBar2 = SafeEncoder.encode("bar2"); + + long status = jedis.pfadd(bFoo, bBar, bBar2); + assertEquals(1, status); + + status = jedis.pfadd(bFoo, bBar, bBar2); + assertEquals(0, status); + } + + @Test + public void pfcount() { + long status = jedis.pfadd("hll", "foo", "bar", "zap"); + assertEquals(1, status); + + status = jedis.pfadd("hll", "zap", "zap", "zap"); + assertEquals(0, status); + + status = jedis.pfadd("hll", "foo", "bar"); + assertEquals(0, status); + + status = jedis.pfcount("hll"); + assertEquals(3, status); + } + + @Test + public void pfcounts() { + long status = jedis.pfadd("hll_1", "foo", "bar", "zap"); + assertEquals(1, status); + status = jedis.pfadd("hll_2", "foo", "bar", "zap"); + assertEquals(1, status); + + status = jedis.pfadd("hll_3", "foo", "bar", "baz"); + assertEquals(1, status); + status = jedis.pfcount("hll_1"); + assertEquals(3, status); + status = jedis.pfcount("hll_2"); + assertEquals(3, status); + status = jedis.pfcount("hll_3"); + assertEquals(3, status); + + status = jedis.pfcount("hll_1", "hll_2"); + assertEquals(3, status); + + status = jedis.pfcount("hll_1", "hll_2", "hll_3"); + assertEquals(4, status); + + } + + @Test + public void pfcountBinary() { + byte[] bHll = SafeEncoder.encode("hll"); + byte[] bFoo = SafeEncoder.encode("foo"); + byte[] bBar = SafeEncoder.encode("bar"); + byte[] bZap = SafeEncoder.encode("zap"); + + long status = jedis.pfadd(bHll, bFoo, bBar, bZap); + assertEquals(1, status); + + status = jedis.pfadd(bHll, bZap, bZap, bZap); + assertEquals(0, status); + + status = jedis.pfadd(bHll, bFoo, bBar); + assertEquals(0, status); + + status = jedis.pfcount(bHll); + assertEquals(3, status); + } + + @Test + public void pfmerge() { + long status = jedis.pfadd("hll1", "foo", "bar", "zap", "a"); + assertEquals(1, status); + + status = jedis.pfadd("hll2", "a", "b", "c", "foo"); + assertEquals(1, status); + + String mergeStatus = jedis.pfmerge("hll3", "hll1", "hll2"); + assertEquals("OK", mergeStatus); + + status = jedis.pfcount("hll3"); + assertEquals(6, status); + } + + @Test + public void pfmergeBinary() { + byte[] bHll1 = SafeEncoder.encode("hll1"); + byte[] bHll2 = SafeEncoder.encode("hll2"); + byte[] bHll3 = SafeEncoder.encode("hll3"); + byte[] bFoo = SafeEncoder.encode("foo"); + byte[] bBar = SafeEncoder.encode("bar"); + byte[] bZap = SafeEncoder.encode("zap"); + byte[] bA = SafeEncoder.encode("a"); + byte[] bB = SafeEncoder.encode("b"); + byte[] bC = SafeEncoder.encode("c"); + + long status = jedis.pfadd(bHll1, bFoo, bBar, bZap, bA); + assertEquals(1, status); + + status = jedis.pfadd(bHll2, bA, bB, bC, bFoo); + assertEquals(1, status); + + String mergeStatus = jedis.pfmerge(bHll3, bHll1, bHll2); + assertEquals("OK", mergeStatus); + + status = jedis.pfcount(bHll3); + assertEquals(6, status); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/ListCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/ListCommandsTestBase.java new file mode 100644 index 0000000000..bfaa0e3bf0 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/ListCommandsTestBase.java @@ -0,0 +1,866 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import org.junit.Test; + +import redis.clients.jedis.args.ListPosition; +import redis.clients.jedis.args.ListDirection; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.LPosParams; +import redis.clients.jedis.resps.KeyedListElement; + +public abstract class ListCommandsTestBase extends UnifiedJedisCommandsTestBase { + + private static final Logger logger = LogManager.getLogger(); + + protected final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + protected final byte[] bfoo1 = { 0x01, 0x02, 0x03, 0x04, 0x05 }; + protected final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + protected final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + protected final byte[] bA = { 0x0A }; + protected final byte[] bB = { 0x0B }; + protected final byte[] bC = { 0x0C }; + protected final byte[] b1 = { 0x01 }; + protected final byte[] b2 = { 0x02 }; + protected final byte[] b3 = { 0x03 }; + protected final byte[] bhello = { 0x04, 0x02 }; + protected final byte[] bx = { 0x02, 0x04 }; + protected final byte[] bdst = { 0x11, 0x12, 0x13, 0x14 }; + + @Test + public void rpush() { + assertEquals(1, jedis.rpush("foo", "bar")); + assertEquals(2, jedis.rpush("foo", "foo")); + assertEquals(4, jedis.rpush("foo", "bar", "foo")); + + // Binary + assertEquals(1, jedis.rpush(bfoo, bbar)); + assertEquals(2, jedis.rpush(bfoo, bfoo)); + assertEquals(4, jedis.rpush(bfoo, bbar, bfoo)); + } + + @Test + public void lpush() { + assertEquals(1, jedis.lpush("foo", "bar")); + assertEquals(2, jedis.lpush("foo", "foo")); + assertEquals(4, jedis.lpush("foo", "bar", "foo")); + + // Binary + assertEquals(1, jedis.lpush(bfoo, bbar)); + assertEquals(2, jedis.lpush(bfoo, bfoo)); + assertEquals(4, jedis.lpush(bfoo, bbar, bfoo)); + } + + @Test + public void llen() { + assertEquals(0, jedis.llen("foo")); + jedis.lpush("foo", "bar"); + jedis.lpush("foo", "car"); + assertEquals(2, jedis.llen("foo")); + + // Binary + assertEquals(0, jedis.llen(bfoo)); + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo, bcar); + assertEquals(2, jedis.llen(bfoo)); + + } + + @Test + public void llenNotOnList() { + try { + jedis.set("foo", "bar"); + jedis.llen("foo"); + fail("JedisDataException expected"); + } catch (final JedisDataException e) { + } + + // Binary + try { + jedis.set(bfoo, bbar); + jedis.llen(bfoo); + fail("JedisDataException expected"); + } catch (final JedisDataException e) { + } + } + + @Test + public void lrange() { + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); + + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + + List range = jedis.lrange("foo", 0, 2); + assertEquals(expected, range); + + range = jedis.lrange("foo", 0, 20); + assertEquals(expected, range); + + expected = new ArrayList(); + expected.add("b"); + expected.add("c"); + + range = jedis.lrange("foo", 1, 2); + assertEquals(expected, range); + + range = jedis.lrange("foo", 2, 1); + assertEquals(Collections. emptyList(), range); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + bexpected.add(bC); + + List brange = jedis.lrange(bfoo, 0, 2); + assertByteArrayListEquals(bexpected, brange); + + brange = jedis.lrange(bfoo, 0, 20); + assertByteArrayListEquals(bexpected, brange); + + bexpected = new ArrayList(); + bexpected.add(bB); + bexpected.add(bC); + + brange = jedis.lrange(bfoo, 1, 2); + assertByteArrayListEquals(bexpected, brange); + + brange = jedis.lrange(bfoo, 2, 1); + assertByteArrayListEquals(Collections. emptyList(), brange); + } + + @Test + public void ltrim() { + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + String status = jedis.ltrim("foo", 0, 1); + + List expected = new ArrayList(); + expected.add("3"); + expected.add("2"); + + assertEquals("OK", status); + assertEquals(2, jedis.llen("foo")); + assertEquals(expected, jedis.lrange("foo", 0, 100)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + String bstatus = jedis.ltrim(bfoo, 0, 1); + + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(b2); + + assertEquals("OK", bstatus); + assertEquals(2, jedis.llen(bfoo)); + assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 100)); + } + + @Test + public void lset() { + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + + List expected = new ArrayList(); + expected.add("3"); + expected.add("bar"); + expected.add("1"); + + String status = jedis.lset("foo", 1, "bar"); + + assertEquals("OK", status); + assertEquals(expected, jedis.lrange("foo", 0, 100)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + + List bexpected = new ArrayList(); + bexpected.add(b3); + bexpected.add(bbar); + bexpected.add(b1); + + String bstatus = jedis.lset(bfoo, 1, bbar); + + assertEquals("OK", bstatus); + assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 100)); + } + + @Test + public void lindex() { + jedis.lpush("foo", "1"); + jedis.lpush("foo", "2"); + jedis.lpush("foo", "3"); + + assertEquals("3", jedis.lindex("foo", 0)); + assertNull(jedis.lindex("foo", 100)); + + // Binary + jedis.lpush(bfoo, b1); + jedis.lpush(bfoo, b2); + jedis.lpush(bfoo, b3); + + assertArrayEquals(b3, jedis.lindex(bfoo, 0)); + assertNull(jedis.lindex(bfoo, 100)); + } + + @Test + public void lrem() { + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "x"); + jedis.lpush("foo", "hello"); + jedis.lpush("foo", "c"); + jedis.lpush("foo", "b"); + jedis.lpush("foo", "a"); + + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + expected.add("hello"); + expected.add("x"); + + assertEquals(2, jedis.lrem("foo", -2, "hello")); + assertEquals(expected, jedis.lrange("foo", 0, 1000)); + assertEquals(0, jedis.lrem("bar", 100, "foo")); + + // Binary + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bx); + jedis.lpush(bfoo, bhello); + jedis.lpush(bfoo, bC); + jedis.lpush(bfoo, bB); + jedis.lpush(bfoo, bA); + + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + bexpected.add(bC); + bexpected.add(bhello); + bexpected.add(bx); + + assertEquals(2, jedis.lrem(bfoo, -2, bhello)); + assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 1000)); + assertEquals(0, jedis.lrem(bbar, 100, bfoo)); + + } + + @Test + public void lpop() { + + assertNull(jedis.lpop("foo")); + assertNull(jedis.lpop("foo", 0)); + + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); + + assertEquals("a", jedis.lpop("foo")); + assertEquals(Arrays.asList("b", "c"), jedis.lpop("foo", 10)); + + assertNull(jedis.lpop("foo")); + assertNull(jedis.lpop("foo", 1)); + + // Binary + + assertNull(jedis.lpop(bfoo)); + assertNull(jedis.lpop(bfoo, 0)); + + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + assertArrayEquals(bA, jedis.lpop(bfoo)); + assertByteArrayListEquals(Arrays.asList(bB, bC), jedis.lpop(bfoo, 10)); + + assertNull(jedis.lpop(bfoo)); + assertNull(jedis.lpop(bfoo, 1)); + + } + + @Test + public void rpop() { + + assertNull(jedis.rpop("foo")); + assertNull(jedis.rpop("foo", 0)); + + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); + + assertEquals("c", jedis.rpop("foo")); + assertEquals(Arrays.asList("b", "a"), jedis.rpop("foo", 10)); + + assertNull(jedis.rpop("foo")); + assertNull(jedis.rpop("foo", 1)); + + // Binary + + assertNull(jedis.rpop(bfoo)); + assertNull(jedis.rpop(bfoo, 0)); + + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + assertArrayEquals(bC, jedis.rpop(bfoo)); + assertByteArrayListEquals(Arrays.asList(bB, bA), jedis.rpop(bfoo, 10)); + + assertNull(jedis.rpop(bfoo)); + assertNull(jedis.rpop(bfoo, 1)); + + } + + @Test + public void rpoplpush() { + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); + + jedis.rpush("dst", "foo"); + jedis.rpush("dst", "bar"); + + String element = jedis.rpoplpush("foo", "dst"); + + assertEquals("c", element); + + List srcExpected = new ArrayList(); + srcExpected.add("a"); + srcExpected.add("b"); + + List dstExpected = new ArrayList(); + dstExpected.add("c"); + dstExpected.add("foo"); + dstExpected.add("bar"); + + assertEquals(srcExpected, jedis.lrange("foo", 0, 1000)); + assertEquals(dstExpected, jedis.lrange("dst", 0, 1000)); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + jedis.rpush(bdst, bfoo); + jedis.rpush(bdst, bbar); + + byte[] belement = jedis.rpoplpush(bfoo, bdst); + + assertArrayEquals(bC, belement); + + List bsrcExpected = new ArrayList(); + bsrcExpected.add(bA); + bsrcExpected.add(bB); + + List bdstExpected = new ArrayList(); + bdstExpected.add(bC); + bdstExpected.add(bfoo); + bdstExpected.add(bbar); + + assertByteArrayListEquals(bsrcExpected, jedis.lrange(bfoo, 0, 1000)); + assertByteArrayListEquals(bdstExpected, jedis.lrange(bdst, 0, 1000)); + + } + + @Test + public void blpop() throws InterruptedException { + List result = jedis.blpop(1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.blpop(1, "foo"); + + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); + + // Multi keys + result = jedis.blpop(1, "foo", "foo1"); + assertNull(result); + + jedis.lpush("foo", "bar"); + jedis.lpush("foo1", "bar1"); + result = jedis.blpop(1, "foo1", "foo"); + + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo1", result.get(0)); + assertEquals("bar1", result.get(1)); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.blpop(1, bfoo); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + + // Binary Multi keys + bresult = jedis.blpop(1, bfoo, bfoo1); + assertNull(bresult); + + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo1, bcar); + bresult = jedis.blpop(1, bfoo, bfoo1); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + public void blpopDouble() throws InterruptedException { + KeyedListElement result = jedis.blpop(0.1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.blpop(3.2, "foo"); + + assertNotNull(result); + assertEquals("foo", result.getKey()); + assertEquals("bar", result.getElement()); + + // Multi keys + result = jedis.blpop(0.18, "foo", "foo1"); + assertNull(result); + + jedis.lpush("foo", "bar"); + jedis.lpush("foo1", "bar1"); + result = jedis.blpop(1d, "foo1", "foo"); + + assertNotNull(result); + assertEquals("foo1", result.getKey()); + assertEquals("bar1", result.getElement()); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.blpop(3.12, bfoo); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + + // Binary Multi keys + bresult = jedis.blpop(0.11, bfoo, bfoo1); + assertNull(bresult); + + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo1, bcar); + bresult = jedis.blpop(1d, bfoo, bfoo1); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + public void blpopDoubleWithSleep() { + long startMillis, totalMillis; + + startMillis = System.currentTimeMillis(); + KeyedListElement result = jedis.blpop(0.04, "foo"); + totalMillis = System.currentTimeMillis() - startMillis; + assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); + assertNull(result); + + startMillis = System.currentTimeMillis(); + new Thread(() -> { + try { + Thread.sleep(30); + } catch(InterruptedException e) { + logger.error("", e); + } + jedis.lpush("foo", "bar"); + }).start(); + result = jedis.blpop(1.2, "foo"); + totalMillis = System.currentTimeMillis() - startMillis; + assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); + + assertNotNull(result); + assertEquals("foo", result.getKey()); + assertEquals("bar", result.getElement()); + } + + @Test + public void brpop() throws InterruptedException { + List result = jedis.brpop(1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.brpop(1, "foo"); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); + + // Multi keys + result = jedis.brpop(1, "foo", "foo1"); + assertNull(result); + + jedis.lpush("foo", "bar"); + jedis.lpush("foo1", "bar1"); + result = jedis.brpop(1, "foo1", "foo"); + + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo1", result.get(0)); + assertEquals("bar1", result.get(1)); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.brpop(1, bfoo); + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + + // Binary Multi keys + bresult = jedis.brpop(1, bfoo, bfoo1); + assertNull(bresult); + + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo1, bcar); + bresult = jedis.brpop(1, bfoo, bfoo1); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + public void brpopDouble() throws InterruptedException { + KeyedListElement result = jedis.brpop(0.1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.brpop(3.2, "foo"); + + assertNotNull(result); + assertEquals("foo", result.getKey()); + assertEquals("bar", result.getElement()); + + // Multi keys + result = jedis.brpop(0.18, "foo", "foo1"); + assertNull(result); + + jedis.lpush("foo", "bar"); + jedis.lpush("foo1", "bar1"); + result = jedis.brpop(1d, "foo1", "foo"); + + assertNotNull(result); + assertEquals("foo1", result.getKey()); + assertEquals("bar1", result.getElement()); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.brpop(3.12, bfoo); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + + // Binary Multi keys + bresult = jedis.brpop(0.11, bfoo, bfoo1); + assertNull(bresult); + + jedis.lpush(bfoo, bbar); + jedis.lpush(bfoo1, bcar); + bresult = jedis.brpop(1d, bfoo, bfoo1); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + public void brpopDoubleWithSleep() { + long startMillis, totalMillis; + + startMillis = System.currentTimeMillis(); + KeyedListElement result = jedis.brpop(0.04, "foo"); + totalMillis = System.currentTimeMillis() - startMillis; + assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); + assertNull(result); + + startMillis = System.currentTimeMillis(); + new Thread(() -> { + try { + Thread.sleep(30); + } catch(InterruptedException e) { + logger.error("", e); + } + jedis.lpush("foo", "bar"); + }).start(); + result = jedis.brpop(1.2, "foo"); + totalMillis = System.currentTimeMillis() - startMillis; + assertTrue("TotalMillis=" + totalMillis, totalMillis < 200); + + assertNotNull(result); + assertEquals("foo", result.getKey()); + assertEquals("bar", result.getElement()); + } + + @Test + public void lpushx() { + assertEquals(0, jedis.lpushx("foo", "bar")); + + jedis.lpush("foo", "a"); + assertEquals(2, jedis.lpushx("foo", "b")); + + // Binary + assertEquals(0, jedis.lpushx(bfoo, bbar)); + + jedis.lpush(bfoo, bA); + assertEquals(2, jedis.lpushx(bfoo, bB)); + } + + @Test + public void rpushx() { + assertEquals(0, jedis.rpushx("foo", "bar")); + + jedis.lpush("foo", "a"); + assertEquals(2, jedis.rpushx("foo", "b")); + + // Binary + assertEquals(0, jedis.rpushx(bfoo, bbar)); + + jedis.lpush(bfoo, bA); + assertEquals(2, jedis.rpushx(bfoo, bB)); + } + + @Test + public void linsert() { + assertEquals(0, jedis.linsert("foo", ListPosition.BEFORE, "bar", "car")); + + jedis.lpush("foo", "a"); + assertEquals(2, jedis.linsert("foo", ListPosition.AFTER, "a", "b")); + + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + + assertEquals(expected, jedis.lrange("foo", 0, 100)); + + assertEquals(-1, jedis.linsert("foo", ListPosition.BEFORE, "bar", "car")); + + // Binary + assertEquals(0, jedis.linsert(bfoo, ListPosition.BEFORE, bbar, bcar)); + + jedis.lpush(bfoo, bA); + assertEquals(2, jedis.linsert(bfoo, ListPosition.AFTER, bA, bB)); + + List bexpected = new ArrayList(); + bexpected.add(bA); + bexpected.add(bB); + + assertByteArrayListEquals(bexpected, jedis.lrange(bfoo, 0, 100)); + + assertEquals(-1, jedis.linsert(bfoo, ListPosition.BEFORE, bbar, bcar)); + + } + + @Test + public void brpoplpush() { + + new Thread(new Runnable() { + @Override + public void run() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + jedis.lpush("foo", "a"); + } + }).start(); + + String element = jedis.brpoplpush("foo", "bar", 0); + + assertEquals("a", element); + assertEquals(1, jedis.llen("bar")); + assertEquals("a", jedis.lrange("bar", 0, -1).get(0)); + + // Binary + + new Thread(new Runnable() { + @Override + public void run() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + jedis.lpush(bfoo, bA); + } + }).start(); + + byte[] belement = jedis.brpoplpush(bfoo, bbar, 0); + + assertArrayEquals(bA, belement); + assertEquals(1, jedis.llen("bar")); + assertArrayEquals(bA, jedis.lrange(bbar, 0, -1).get(0)); + } + + @Test + public void lpos() { + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "c"); + + Long pos = jedis.lpos("foo", "b"); + assertEquals(1, pos.intValue()); + pos = jedis.lpos("foo", "d"); + assertNull(pos); + + jedis.rpush("foo", "a"); + jedis.rpush("foo", "b"); + jedis.rpush("foo", "b"); + + pos = jedis.lpos("foo", "b", LPosParams.lPosParams()); + assertEquals(1, pos.intValue()); + pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(3)); + assertEquals(5, pos.intValue()); + pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-2)); + assertEquals(4, pos.intValue()); + pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-5)); + assertNull(pos); + + pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(1).maxlen(2)); + assertEquals(1, pos.intValue()); + pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(2).maxlen(2)); + assertNull(pos); + pos = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-2).maxlen(2)); + assertEquals(4, pos.intValue()); + + List expected = new ArrayList(); + expected.add(1L); + expected.add(4L); + expected.add(5L); + List posList = jedis.lpos("foo", "b", LPosParams.lPosParams(), 2); + assertEquals(expected.subList(0, 2), posList); + posList = jedis.lpos("foo", "b", LPosParams.lPosParams(), 0); + assertEquals(expected, posList); + posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(2), 0); + assertEquals(expected.subList(1, 3), posList); + posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(2).maxlen(5), 0); + assertEquals(expected.subList(1, 2), posList); + + Collections.reverse(expected); + posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-2), 0); + assertEquals(expected.subList(1, 3), posList); + posList = jedis.lpos("foo", "b", LPosParams.lPosParams().rank(-1).maxlen(5), 2); + assertEquals(expected.subList(0, 2), posList); + + // Binary + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bC); + + pos = jedis.lpos(bfoo, bB); + assertEquals(1, pos.intValue()); + pos = jedis.lpos(bfoo, b3); + assertNull(pos); + + jedis.rpush(bfoo, bA); + jedis.rpush(bfoo, bB); + jedis.rpush(bfoo, bA); + + pos = jedis.lpos(bfoo, bB, LPosParams.lPosParams().rank(2)); + assertEquals(4, pos.intValue()); + pos = jedis.lpos(bfoo, bB, LPosParams.lPosParams().rank(-2).maxlen(5)); + assertEquals(1, pos.intValue()); + + expected.clear(); + expected.add(0L); + expected.add(3L); + expected.add(5L); + + posList = jedis.lpos(bfoo, bA, LPosParams.lPosParams().maxlen(6), 0); + assertEquals(expected, posList); + posList = jedis.lpos(bfoo, bA, LPosParams.lPosParams().maxlen(6).rank(2), 1); + assertEquals(expected.subList(1, 2), posList); + + } + + @Test + public void lmove() { + jedis.rpush("foo", "bar1", "bar2", "bar3"); + assertEquals("bar3", jedis.lmove("foo", "bar", ListDirection.RIGHT, ListDirection.LEFT)); + assertEquals(Collections.singletonList("bar3"), jedis.lrange("bar", 0, -1)); + assertEquals(Arrays.asList("bar1", "bar2"), jedis.lrange("foo", 0, -1)); + + // Binary + jedis.rpush(bfoo, b1, b2, b3); + assertArrayEquals(b3, jedis.lmove(bfoo, bbar, ListDirection.RIGHT, ListDirection.LEFT)); + assertByteArrayListEquals(Collections.singletonList(b3), jedis.lrange(bbar, 0, -1)); + assertByteArrayListEquals(Arrays.asList(b1, b2), jedis.lrange(bfoo, 0, -1)); + } + + @Test + public void blmove() { + new Thread(() -> { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + jedis.rpush("foo", "bar1", "bar2", "bar3"); + }).start(); + + assertEquals("bar3", jedis.blmove("foo", "bar", ListDirection.RIGHT, ListDirection.LEFT, 0)); + assertEquals(Collections.singletonList("bar3"), jedis.lrange("bar", 0, -1)); + assertEquals(Arrays.asList("bar1", "bar2"), jedis.lrange("foo", 0, -1)); + + // Binary + new Thread(() -> { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + jedis.rpush(bfoo, b1, b2, b3); + }).start(); + assertArrayEquals(b3, jedis.blmove(bfoo, bbar, ListDirection.RIGHT, ListDirection.LEFT, 0)); + assertByteArrayListEquals(Collections.singletonList(b3), jedis.lrange(bbar, 0, -1)); + assertByteArrayListEquals(Arrays.asList(b1, b2), jedis.lrange(bfoo, 0, -1)); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/SetCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/SetCommandsTestBase.java new file mode 100644 index 0000000000..94f6c7eb9b --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/SetCommandsTestBase.java @@ -0,0 +1,607 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; + +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayCollectionContainsAll; +import static redis.clients.jedis.util.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContainsAll; +import static redis.clients.jedis.util.ByteArrayUtil.byteArrayCollectionRemoveAll; + +import java.util.Arrays; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.junit.Test; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; + +public abstract class SetCommandsTestBase extends UnifiedJedisCommandsTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + final byte[] bc = { 0x0C }; + final byte[] bd = { 0x0D }; + final byte[] bx = { 0x42 }; + + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + + @Test + public void sadd() { + long status = jedis.sadd("foo", "a"); + assertEquals(1, status); + + status = jedis.sadd("foo", "a"); + assertEquals(0, status); + + long bstatus = jedis.sadd(bfoo, ba); + assertEquals(1, bstatus); + + bstatus = jedis.sadd(bfoo, ba); + assertEquals(0, bstatus); + + } + + @Test + public void smembers() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + Set expected = new HashSet(); + expected.add("a"); + expected.add("b"); + + Set members = jedis.smembers("foo"); + + assertEquals(expected, members); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(ba); + + Set bmembers = jedis.smembers(bfoo); + + assertByteArraySetEquals(bexpected, bmembers); + } + + @Test + public void srem() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + long status = jedis.srem("foo", "a"); + + Set expected = new HashSet(); + expected.add("b"); + + assertEquals(1, status); + assertEquals(expected, jedis.smembers("foo")); + + status = jedis.srem("foo", "bar"); + + assertEquals(0, status); + + // Binary + + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + long bstatus = jedis.srem(bfoo, ba); + + Set bexpected = new HashSet(); + bexpected.add(bb); + + assertEquals(1, bstatus); + assertByteArraySetEquals(bexpected, jedis.smembers(bfoo)); + + bstatus = jedis.srem(bfoo, bbar); + + assertEquals(0, bstatus); + + } + + @Test + public void spop() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + String member = jedis.spop("foo"); + + assertTrue("a".equals(member) || "b".equals(member)); + assertEquals(1, jedis.smembers("foo").size()); + + member = jedis.spop("bar"); + assertNull(member); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + byte[] bmember = jedis.spop(bfoo); + + assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); + assertEquals(1, jedis.smembers(bfoo).size()); + + bmember = jedis.spop(bbar); + assertNull(bmember); + + } + + @Test + public void spopWithCount() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); + + Set superSet = new HashSet(); + superSet.add("c"); + superSet.add("b"); + superSet.add("a"); + + Set members = jedis.spop("foo", 2); + + assertEquals(2, members.size()); + assertCollectionContainsAll(superSet, members); + superSet.removeAll(members); + + members = jedis.spop("foo", 2); + assertEquals(1, members.size()); + assertEquals(superSet, members); + + assertTrue(jedis.spop("foo", 2).isEmpty()); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); + + Set bsuperSet = new HashSet(); + bsuperSet.add(bc); + bsuperSet.add(bb); + bsuperSet.add(ba); + + Set bmembers = jedis.spop(bfoo, 2); + + assertEquals(2, bmembers.size()); + assertByteArrayCollectionContainsAll(bsuperSet, bmembers); + byteArrayCollectionRemoveAll(bsuperSet, bmembers); + + bmembers = jedis.spop(bfoo, 2); + assertEquals(1, bmembers.size()); + assertByteArraySetEquals(bsuperSet, bmembers); + + assertTrue(jedis.spop(bfoo, 2).isEmpty()); + } + + @Test + public void smove() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + jedis.sadd("bar", "c"); + + long status = jedis.smove("foo", "bar", "a"); + + Set expectedSrc = new HashSet(); + expectedSrc.add("b"); + + Set expectedDst = new HashSet(); + expectedDst.add("c"); + expectedDst.add("a"); + + assertEquals(status, 1); + assertEquals(expectedSrc, jedis.smembers("foo")); + assertEquals(expectedDst, jedis.smembers("bar")); + + status = jedis.smove("foo", "bar", "a"); + + assertEquals(status, 0); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bc); + + long bstatus = jedis.smove(bfoo, bbar, ba); + + Set bexpectedSrc = new HashSet(); + bexpectedSrc.add(bb); + + Set bexpectedDst = new HashSet(); + bexpectedDst.add(bc); + bexpectedDst.add(ba); + + assertEquals(bstatus, 1); + assertByteArraySetEquals(bexpectedSrc, jedis.smembers(bfoo)); + assertByteArraySetEquals(bexpectedDst, jedis.smembers(bbar)); + + bstatus = jedis.smove(bfoo, bbar, ba); + assertEquals(bstatus, 0); + + } + + @Test + public void scard() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + long card = jedis.scard("foo"); + + assertEquals(2, card); + + card = jedis.scard("bar"); + assertEquals(0, card); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + long bcard = jedis.scard(bfoo); + + assertEquals(2, bcard); + + bcard = jedis.scard(bbar); + assertEquals(0, bcard); + + } + + @Test + public void sismember() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + assertTrue(jedis.sismember("foo", "a")); + + assertFalse(jedis.sismember("foo", "c")); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + assertTrue(jedis.sismember(bfoo, ba)); + + assertFalse(jedis.sismember(bfoo, bc)); + + } + + @Test + public void smismember() { + jedis.sadd("foo", "a", "b"); + + assertEquals(Arrays.asList(true, false), jedis.smismember("foo", "a", "c")); + + // Binary + jedis.sadd(bfoo, ba, bb); + + assertEquals(Arrays.asList(true, false), jedis.smismember(bfoo, ba, bc)); + } + + @Test + public void sinter() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); + + Set expected = new HashSet(); + expected.add("b"); + + Set intersection = jedis.sinter("foo", "bar"); + assertEquals(expected, intersection); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new HashSet(); + bexpected.add(bb); + + Set bintersection = jedis.sinter(bfoo, bbar); + assertByteArraySetEquals(bexpected, bintersection); + } + + @Test + public void sinterstore() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); + + Set expected = new HashSet(); + expected.add("b"); + + long status = jedis.sinterstore("car", "foo", "bar"); + assertEquals(1, status); + + assertEquals(expected, jedis.smembers("car")); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new HashSet(); + bexpected.add(bb); + + long bstatus = jedis.sinterstore(bcar, bfoo, bbar); + assertEquals(1, bstatus); + + assertByteArraySetEquals(bexpected, jedis.smembers(bcar)); + + } + + @Test + public void sunion() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); + + Set expected = new HashSet(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + + Set union = jedis.sunion("foo", "bar"); + assertEquals(expected, union); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(bc); + bexpected.add(ba); + + Set bunion = jedis.sunion(bfoo, bbar); + assertByteArraySetEquals(bexpected, bunion); + + } + + @Test + public void sunionstore() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + jedis.sadd("bar", "b"); + jedis.sadd("bar", "c"); + + Set expected = new HashSet(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + + long status = jedis.sunionstore("car", "foo", "bar"); + assertEquals(3, status); + + assertEquals(expected, jedis.smembers("car")); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + jedis.sadd(bbar, bb); + jedis.sadd(bbar, bc); + + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(bc); + bexpected.add(ba); + + long bstatus = jedis.sunionstore(bcar, bfoo, bbar); + assertEquals(3, bstatus); + + assertByteArraySetEquals(bexpected, jedis.smembers(bcar)); + + } + + @Test + public void sdiff() { + jedis.sadd("foo", "x"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); + + jedis.sadd("bar", "c"); + + jedis.sadd("car", "a"); + jedis.sadd("car", "d"); + + Set expected = new HashSet(); + expected.add("x"); + expected.add("b"); + + Set diff = jedis.sdiff("foo", "bar", "car"); + assertEquals(expected, diff); + + // Binary + jedis.sadd(bfoo, bx); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); + + jedis.sadd(bbar, bc); + + jedis.sadd(bcar, ba); + jedis.sadd(bcar, bd); + + Set bexpected = new HashSet(); + bexpected.add(bb); + bexpected.add(bx); + + Set bdiff = jedis.sdiff(bfoo, bbar, bcar); + assertByteArraySetEquals(bexpected, bdiff); + + } + + @Test + public void sdiffstore() { + jedis.sadd("foo", "x"); + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + jedis.sadd("foo", "c"); + + jedis.sadd("bar", "c"); + + jedis.sadd("car", "a"); + jedis.sadd("car", "d"); + + Set expected = new HashSet(); + expected.add("x"); + expected.add("b"); + + long status = jedis.sdiffstore("tar", "foo", "bar", "car"); + assertEquals(2, status); + assertEquals(expected, jedis.smembers("tar")); + + // Binary + jedis.sadd(bfoo, bx); + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + jedis.sadd(bfoo, bc); + + jedis.sadd(bbar, bc); + + jedis.sadd(bcar, ba); + jedis.sadd(bcar, bd); + + Set bexpected = new HashSet(); + bexpected.add(bx); + bexpected.add(bb); + + long bstatus = jedis.sdiffstore("tar".getBytes(), bfoo, bbar, bcar); + assertEquals(2, bstatus); + assertByteArraySetEquals(bexpected, jedis.smembers("tar".getBytes())); + + } + + @Test + public void srandmember() { + jedis.sadd("foo", "a"); + jedis.sadd("foo", "b"); + + String member = jedis.srandmember("foo"); + + assertTrue("a".equals(member) || "b".equals(member)); + assertEquals(2, jedis.smembers("foo").size()); + + List members = jedis.srandmember("foo", 2); + members.sort(Comparator.naturalOrder()); + assertEquals( Arrays.asList("a", "b"), members); + + member = jedis.srandmember("bar"); + assertNull(member); + + members = jedis.srandmember("bar", 2); + assertEquals(0, members.size()); + + // Binary + jedis.sadd(bfoo, ba); + jedis.sadd(bfoo, bb); + + byte[] bmember = jedis.srandmember(bfoo); + + assertTrue(Arrays.equals(ba, bmember) || Arrays.equals(bb, bmember)); + assertEquals(2, jedis.smembers(bfoo).size()); + + List bmembers = jedis.srandmember(bfoo, 2); + assertEquals(2, bmembers.size()); + + bmember = jedis.srandmember(bbar); + assertNull(bmember); + + members = jedis.srandmember("bbar", 2); + assertEquals(0, members.size()); + } + + @Test + public void sscan() { + jedis.sadd("foo", "a", "b"); + + ScanResult result = jedis.sscan("foo", SCAN_POINTER_START); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + jedis.sadd(bfoo, ba, bb); + + ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void sscanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.sadd("foo", "b", "a", "aa"); + ScanResult result = jedis.sscan("foo", SCAN_POINTER_START, params); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bbarstar); + + jedis.sadd(bfoo, bbar1, bbar2, bbar3); + ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void sscanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + jedis.sadd("foo", "a1", "a2", "a3", "a4", "a5"); + + ScanResult result = jedis.sscan("foo", SCAN_POINTER_START, params); + + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.sadd(bfoo, bbar1, bbar2, bbar3); + ScanResult bResult = jedis.sscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/SortedSetCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/SortedSetCommandsTestBase.java new file mode 100644 index 0000000000..8f923ddb7a --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/SortedSetCommandsTestBase.java @@ -0,0 +1,1540 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.*; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START_BINARY; +import static redis.clients.jedis.util.AssertUtil.assertByteArrayListEquals; +import static redis.clients.jedis.util.AssertUtil.assertByteArraySetEquals; +import static redis.clients.jedis.util.AssertUtil.assertCollectionContains; + +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.Test; + +import redis.clients.jedis.BuilderFactory; +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.params.ZAddParams; +import redis.clients.jedis.params.ZIncrByParams; +import redis.clients.jedis.params.ZParams; +import redis.clients.jedis.resps.KeyedZSetElement; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.resps.Tuple; +import redis.clients.jedis.util.SafeEncoder; + +public class SortedSetCommandsTestBase extends UnifiedJedisCommandsTestBase { + final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; + final byte[] bbar = { 0x05, 0x06, 0x07, 0x08 }; + final byte[] bcar = { 0x09, 0x0A, 0x0B, 0x0C }; + final byte[] ba = { 0x0A }; + final byte[] bb = { 0x0B }; + final byte[] bc = { 0x0C }; + final byte[] bInclusiveB = { 0x5B, 0x0B }; + final byte[] bExclusiveC = { 0x28, 0x0C }; + final byte[] bLexMinusInf = { 0x2D }; + final byte[] bLexPlusInf = { 0x2B }; + + final byte[] bbar1 = { 0x05, 0x06, 0x07, 0x08, 0x0A }; + final byte[] bbar2 = { 0x05, 0x06, 0x07, 0x08, 0x0B }; + final byte[] bbar3 = { 0x05, 0x06, 0x07, 0x08, 0x0C }; + final byte[] bbarstar = { 0x05, 0x06, 0x07, 0x08, '*' }; + + @Test + public void zadd() { + assertEquals(1, jedis.zadd("foo", 1d, "a")); + + assertEquals(1, jedis.zadd("foo", 10d, "b")); + + assertEquals(1, jedis.zadd("foo", 0.1d, "c")); + + assertEquals(0, jedis.zadd("foo", 2d, "a")); + + // Binary + assertEquals(1, jedis.zadd(bfoo, 1d, ba)); + + assertEquals(1, jedis.zadd(bfoo, 10d, bb)); + + assertEquals(1, jedis.zadd(bfoo, 0.1d, bc)); + + assertEquals(0, jedis.zadd(bfoo, 2d, ba)); + } + + @Test + public void zaddWithParams() { + jedis.del("foo"); + + // xx: never add new member + assertEquals(0L, jedis.zadd("foo", 1d, "a", ZAddParams.zAddParams().xx())); + + jedis.zadd("foo", 1d, "a"); + // nx: never update current member + assertEquals(0L, jedis.zadd("foo", 2d, "a", ZAddParams.zAddParams().nx())); + assertEquals(Double.valueOf(1d), jedis.zscore("foo", "a")); + + Map scoreMembers = new HashMap(); + scoreMembers.put("a", 2d); + scoreMembers.put("b", 1d); + // ch: return count of members not only added, but also updated + assertEquals(2L, jedis.zadd("foo", scoreMembers, ZAddParams.zAddParams().ch())); + + // lt: only update existing elements if the new score is less than the current score. + jedis.zadd("foo", 3d, "a", ZAddParams.zAddParams().lt()); + assertEquals(Double.valueOf(2d), jedis.zscore("foo", "a")); + jedis.zadd("foo", 1d, "a", ZAddParams.zAddParams().lt()); + assertEquals(Double.valueOf(1d), jedis.zscore("foo", "a")); + + // gt: only update existing elements if the new score is greater than the current score. + jedis.zadd("foo", 0d, "b", ZAddParams.zAddParams().gt()); + assertEquals(Double.valueOf(1d), jedis.zscore("foo", "b")); + jedis.zadd("foo", 2d, "b", ZAddParams.zAddParams().gt()); + assertEquals(Double.valueOf(2d), jedis.zscore("foo", "b")); + + // incr: don't update already existing elements. + assertNull(jedis.zaddIncr("foo", 1d, "b", ZAddParams.zAddParams().nx())); + assertEquals(Double.valueOf(2d), jedis.zscore("foo", "b")); + // incr: update elements that already exist. + assertEquals(Double.valueOf(3d), jedis.zaddIncr("foo", 1d,"b", ZAddParams.zAddParams().xx())); + assertEquals(Double.valueOf(3d), jedis.zscore("foo", "b")); + + // binary + jedis.del(bfoo); + + // xx: never add new member + assertEquals(0L, jedis.zadd(bfoo, 1d, ba, ZAddParams.zAddParams().xx())); + + jedis.zadd(bfoo, 1d, ba); + // nx: never update current member + assertEquals(0L, jedis.zadd(bfoo, 2d, ba, ZAddParams.zAddParams().nx())); + assertEquals(Double.valueOf(1d), jedis.zscore(bfoo, ba)); + + Map binaryScoreMembers = new HashMap(); + binaryScoreMembers.put(ba, 2d); + binaryScoreMembers.put(bb, 1d); + // ch: return count of members not only added, but also updated + assertEquals(2L, jedis.zadd(bfoo, binaryScoreMembers, ZAddParams.zAddParams().ch())); + + // lt: only update existing elements if the new score is less than the current score. + jedis.zadd(bfoo, 3d, ba, ZAddParams.zAddParams().lt()); + assertEquals(Double.valueOf(2d), jedis.zscore(bfoo, ba)); + jedis.zadd(bfoo, 1d, ba, ZAddParams.zAddParams().lt()); + assertEquals(Double.valueOf(1d), jedis.zscore(bfoo, ba)); + + // gt: only update existing elements if the new score is greater than the current score. + jedis.zadd(bfoo, 0d, bb, ZAddParams.zAddParams().gt()); + assertEquals(Double.valueOf(1d), jedis.zscore(bfoo, bb)); + jedis.zadd(bfoo, 2d, bb, ZAddParams.zAddParams().gt()); + assertEquals(Double.valueOf(2d), jedis.zscore(bfoo, bb)); + + // incr: don't update already existing elements. + assertNull(jedis.zaddIncr(bfoo, 1d, bb, ZAddParams.zAddParams().nx())); + assertEquals(Double.valueOf(2d), jedis.zscore(bfoo, bb)); + // incr: update elements that already exist. + assertEquals(Double.valueOf(3d), jedis.zaddIncr(bfoo, 1d, bb, ZAddParams.zAddParams().xx())); + assertEquals(Double.valueOf(3d), jedis.zscore(bfoo, bb)); + } + + @Test + public void zrange() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + List expected = new ArrayList(); + expected.add("c"); + expected.add("a"); + + List range = jedis.zrange("foo", 0, 1); + assertEquals(expected, range); + + expected.add("b"); + range = jedis.zrange("foo", 0, 100); + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List bexpected = new ArrayList(); + bexpected.add(bc); + bexpected.add(ba); + + List brange = jedis.zrange(bfoo, 0, 1); + assertByteArrayListEquals(bexpected, brange); + + bexpected.add(bb); + brange = jedis.zrange(bfoo, 0, 100); + assertByteArrayListEquals(bexpected, brange); + } + + @Test + public void zrangeByLex() { + jedis.zadd("foo", 1, "aa"); + jedis.zadd("foo", 1, "c"); + jedis.zadd("foo", 1, "bb"); + jedis.zadd("foo", 1, "d"); + + List expected = new ArrayList(); + expected.add("bb"); + expected.add("c"); + + // exclusive aa ~ inclusive c + assertEquals(expected, jedis.zrangeByLex("foo", "(aa", "[c")); + + expected.clear(); + expected.add("bb"); + expected.add("c"); + + // with LIMIT + assertEquals(expected, jedis.zrangeByLex("foo", "-", "+", 1, 2)); + } + + @Test + public void zrangeByLexBinary() { + // binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 1, bc); + jedis.zadd(bfoo, 1, bb); + + List bExpected = new ArrayList(); + bExpected.add(bb); + + assertByteArrayListEquals(bExpected, jedis.zrangeByLex(bfoo, bInclusiveB, bExclusiveC)); + + bExpected.clear(); + bExpected.add(ba); + bExpected.add(bb); + + // with LIMIT + assertByteArrayListEquals(bExpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf, 0, 2)); + } + + @Test + public void zrevrangeByLex() { + jedis.zadd("foo", 1, "aa"); + jedis.zadd("foo", 1, "c"); + jedis.zadd("foo", 1, "bb"); + jedis.zadd("foo", 1, "d"); + + List expected = new ArrayList(); + expected.add("c"); + expected.add("bb"); + + // exclusive aa ~ inclusive c + assertEquals(expected, jedis.zrevrangeByLex("foo", "[c", "(aa")); + + expected.clear(); + expected.add("c"); + expected.add("bb"); + + // with LIMIT + assertEquals(expected, jedis.zrevrangeByLex("foo", "+", "-", 1, 2)); + } + + @Test + public void zrevrangeByLexBinary() { + // binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 1, bc); + jedis.zadd(bfoo, 1, bb); + + List bExpected = new ArrayList(); + bExpected.add(bb); + + assertByteArrayListEquals(bExpected, jedis.zrevrangeByLex(bfoo, bExclusiveC, bInclusiveB)); + + bExpected.clear(); + bExpected.add(bc); + bExpected.add(bb); + + // with LIMIT + assertByteArrayListEquals(bExpected, jedis.zrevrangeByLex(bfoo, bLexPlusInf, bLexMinusInf, 0, 2)); + } + + @Test + public void zrevrange() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + List expected = new ArrayList(); + expected.add("b"); + expected.add("a"); + + List range = jedis.zrevrange("foo", 0, 1); + assertEquals(expected, range); + + expected.add("c"); + range = jedis.zrevrange("foo", 0, 100); + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List bexpected = new ArrayList(); + bexpected.add(bb); + bexpected.add(ba); + + List brange = jedis.zrevrange(bfoo, 0, 1); + assertByteArrayListEquals(bexpected, brange); + + bexpected.add(bc); + brange = jedis.zrevrange(bfoo, 0, 100); + assertByteArrayListEquals(bexpected, brange); + } + + @Test + public void zrem() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); + + assertEquals(1, jedis.zrem("foo", "a")); + + List expected = new ArrayList(); + expected.add("b"); + + assertEquals(expected, jedis.zrange("foo", 0, 100)); + + assertEquals(0, jedis.zrem("foo", "bar")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + assertEquals(1, jedis.zrem(bfoo, ba)); + + List bexpected = new ArrayList(); + bexpected.add(bb); + + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + + assertEquals(0, jedis.zrem(bfoo, bbar)); + } + + @Test + public void zincrby() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); + + assertEquals(3d, jedis.zincrby("foo", 2d, "a"), 0); + + List expected = new ArrayList(); + expected.add("b"); + expected.add("a"); + + assertEquals(expected, jedis.zrange("foo", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + assertEquals(3d, jedis.zincrby(bfoo, 2d, ba), 0); + + List bexpected = new ArrayList(); + bexpected.add(bb); + bexpected.add(ba); + + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + } + + @Test + public void zincrbyWithParams() { + jedis.del("foo"); + + // xx: never add new member + assertNull(jedis.zincrby("foo", 2d, "a", ZIncrByParams.zIncrByParams().xx())); + + jedis.zadd("foo", 2d, "a"); + + // nx: never update current member + assertNull(jedis.zincrby("foo", 1d, "a", ZIncrByParams.zIncrByParams().nx())); + assertEquals(Double.valueOf(2d), jedis.zscore("foo", "a")); + + // Binary + + jedis.del(bfoo); + + // xx: never add new member + assertNull(jedis.zincrby(bfoo, 2d, ba, ZIncrByParams.zIncrByParams().xx())); + + jedis.zadd(bfoo, 2d, ba); + + // nx: never update current member + assertNull(jedis.zincrby(bfoo, 1d, ba, ZIncrByParams.zIncrByParams().nx())); + assertEquals(Double.valueOf(2d), jedis.zscore(bfoo, ba)); + } + + @Test + public void zrank() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); + + long rank = jedis.zrank("foo", "a"); + assertEquals(0, rank); + + rank = jedis.zrank("foo", "b"); + assertEquals(1, rank); + + assertNull(jedis.zrank("car", "b")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + long brank = jedis.zrank(bfoo, ba); + assertEquals(0, brank); + + brank = jedis.zrank(bfoo, bb); + assertEquals(1, brank); + + assertNull(jedis.zrank(bcar, bb)); + } + + @Test + public void zrevrank() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 2d, "b"); + + long rank = jedis.zrevrank("foo", "a"); + assertEquals(1, rank); + + rank = jedis.zrevrank("foo", "b"); + assertEquals(0, rank); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 2d, bb); + + long brank = jedis.zrevrank(bfoo, ba); + assertEquals(1, brank); + + brank = jedis.zrevrank(bfoo, bb); + assertEquals(0, brank); + } + + @Test + public void zrangeWithScores() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + List expected = new ArrayList(); + expected.add(new Tuple("c", 0.1d)); + expected.add(new Tuple("a", 2d)); + + List range = jedis.zrangeWithScores("foo", 0, 1); + assertEquals(expected, range); + + expected.add(new Tuple("b", 10d)); + range = jedis.zrangeWithScores("foo", 0, 100); + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); + + List brange = jedis.zrangeWithScores(bfoo, 0, 1); + assertEquals(bexpected, brange); + + bexpected.add(new Tuple(bb, 10d)); + brange = jedis.zrangeWithScores(bfoo, 0, 100); + assertEquals(bexpected, brange); + + } + + @Test + public void zrevrangeWithScores() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + List expected = new ArrayList(); + expected.add(new Tuple("b", 10d)); + expected.add(new Tuple("a", 2d)); + + List range = jedis.zrevrangeWithScores("foo", 0, 1); + assertEquals(expected, range); + + expected.add(new Tuple("c", 0.1d)); + range = jedis.zrevrangeWithScores("foo", 0, 100); + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(bb, 10d)); + bexpected.add(new Tuple(ba, 2d)); + + List brange = jedis.zrevrangeWithScores(bfoo, 0, 1); + assertEquals(bexpected, brange); + + bexpected.add(new Tuple(bc, 0.1d)); + brange = jedis.zrevrangeWithScores(bfoo, 0, 100); + assertEquals(bexpected, brange); + } + + @Test + public void zcard() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + assertEquals(3, jedis.zcard("foo")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + assertEquals(3, jedis.zcard(bfoo)); + } + + @Test + public void zscore() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + assertEquals((Double) 10d, jedis.zscore("foo", "b")); + + assertEquals((Double) 0.1d, jedis.zscore("foo", "c")); + + assertNull(jedis.zscore("foo", "s")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + assertEquals((Double) 10d, jedis.zscore(bfoo, bb)); + + assertEquals((Double) 0.1d, jedis.zscore(bfoo, bc)); + + assertNull(jedis.zscore(bfoo, SafeEncoder.encode("s"))); + + } + + @Test + public void zmscore() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + assertEquals(Arrays.asList(10d, 0.1d, null), jedis.zmscore("foo", "b", "c", "s")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + assertEquals(Arrays.asList(10d, 0.1d, null), + jedis.zmscore(bfoo, bb, bc, SafeEncoder.encode("s"))); + } + + @Test + public void zpopmax() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "d"); + + Tuple actual = jedis.zpopmax("foo"); + Tuple expected = new Tuple("b", 10d); + assertEquals(expected, actual); + + actual = jedis.zpopmax("foo"); + expected = new Tuple("d", 2d); + assertEquals(expected, actual); + + actual = jedis.zpopmax("foo"); + expected = new Tuple("a", 1d); + assertEquals(expected, actual); + + actual = jedis.zpopmax("foo"); + expected = new Tuple("c", 0.1d); + assertEquals(expected, actual); + + // Empty + actual = jedis.zpopmax("foo"); + assertNull(actual); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + // First + actual = jedis.zpopmax(bfoo); + expected = new Tuple(bb, 10d); + assertEquals(expected, actual); + + // Second + actual = jedis.zpopmax(bfoo); + expected = new Tuple(ba, 2d); + assertEquals(expected, actual); + + // Third + actual = jedis.zpopmax(bfoo); + expected = new Tuple(bc, 0.1d); + assertEquals(expected, actual); + + // Empty + actual = jedis.zpopmax(bfoo); + assertNull(actual); + } + + @Test + public void zpopmaxWithCount() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "d"); + jedis.zadd("foo", 0.03, "e"); + + List actual = jedis.zpopmax("foo", 2); + assertEquals(2, actual.size()); + + List expected = new ArrayList(); + expected.add(new Tuple("b", 10d)); + expected.add(new Tuple("d", 2d)); + assertEquals(expected, actual); + + actual = jedis.zpopmax("foo", 3); + assertEquals(3, actual.size()); + + expected.clear(); + expected.add(new Tuple("a", 1d)); + expected.add(new Tuple("c", 0.1d)); + expected.add(new Tuple("e", 0.03d)); + assertEquals(expected, actual); + + // Empty + actual = jedis.zpopmax("foo", 1); + expected.clear(); + assertEquals(expected, actual); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + // First + actual = jedis.zpopmax(bfoo, 1); + expected.clear(); + expected.add(new Tuple(bb, 10d)); + assertEquals(expected, actual); + + // Second + actual = jedis.zpopmax(bfoo, 1); + expected.clear(); + expected.add(new Tuple(ba, 2d)); + assertEquals(expected, actual); + + // Last 2 (just 1, because 1 was overwritten) + actual = jedis.zpopmax(bfoo, 1); + expected.clear(); + expected.add(new Tuple(bc, 0.1d)); + assertEquals(expected, actual); + + // Empty + actual = jedis.zpopmax(bfoo, 1); + expected.clear(); + assertEquals(expected, actual); + } + + @Test + public void zpopmin() { + + jedis.zadd("foo", 1d, "a", ZAddParams.zAddParams().nx()); + jedis.zadd("foo", 10d, "b", ZAddParams.zAddParams().nx()); + jedis.zadd("foo", 0.1d, "c", ZAddParams.zAddParams().nx()); + jedis.zadd("foo", 2d, "a", ZAddParams.zAddParams().nx()); + + List range = jedis.zpopmin("foo", 2); + + List expected = new ArrayList(); + expected.add(new Tuple("c", 0.1d)); + expected.add(new Tuple("a", 1d)); + + assertEquals(expected, range); + + assertEquals(new Tuple("b", 10d), jedis.zpopmin("foo")); + + // Binary + + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List brange = jedis.zpopmin(bfoo, 2); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); + + assertEquals(bexpected, brange); + + assertEquals(new Tuple(bb, 10d), jedis.zpopmin(bfoo)); + } + + @Test + public void zcount() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + assertEquals(2, jedis.zcount("foo", 0.01d, 2.1d)); + + assertEquals(3, jedis.zcount("foo", "(0.01", "+inf")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + assertEquals(2, jedis.zcount(bfoo, 0.01d, 2.1d)); + + assertEquals(3, jedis.zcount(bfoo, SafeEncoder.encode("(0.01"), SafeEncoder.encode("+inf"))); + } + + @Test + public void zlexcount() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 1, "b"); + jedis.zadd("foo", 1, "c"); + jedis.zadd("foo", 1, "aa"); + + assertEquals(2, jedis.zlexcount("foo", "[aa", "(c")); + + assertEquals(4, jedis.zlexcount("foo", "-", "+")); + + assertEquals(3, jedis.zlexcount("foo", "-", "(c")); + + assertEquals(3, jedis.zlexcount("foo", "[aa", "+")); + } + + @Test + public void zlexcountBinary() { + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 1, bc); + jedis.zadd(bfoo, 1, bb); + + assertEquals(1, jedis.zlexcount(bfoo, bInclusiveB, bExclusiveC)); + + assertEquals(3, jedis.zlexcount(bfoo, bLexMinusInf, bLexPlusInf)); + } + + @Test + public void zrangebyscore() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + List range = jedis.zrangeByScore("foo", 0d, 2d); + + List expected = new ArrayList(); + expected.add("c"); + expected.add("a"); + + assertEquals(expected, range); + + range = jedis.zrangeByScore("foo", 0d, 2d, 0, 1); + + expected = new ArrayList(); + expected.add("c"); + + assertEquals(expected, range); + + range = jedis.zrangeByScore("foo", 0d, 2d, 1, 1); + List range2 = jedis.zrangeByScore("foo", "-inf", "(2"); + assertEquals(expected, range2); + + expected = new ArrayList(); + expected.add("a"); + + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List brange = jedis.zrangeByScore(bfoo, 0d, 2d); + + List bexpected = new ArrayList(); + bexpected.add(bc); + bexpected.add(ba); + + assertByteArrayListEquals(bexpected, brange); + + brange = jedis.zrangeByScore(bfoo, 0d, 2d, 0, 1); + + bexpected = new ArrayList(); + bexpected.add(bc); + + assertByteArrayListEquals(bexpected, brange); + + brange = jedis.zrangeByScore(bfoo, 0d, 2d, 1, 1); + List brange2 = jedis.zrangeByScore(bfoo, SafeEncoder.encode("-inf"), + SafeEncoder.encode("(2")); + assertByteArrayListEquals(bexpected, brange2); + + bexpected = new ArrayList(); + bexpected.add(ba); + + assertByteArrayListEquals(bexpected, brange); + + } + + @Test + public void zrevrangebyscore() { + jedis.zadd("foo", 1.0d, "a"); + jedis.zadd("foo", 2.0d, "b"); + jedis.zadd("foo", 3.0d, "c"); + jedis.zadd("foo", 4.0d, "d"); + jedis.zadd("foo", 5.0d, "e"); + + List range = jedis.zrevrangeByScore("foo", 3d, Double.NEGATIVE_INFINITY, 0, 1); + List expected = new ArrayList(); + expected.add("c"); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, 0, 2); + expected = new ArrayList(); + expected.add("c"); + expected.add("b"); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScore("foo", 3.5d, Double.NEGATIVE_INFINITY, 1, 1); + expected = new ArrayList(); + expected.add("b"); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScore("foo", 4d, 2d); + expected = new ArrayList(); + expected.add("d"); + expected.add("c"); + expected.add("b"); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScore("foo", "+inf", "(4"); + expected = new ArrayList(); + expected.add("e"); + + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List brange = jedis.zrevrangeByScore(bfoo, 2d, 0d); + + List bexpected = new ArrayList(); + bexpected.add(ba); + bexpected.add(bc); + + assertByteArrayListEquals(bexpected, brange); + + brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 0, 1); + + bexpected = new ArrayList(); + bexpected.add(ba); + + assertByteArrayListEquals(bexpected, brange); + + List brange2 = jedis.zrevrangeByScore(bfoo, SafeEncoder.encode("+inf"), + SafeEncoder.encode("(2")); + + bexpected = new ArrayList(); + bexpected.add(bb); + + assertByteArrayListEquals(bexpected, brange2); + + brange = jedis.zrevrangeByScore(bfoo, 2d, 0d, 1, 1); + bexpected = new ArrayList(); + bexpected.add(bc); + + assertByteArrayListEquals(bexpected, brange); + } + + @Test + public void zrangebyscoreWithScores() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + List range = jedis.zrangeByScoreWithScores("foo", 0d, 2d); + + List expected = new ArrayList(); + expected.add(new Tuple("c", 0.1d)); + expected.add(new Tuple("a", 2d)); + + assertEquals(expected, range); + + range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 0, 1); + + expected = new ArrayList(); + expected.add(new Tuple("c", 0.1d)); + + assertEquals(expected, range); + + range = jedis.zrangeByScoreWithScores("foo", 0d, 2d, 1, 1); + + expected = new ArrayList(); + expected.add(new Tuple("a", 2d)); + + assertEquals(expected, range); + + // Binary + + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(bc, 0.1d)); + bexpected.add(new Tuple(ba, 2d)); + + assertEquals(bexpected, brange); + + brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 0, 1); + + bexpected = new ArrayList(); + bexpected.add(new Tuple(bc, 0.1d)); + + assertEquals(bexpected, brange); + + brange = jedis.zrangeByScoreWithScores(bfoo, 0d, 2d, 1, 1); + + bexpected = new ArrayList(); + bexpected.add(new Tuple(ba, 2d)); + + assertEquals(bexpected, brange); + + } + + @Test + public void zrevrangebyscoreWithScores() { + jedis.zadd("foo", 1.0d, "a"); + jedis.zadd("foo", 2.0d, "b"); + jedis.zadd("foo", 3.0d, "c"); + jedis.zadd("foo", 4.0d, "d"); + jedis.zadd("foo", 5.0d, "e"); + + List range = jedis.zrevrangeByScoreWithScores("foo", 3d, Double.NEGATIVE_INFINITY, 0, 1); + List expected = new ArrayList(); + expected.add(new Tuple("c", 3.0d)); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, Double.NEGATIVE_INFINITY, 0, 2); + expected = new ArrayList(); + expected.add(new Tuple("c", 3.0d)); + expected.add(new Tuple("b", 2.0d)); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScoreWithScores("foo", 3.5d, Double.NEGATIVE_INFINITY, 1, 1); + expected = new ArrayList(); + expected.add(new Tuple("b", 2.0d)); + + assertEquals(expected, range); + + range = jedis.zrevrangeByScoreWithScores("foo", 4d, 2d); + expected = new ArrayList(); + expected.add(new Tuple("d", 4.0d)); + expected.add(new Tuple("c", 3.0d)); + expected.add(new Tuple("b", 2.0d)); + + assertEquals(expected, range); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + List brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(ba, 2d)); + bexpected.add(new Tuple(bc, 0.1d)); + + assertEquals(bexpected, brange); + + brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 0, 1); + + bexpected = new ArrayList(); + bexpected.add(new Tuple(ba, 2d)); + + assertEquals(bexpected, brange); + + brange = jedis.zrevrangeByScoreWithScores(bfoo, 2d, 0d, 1, 1); + + bexpected = new ArrayList(); + bexpected.add(new Tuple(bc, 0.1d)); + + assertEquals(bexpected, brange); + } + + @Test + public void zremrangeByRank() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + assertEquals(1, jedis.zremrangeByRank("foo", 0, 0)); + + List expected = new ArrayList(); + expected.add("a"); + expected.add("b"); + + assertEquals(expected, jedis.zrange("foo", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + assertEquals(1, jedis.zremrangeByRank(bfoo, 0, 0)); + + List bexpected = new ArrayList(); + bexpected.add(ba); + bexpected.add(bb); + + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + + } + + @Test + public void zremrangeByScore() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 10d, "b"); + jedis.zadd("foo", 0.1d, "c"); + jedis.zadd("foo", 2d, "a"); + + assertEquals(2, jedis.zremrangeByScore("foo", 0, 2)); + + List expected = new ArrayList(); + expected.add("b"); + + assertEquals(expected, jedis.zrange("foo", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bfoo, 0.1d, bc); + jedis.zadd(bfoo, 2d, ba); + + assertEquals(2, jedis.zremrangeByScore(bfoo, 0, 2)); + + List bexpected = new ArrayList(); + bexpected.add(bb); + + assertByteArrayListEquals(bexpected, jedis.zrange(bfoo, 0, 100)); + } + + @Test + public void zremrangeByScoreExclusive() { + jedis.zadd("foo", 1d, "a"); + jedis.zadd("foo", 0d, "c"); + jedis.zadd("foo", 2d, "b"); + + assertEquals(1, jedis.zremrangeByScore("foo", "(0", "(2")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 0d, bc); + jedis.zadd(bfoo, 2d, bb); + + assertEquals(1, jedis.zremrangeByScore(bfoo, "(0".getBytes(), "(2".getBytes())); + } + + @Test + public void zremrangeByLex() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 1, "b"); + jedis.zadd("foo", 1, "c"); + jedis.zadd("foo", 1, "aa"); + + assertEquals(2, jedis.zremrangeByLex("foo", "[aa", "(c")); + + List expected = new ArrayList(); + expected.add("a"); + expected.add("c"); + + assertEquals(expected, jedis.zrangeByLex("foo", "-", "+")); + } + + @Test + public void zremrangeByLexBinary() { + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 1, bc); + jedis.zadd(bfoo, 1, bb); + + assertEquals(1, jedis.zremrangeByLex(bfoo, bInclusiveB, bExclusiveC)); + + List bexpected = new ArrayList(); + bexpected.add(ba); + bexpected.add(bc); + + assertByteArrayListEquals(bexpected, jedis.zrangeByLex(bfoo, bLexMinusInf, bLexPlusInf)); + } + + @Test + public void zunion() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + jedis.zadd("bar", 2, "b"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + Set expected = new LinkedHashSet<>(); + expected.add("a"); + expected.add("b"); + assertEquals(expected, jedis.zunion(params, "foo", "bar")); + + Set expectedTuple = new LinkedHashSet<>(); + expectedTuple.add(new Tuple("b", new Double(9))); + expectedTuple.add(new Tuple("a", new Double(7))); + assertEquals(expectedTuple, jedis.zunionWithScores(params, "foo", "bar")); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); + + ZParams bparams = new ZParams(); + bparams.weights(2, 2.5); + bparams.aggregate(ZParams.Aggregate.SUM); + Set bexpected = new LinkedHashSet<>(); + bexpected.add(bb); + bexpected.add(ba); + assertByteArraySetEquals(bexpected, jedis.zunion(params, bfoo, bbar)); + + Set bexpectedTuple = new LinkedHashSet<>(); + bexpectedTuple.add(new Tuple(bb, new Double(9))); + bexpectedTuple.add(new Tuple(ba, new Double(7))); + assertEquals(bexpectedTuple, jedis.zunionWithScores(bparams, bfoo, bbar)); + } + + @Test + public void zunionstore() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + jedis.zadd("bar", 2, "b"); + + assertEquals(2, jedis.zunionstore("dst", "foo", "bar")); + + List expected = new ArrayList(); + expected.add(new Tuple("a", new Double(3))); + expected.add(new Tuple("b", new Double(4))); + assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); + + assertEquals(2, jedis.zunionstore(SafeEncoder.encode("dst"), bfoo, bbar)); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(ba, new Double(3))); + bexpected.add(new Tuple(bb, new Double(4))); + assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); + } + + @Test + public void zunionstoreParams() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + jedis.zadd("bar", 2, "b"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + + assertEquals(2, jedis.zunionstore("dst", params, "foo", "bar")); + + List expected = new ArrayList(); + expected.add(new Tuple("a", new Double(7))); + expected.add(new Tuple("b", new Double(9))); + assertEquals(expected, jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + jedis.zadd(bbar, 2, bb); + + ZParams bparams = new ZParams(); + bparams.weights(2, 2.5); + bparams.aggregate(ZParams.Aggregate.SUM); + + assertEquals(2, jedis.zunionstore(SafeEncoder.encode("dst"), bparams, bfoo, bbar)); + + List bexpected = new ArrayList(); + bexpected.add(new Tuple(ba, new Double(7))); + bexpected.add(new Tuple(bb, new Double(9))); + assertEquals(bexpected, jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); + } + + @Test + public void zinter() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + assertEquals(Collections.singleton("a"), jedis.zinter(params, "foo", "bar")); + + assertEquals(Collections.singleton(new Tuple("a", new Double(7))), + jedis.zinterWithScores(params, "foo", "bar")); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + + ZParams bparams = new ZParams(); + bparams.weights(2, 2.5); + bparams.aggregate(ZParams.Aggregate.SUM); + assertByteArraySetEquals(Collections.singleton(ba), jedis.zinter(params, bfoo, bbar)); + + assertEquals(Collections.singleton(new Tuple(ba, new Double(7))), + jedis.zinterWithScores(bparams, bfoo, bbar)); + } + + @Test + public void zinterstore() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + + assertEquals(1, jedis.zinterstore("dst", "foo", "bar")); + + assertEquals(Collections.singletonList(new Tuple("a", new Double(3))), + jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + + assertEquals(1, jedis.zinterstore(SafeEncoder.encode("dst"), bfoo, bbar)); + + assertEquals(Collections.singletonList(new Tuple(ba, new Double(3))), + jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); + } + + @Test + public void zintertoreParams() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + jedis.zadd("bar", 2, "a"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + + assertEquals(1, jedis.zinterstore("dst", params, "foo", "bar")); + + assertEquals(Collections.singletonList(new Tuple("a", new Double(7))), + jedis.zrangeWithScores("dst", 0, 100)); + + // Binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 2, bb); + jedis.zadd(bbar, 2, ba); + + ZParams bparams = new ZParams(); + bparams.weights(2, 2.5); + bparams.aggregate(ZParams.Aggregate.SUM); + + assertEquals(1, jedis.zinterstore(SafeEncoder.encode("dst"), bparams, bfoo, bbar)); + + assertEquals(Collections.singletonList(new Tuple(ba, new Double(7))), + jedis.zrangeWithScores(SafeEncoder.encode("dst"), 0, 100)); + } + + @Test + public void zscan() { + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 2, "b"); + + ScanResult result = jedis.zscan("foo", SCAN_POINTER_START); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + jedis.zadd(bfoo, 1, ba); + jedis.zadd(bfoo, 1, bb); + + ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void zscanMatch() { + ScanParams params = new ScanParams(); + params.match("a*"); + + jedis.zadd("foo", 2, "b"); + jedis.zadd("foo", 1, "a"); + jedis.zadd("foo", 11, "aa"); + ScanResult result = jedis.zscan("foo", SCAN_POINTER_START, params); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.match(bbarstar); + + jedis.zadd(bfoo, 2, bbar1); + jedis.zadd(bfoo, 1, bbar2); + jedis.zadd(bfoo, 11, bbar3); + ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertArrayEquals(SCAN_POINTER_START_BINARY, bResult.getCursorAsBytes()); + assertFalse(bResult.getResult().isEmpty()); + + } + + @Test + public void zscanCount() { + ScanParams params = new ScanParams(); + params.count(2); + + jedis.zadd("foo", 1, "a1"); + jedis.zadd("foo", 2, "a2"); + jedis.zadd("foo", 3, "a3"); + jedis.zadd("foo", 4, "a4"); + jedis.zadd("foo", 5, "a5"); + + ScanResult result = jedis.zscan("foo", SCAN_POINTER_START, params); + + assertFalse(result.getResult().isEmpty()); + + // binary + params = new ScanParams(); + params.count(2); + + jedis.zadd(bfoo, 2, bbar1); + jedis.zadd(bfoo, 1, bbar2); + jedis.zadd(bfoo, 11, bbar3); + + ScanResult bResult = jedis.zscan(bfoo, SCAN_POINTER_START_BINARY, params); + + assertFalse(bResult.getResult().isEmpty()); + } + + @Test + public void infinity() { + jedis.zadd("key", Double.POSITIVE_INFINITY, "pos"); + assertEquals(Double.POSITIVE_INFINITY, jedis.zscore("key", "pos"), 0d); + jedis.zadd("key", Double.NEGATIVE_INFINITY, "neg"); + assertEquals(Double.NEGATIVE_INFINITY, jedis.zscore("key", "neg"), 0d); + jedis.zadd("key", 0d, "zero"); + + List set = jedis.zrangeWithScores("key", 0, -1); + Iterator itr = set.iterator(); + assertEquals(Double.NEGATIVE_INFINITY, itr.next().getScore(), 0d); + assertEquals(0d, itr.next().getScore(), 0d); + assertEquals(Double.POSITIVE_INFINITY, itr.next().getScore(), 0d); + } + + @Test + public void bzpopmax() { + jedis.zadd("foo", 1d, "a", ZAddParams.zAddParams().nx()); + jedis.zadd("foo", 10d, "b", ZAddParams.zAddParams().nx()); + jedis.zadd("bar", 0.1d, "c", ZAddParams.zAddParams().nx()); + assertEquals(new KeyedZSetElement("foo", "b", 10d), jedis.bzpopmax(0, "foo", "bar")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bbar, 0.1d, bc); + List actual = jedis.bzpopmax(0, bfoo, bbar); + assertEquals(3, actual.size()); + assertArrayEquals(bfoo, actual.get(0)); + assertArrayEquals(bb, actual.get(1)); + assertEquals(10d, BuilderFactory.DOUBLE.build(actual.get(2)), 1e-10); + } + + @Test + public void bzpopmin() { + jedis.zadd("foo", 1d, "a", ZAddParams.zAddParams().nx()); + jedis.zadd("foo", 10d, "b", ZAddParams.zAddParams().nx()); + jedis.zadd("bar", 0.1d, "c", ZAddParams.zAddParams().nx()); + assertEquals(new KeyedZSetElement("bar", "c", 0.1d), jedis.bzpopmin(0, "bar", "foo")); + + // Binary + jedis.zadd(bfoo, 1d, ba); + jedis.zadd(bfoo, 10d, bb); + jedis.zadd(bbar, 0.1d, bc); + List actual = jedis.bzpopmin(0, bbar, bfoo); + assertEquals(3, actual.size()); + assertArrayEquals(bbar, actual.get(0)); + assertArrayEquals(bc, actual.get(1)); + assertEquals(0.1d, BuilderFactory.DOUBLE.build(actual.get(2)), 1e-10); + } + + @Test + public void zdiff() { + jedis.zadd("foo", 1.0, "a"); + jedis.zadd("foo", 2.0, "b"); + jedis.zadd("bar", 1.0, "a"); + + assertEquals(0, jedis.zdiff("bar1", "bar2").size()); + assertEquals(Collections.singleton("b"), jedis.zdiff("foo", "bar")); + assertEquals(Collections.singleton(new Tuple("b", 2.0d)), jedis.zdiffWithScores("foo", "bar")); + + // binary + + jedis.zadd(bfoo, 1.0, ba); + jedis.zadd(bfoo, 2.0, bb); + jedis.zadd(bbar, 1.0, ba); + + assertEquals(0, jedis.zdiff(bbar1, bbar2).size()); + Set bactual = jedis.zdiff(bfoo, bbar); + assertEquals(1, bactual.size()); + assertArrayEquals(bb, bactual.iterator().next()); + assertEquals(Collections.singleton(new Tuple(bb, 2.0d)), jedis.zdiffWithScores(bfoo, bbar)); + } + + @Test + public void zdiffStore() { + jedis.zadd("foo", 1.0, "a"); + jedis.zadd("foo", 2.0, "b"); + jedis.zadd("bar", 1.0, "a"); + + assertEquals(0, jedis.zdiffStore("bar3", "bar1", "bar2")); + assertEquals(1, jedis.zdiffStore("bar3", "foo", "bar")); + assertEquals(Collections.singletonList("b"), jedis.zrange("bar3", 0, -1)); + + // binary + + jedis.zadd(bfoo, 1.0, ba); + jedis.zadd(bfoo, 2.0, bb); + jedis.zadd(bbar, 1.0, ba); + + assertEquals(0, jedis.zdiffStore(bbar3, bbar1, bbar2)); + assertEquals(1, jedis.zdiffStore(bbar3, bfoo, bbar)); + List bactual = jedis.zrange(bbar3, 0, -1); + assertArrayEquals(bb, bactual.iterator().next()); + } + + @Test + public void zrandmember() { + assertNull(jedis.zrandmember("foo")); + assertEquals(Collections.emptyList(), jedis.zrandmember("foo", 1)); + assertEquals(Collections.emptyList(), jedis.zrandmemberWithScores("foo", 1)); + + Map hash = new HashMap<>(); + hash.put("bar1", 1d); + hash.put("bar2", 10d); + hash.put("bar3", 0.1d); + jedis.zadd("foo", hash); + + assertTrue(hash.containsKey(jedis.zrandmember("foo"))); + assertEquals(2, jedis.zrandmember("foo", 2).size()); + + List actual = jedis.zrandmemberWithScores("foo", 2); + assertNotNull(actual); + assertEquals(2, actual.size()); + Tuple tuple = actual.iterator().next(); + assertEquals(hash.get(tuple.getElement()), Double.valueOf(tuple.getScore())); + + // Binary + assertNull(jedis.zrandmember(bfoo)); + assertEquals(Collections.emptyList(), jedis.zrandmember(bfoo, 1)); + assertEquals(Collections.emptyList(), jedis.zrandmemberWithScores(bfoo, 1)); + + Map bhash = new HashMap<>(); + bhash.put(bbar1, 1d); + bhash.put(bbar2, 10d); + bhash.put(bbar3, 0.1d); + jedis.zadd(bfoo, bhash); + + assertCollectionContains(bhash.keySet(), jedis.zrandmember(bfoo)); + assertEquals(2, jedis.zrandmember(bfoo, 2).size()); + + List bactual = jedis.zrandmemberWithScores(bfoo, 2); + assertNotNull(bactual); + assertEquals(2, bactual.size()); + tuple = bactual.iterator().next(); + assertEquals(getScoreFromByteMap(bhash, tuple.getBinaryElement()), Double.valueOf(tuple.getScore())); + } + + private Double getScoreFromByteMap(Map bhash, byte[] key) { + for (Map.Entry en : bhash.entrySet()) { + if (Arrays.equals(en.getKey(), key)) { + return en.getValue(); + } + } + return null; + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/StringValuesCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/StringValuesCommandsTestBase.java new file mode 100644 index 0000000000..fc5846dbb5 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/StringValuesCommandsTestBase.java @@ -0,0 +1,318 @@ +package redis.clients.jedis.commands.unified; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.assertNull; +import static org.junit.Assume.assumeFalse; +import static redis.clients.jedis.util.RedisVersionUtil.checkRedisMajorVersionNumber; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Test; + +import redis.clients.jedis.resps.LCSMatchResult; +import redis.clients.jedis.resps.LCSMatchResult.MatchedPosition; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.params.GetExParams; +import redis.clients.jedis.params.StrAlgoLCSParams; + +public abstract class StringValuesCommandsTestBase extends UnifiedJedisCommandsTestBase { + @Test + public void setAndGet() { + String status = jedis.set("foo", "bar"); + assertEquals("OK", status); + + String value = jedis.get("foo"); + assertEquals("bar", value); + + assertNull(jedis.get("bar")); + } + + @Test + public void getSet() { + String value = jedis.getSet("foo", "bar"); + assertNull(value); + value = jedis.get("foo"); + assertEquals("bar", value); + } + + @Test + public void getDel() { + String status = jedis.set("foo", "bar"); + assertEquals("OK", status); + + String value = jedis.getDel("foo"); + assertEquals("bar", value); + + assertNull(jedis.get("foo")); + } + + @Test + public void getEx() { + assertNull(jedis.getEx("foo", GetExParams.getExParams().ex(1))); + jedis.set("foo", "bar"); + + assertEquals("bar", jedis.getEx("foo", GetExParams.getExParams().ex(10))); + long ttl = jedis.ttl("foo"); + assertTrue(ttl > 0 && ttl <= 10); + + assertEquals("bar", jedis.getEx("foo", GetExParams.getExParams().px(20000l))); + ttl = jedis.ttl("foo"); + assertTrue(ttl > 10 && ttl <= 20); + + assertEquals("bar", jedis.getEx("foo", GetExParams.getExParams().exAt(System.currentTimeMillis() / 1000 + 30))); + ttl = jedis.ttl("foo"); + assertTrue(ttl > 20 && ttl <= 30); + + assertEquals("bar", jedis.getEx("foo", GetExParams.getExParams().pxAt(System.currentTimeMillis() + 40000l))); + ttl = jedis.ttl("foo"); + assertTrue(ttl > 30 && ttl <= 40); + + assertEquals("bar", jedis.getEx("foo", GetExParams.getExParams().persist())); + assertEquals(-1, jedis.ttl("foo")); + } + + @Test + public void mget() { + List values = jedis.mget("foo", "bar"); + List expected = new ArrayList(); + expected.add(null); + expected.add(null); + + assertEquals(expected, values); + + jedis.set("foo", "bar"); + + expected = new ArrayList(); + expected.add("bar"); + expected.add(null); + values = jedis.mget("foo", "bar"); + + assertEquals(expected, values); + + jedis.set("bar", "foo"); + + expected = new ArrayList(); + expected.add("bar"); + expected.add("foo"); + values = jedis.mget("foo", "bar"); + + assertEquals(expected, values); + } + + @Test + public void setnx() { + assertEquals(1, jedis.setnx("foo", "bar")); + assertEquals("bar", jedis.get("foo")); + + assertEquals(0, jedis.setnx("foo", "bar2")); + assertEquals("bar", jedis.get("foo")); + } + + @Test + public void setex() { + String status = jedis.setex("foo", 20, "bar"); + assertEquals("OK", status); + long ttl = jedis.ttl("foo"); + assertTrue(ttl > 0 && ttl <= 20); + } + + @Test + public void mset() { + String status = jedis.mset("foo", "bar", "bar", "foo"); + assertEquals("OK", status); + assertEquals("bar", jedis.get("foo")); + assertEquals("foo", jedis.get("bar")); + } + + @Test + public void msetnx() { + assertEquals(1, jedis.msetnx("foo", "bar", "bar", "foo")); + assertEquals("bar", jedis.get("foo")); + assertEquals("foo", jedis.get("bar")); + + assertEquals(0, jedis.msetnx("foo", "bar1", "bar2", "foo2")); + assertEquals("bar", jedis.get("foo")); + assertEquals("foo", jedis.get("bar")); + } + + @Test + public void incr() { + assertEquals(1, jedis.incr("foo")); + assertEquals(2, jedis.incr("foo")); + } + + @Test(expected = JedisDataException.class) + public void incrWrongValue() { + jedis.set("foo", "bar"); + jedis.incr("foo"); + } + + @Test + public void incrBy() { + assertEquals(2, jedis.incrBy("foo", 2)); + assertEquals(5, jedis.incrBy("foo", 3)); + } + + @Test(expected = JedisDataException.class) + public void incrByWrongValue() { + jedis.set("foo", "bar"); + jedis.incrBy("foo", 2); + } + + @Test + public void incrByFloat() { + assertEquals(10.5, jedis.incrByFloat("foo", 10.5), 0.0); + assertEquals(10.6, jedis.incrByFloat("foo", 0.1), 0.0); + } + + @Test(expected = JedisDataException.class) + public void incrByFloatWrongValue() { + jedis.set("foo", "bar"); + jedis.incrByFloat("foo", 2d); + } + + @Test(expected = JedisDataException.class) + public void decrWrongValue() { + jedis.set("foo", "bar"); + jedis.decr("foo"); + } + + @Test + public void decr() { + assertEquals(-1, jedis.decr("foo")); + assertEquals(-2, jedis.decr("foo")); + } + + @Test + public void decrBy() { + assertEquals(-2, jedis.decrBy("foo", 2)); + assertEquals(-4, jedis.decrBy("foo", 2)); + } + + @Test(expected = JedisDataException.class) + public void decrByWrongValue() { + jedis.set("foo", "bar"); + jedis.decrBy("foo", 2); + } + + @Test + public void append() { + assertEquals(3, jedis.append("foo", "bar")); + assertEquals("bar", jedis.get("foo")); + assertEquals(6, jedis.append("foo", "bar")); + assertEquals("barbar", jedis.get("foo")); + } + + @Test + public void substr() { + jedis.set("s", "This is a string"); + assertEquals("This", jedis.substr("s", 0, 3)); + assertEquals("ing", jedis.substr("s", -3, -1)); + assertEquals("This is a string", jedis.substr("s", 0, -1)); + assertEquals(" string", jedis.substr("s", 9, 100000)); + } + + @Test + public void strlen() { + String str = "This is a string"; + jedis.set("s", str); + assertEquals(str.length(), jedis.strlen("s")); + } + + @Test + public void incrLargeNumbers() { + assertEquals(1, jedis.incr("foo")); + assertEquals(1L + Integer.MAX_VALUE, jedis.incrBy("foo", Integer.MAX_VALUE)); + } + + @Test(expected = JedisDataException.class) + public void incrReallyLargeNumbers() { + jedis.set("foo", Long.toString(Long.MAX_VALUE)); + jedis.incr("foo"); // Should throw an exception + } + + @Test + public void psetex() { + String status = jedis.psetex("foo", 20000, "bar"); + assertEquals("OK", status); + long ttl = jedis.ttl("foo"); + assertTrue(ttl > 0 && ttl <= 20000); + } + + @Test + public void strAlgoLcsWithLen() { + assumeFalse(checkRedisMajorVersionNumber(7)); + LCSMatchResult stringMatchResult = jedis.strAlgoLCSStrings("ohmytext", "mynewtext", + StrAlgoLCSParams.StrAlgoLCSParams().len()); + assertEquals(stringMatchResult.getLen(), 6); + } + + @Test + public void strAlgoLcs() { + assumeFalse(checkRedisMajorVersionNumber(7)); + LCSMatchResult stringMatchResult = jedis.strAlgoLCSStrings("ohmytext", "mynewtext", + StrAlgoLCSParams.StrAlgoLCSParams()); + assertEquals(stringMatchResult.getMatchString(), "mytext"); + } + + @Test + public void strAlgoLcsWithIdx() { + assumeFalse(checkRedisMajorVersionNumber(7)); + LCSMatchResult stringMatchResult = jedis.strAlgoLCSStrings("ohmytext", "mynewtext", + StrAlgoLCSParams.StrAlgoLCSParams().idx().withMatchLen()); + assertEquals(stringMatchResult.getLen(), 6); + assertEquals(2, stringMatchResult.getMatches().size()); + + MatchedPosition position0 = stringMatchResult.getMatches().get(0); + assertEquals(position0.getA().getStart(), 4); + assertEquals(position0.getA().getEnd(), 7); + assertEquals(position0.getB().getStart(), 5); + assertEquals(position0.getB().getEnd(), 8); + assertEquals(position0.getMatchLen(), 4); + + MatchedPosition position1 = stringMatchResult.getMatches().get(1); + assertEquals(position1.getA().getStart(), 2); + assertEquals(position1.getA().getEnd(), 3); + assertEquals(position1.getB().getStart(), 0); + assertEquals(position1.getB().getEnd(), 1); + assertEquals(position1.getMatchLen(), 2); + } + + @Test + public void strAlgoLcsWithKey() { + assumeFalse(checkRedisMajorVersionNumber(7)); + jedis.mset("key1", "ohmytext", "key2", "mynewtext"); + + LCSMatchResult stringMatchResult = jedis.strAlgoLCSKeys("key1", "key2", + StrAlgoLCSParams.StrAlgoLCSParams()); + assertEquals("mytext", stringMatchResult.getMatchString()); + } + + @Test + public void strAlgoLcsWithKeyAndIdx() { + assumeFalse(checkRedisMajorVersionNumber(7)); + jedis.mset("key1", "ohmytext", "key2", "mynewtext"); + + LCSMatchResult stringMatchResult = jedis.strAlgoLCSKeys( "key1", "key2", + StrAlgoLCSParams.StrAlgoLCSParams().idx().withMatchLen()); + assertEquals(stringMatchResult.getLen(), 6); + assertEquals(2, stringMatchResult.getMatches().size()); + + MatchedPosition position0 = stringMatchResult.getMatches().get(0); + assertEquals(position0.getA().getStart(), 4); + assertEquals(position0.getA().getEnd(), 7); + assertEquals(position0.getB().getStart(), 5); + assertEquals(position0.getB().getEnd(), 8); + assertEquals(position0.getMatchLen(), 4); + + MatchedPosition position1 = stringMatchResult.getMatches().get(1); + assertEquals(position1.getA().getStart(), 2); + assertEquals(position1.getA().getEnd(), 3); + assertEquals(position1.getB().getStart(), 0); + assertEquals(position1.getB().getEnd(), 1); + assertEquals(position1.getMatchLen(), 2); + } + +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/UnifiedJedisCommandsTestBase.java b/src/test/java/redis/clients/jedis/commands/unified/UnifiedJedisCommandsTestBase.java new file mode 100644 index 0000000000..cbd046231d --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/UnifiedJedisCommandsTestBase.java @@ -0,0 +1,11 @@ +package redis.clients.jedis.commands.unified; + +import redis.clients.jedis.UnifiedJedis; + +public abstract class UnifiedJedisCommandsTestBase { + + protected static UnifiedJedis jedis; + + public UnifiedJedisCommandsTestBase() { + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterAllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterAllKindOfValuesCommandsTest.java new file mode 100644 index 0000000000..c3c0f9f127 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterAllKindOfValuesCommandsTest.java @@ -0,0 +1,266 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertTrue; +import static redis.clients.jedis.params.ScanParams.SCAN_POINTER_START; + +import java.util.Collections; +import java.util.HashSet; +import java.util.Set; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.params.ScanParams; +import redis.clients.jedis.resps.ScanResult; +import redis.clients.jedis.commands.unified.AllKindOfValuesCommandsTestBase; + +public class ClusterAllKindOfValuesCommandsTest extends AllKindOfValuesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void existsMany() { + String status = jedis.set("{foo}1", "bar1"); + assertEquals("OK", status); + + status = jedis.set("{foo}2", "bar2"); + assertEquals("OK", status); + + assertEquals(2L, jedis.exists("{foo}1", "{foo}2")); + + assertEquals(1L, jedis.del("{foo}1")); + + assertEquals(1L, jedis.exists("{foo}1", "{foo}2")); + } + + @Test + @Override + public void del() { + jedis.set("{foo}1", "bar1"); + jedis.set("{foo}2", "bar2"); + jedis.set("{foo}3", "bar3"); + + assertEquals(3L, jedis.del("{foo}1", "{foo}2", "{foo}3")); + + assertFalse(jedis.exists("{foo}1")); + assertFalse(jedis.exists("{foo}2")); + assertFalse(jedis.exists("{foo}3")); + + jedis.set("{foo}1", "bar1"); + + assertEquals(1L, jedis.del("{foo}1", "{foo}2")); + + assertEquals(0L, jedis.del("{foo}1", "{foo}2")); + } + + @Test + @Override + public void unlink() { + jedis.set("{foo}1", "bar1"); + jedis.set("{foo}2", "bar2"); + jedis.set("{foo}3", "bar3"); + + assertEquals(3, jedis.unlink("{foo}1", "{foo}2", "{foo}3")); + + assertEquals(0, jedis.exists("{foo}1", "{foo}2", "{foo}3")); + + jedis.set("{foo}1", "bar1"); + + assertEquals(1, jedis.unlink("{foo}1", "{foo}2")); + + assertEquals(0, jedis.unlink("{foo}1", "{foo}2")); + + jedis.set("{foo}", "bar"); + assertEquals(1, jedis.unlink("{foo}")); + assertFalse(jedis.exists("{foo}")); + } + + @Test + @Override + public void keys() { + jedis.set("{foo}", "bar"); + jedis.set("{foo}bar", "bar"); + + Set keys = jedis.keys("{foo}*"); + Set expected = new HashSet<>(); + expected.add("{foo}"); + expected.add("{foo}bar"); + assertEquals(expected, keys); + + expected.clear(); + keys = jedis.keys("{bar}*"); + + assertEquals(expected, keys); + } + + @Test + @Override + public void rename() { + jedis.set("foo{#}", "bar"); + String status = jedis.rename("foo{#}", "bar{#}"); + assertEquals("OK", status); + + assertNull(jedis.get("foo{#}")); + + assertEquals("bar", jedis.get("bar{#}")); + } + + @Test + @Override + public void renamenx() { + jedis.set("foo{&}", "bar"); + assertEquals(1, jedis.renamenx("foo{&}", "bar{&}")); + + jedis.set("foo{&}", "bar"); + assertEquals(0, jedis.renamenx("foo{&}", "bar{&}")); + } + + @Test(expected = UnsupportedOperationException.class) + @Override + public void dbSize() { + super.dbSize(); + } + + @Test + @Override + public void touch() throws Exception { + assertEquals(0, jedis.touch("{foo}1", "{foo}2", "{foo}3")); + + jedis.set("{foo}1", "bar1"); + + Thread.sleep(1100); // little over 1 sec + assertTrue(jedis.objectIdletime("{foo}1") > 0); + + assertEquals(1, jedis.touch("{foo}1")); + assertEquals(0L, jedis.objectIdletime("{foo}1").longValue()); + + assertEquals(1, jedis.touch("{foo}1", "{foo}2", "{foo}3")); + + jedis.set("{foo}2", "bar2"); + + jedis.set("{foo}3", "bar3"); + + assertEquals(3, jedis.touch("{foo}1", "{foo}2", "{foo}3")); + } + + @Test + @Override + public void scan() { + jedis.set("{%}b", "b"); + jedis.set("a{%}", "a"); + + ScanResult result = jedis.scan(SCAN_POINTER_START, new ScanParams().match("*{%}*")); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + @Override + public void scanMatch() { + ScanParams params = new ScanParams(); + params.match("a{-}*"); + + jedis.set("b{-}", "b"); + jedis.set("a{-}", "a"); + jedis.set("a{-}a", "aa"); + ScanResult result = jedis.scan(SCAN_POINTER_START, params); + + assertEquals(SCAN_POINTER_START, result.getCursor()); + assertFalse(result.getResult().isEmpty()); + } + + @Test + @Override + public void scanCount() { + ScanParams params = new ScanParams(); + params.match("{a}*"); + params.count(2); + + for (int i = 0; i < 10; i++) { + jedis.set("{a}" + i, "a" + i); + } + + ScanResult result = jedis.scan(SCAN_POINTER_START, params); + assertTrue(result.getResult().size() >= 2); + } + + @Test + @Override + public void scanType() { + ScanParams noCount = new ScanParams().match("*{+}*"); + ScanParams pagingParams = new ScanParams().match("*{+}*").count(4); + + jedis.set("{+}a", "a"); + jedis.hset("{+}b", "b", "b"); + jedis.set("c{+}", "c"); + jedis.sadd("d{+}", "d"); + jedis.set("e{+}", "e"); + jedis.zadd("{+}f", 0d, "f"); + jedis.set("{+}g", "g"); + + // string + ScanResult scanResult; + + scanResult = jedis.scan(SCAN_POINTER_START, pagingParams, "string"); + assertFalse(scanResult.isCompleteIteration()); + int page1Count = scanResult.getResult().size(); + scanResult = jedis.scan(scanResult.getCursor(), pagingParams, "string"); + assertTrue(scanResult.isCompleteIteration()); + int page2Count = scanResult.getResult().size(); + assertEquals(4, page1Count + page2Count); + + + scanResult = jedis.scan(SCAN_POINTER_START, noCount, "hash"); + assertEquals(Collections.singletonList("{+}b"), scanResult.getResult()); + scanResult = jedis.scan(SCAN_POINTER_START, noCount, "set"); + assertEquals(Collections.singletonList("d{+}"), scanResult.getResult()); + scanResult = jedis.scan(SCAN_POINTER_START, noCount, "zset"); + assertEquals(Collections.singletonList("{+}f"), scanResult.getResult()); + } + + @Test(expected = IllegalArgumentException.class) + @Override + public void scanIsCompleteIteration() { + super.scanIsCompleteIteration(); + } + + @Test + @Override + public void copy() { + assertFalse(jedis.copy("unkn{o}wn", "f{o}o", false)); + + jedis.set("{foo}1", "bar"); + assertTrue(jedis.copy("{foo}1", "{foo}2", false)); + assertEquals("bar", jedis.get("{foo}2")); + + // replace + jedis.set("{foo}1", "bar1"); + assertTrue(jedis.copy("{foo}1", "{foo}2", true)); + assertEquals("bar1", jedis.get("{foo}2")); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBinaryValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBinaryValuesCommandsTest.java new file mode 100644 index 0000000000..d648d1098f --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBinaryValuesCommandsTest.java @@ -0,0 +1,45 @@ +package redis.clients.jedis.commands.unified.cluster; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import redis.clients.jedis.commands.unified.BinaryValuesCommandsTestBase; + +public class ClusterBinaryValuesCommandsTest extends BinaryValuesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Ignore + @Override + public void mget() { + } + + @Ignore + @Override + public void mset() { + } + + @Ignore + @Override + public void msetnx() { + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBitCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBitCommandsTest.java new file mode 100644 index 0000000000..9541974f98 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterBitCommandsTest.java @@ -0,0 +1,78 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import redis.clients.jedis.args.BitOP; +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.commands.unified.BitCommandsTestBase; + +public class ClusterBitCommandsTest extends BitCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void bitOp() { + jedis.set("{key}1", "\u0060"); + jedis.set("{key}2", "\u0044"); + + jedis.bitop(BitOP.AND, "resultAnd{key}", "{key}1", "{key}2"); + String resultAnd = jedis.get("resultAnd{key}"); + assertEquals("\u0040", resultAnd); + + jedis.bitop(BitOP.OR, "resultOr{key}", "{key}1", "{key}2"); + String resultOr = jedis.get("resultOr{key}"); + assertEquals("\u0064", resultOr); + + jedis.bitop(BitOP.XOR, "resultXor{key}", "{key}1", "{key}2"); + String resultXor = jedis.get("resultXor{key}"); + assertEquals("\u0024", resultXor); + } + + @Test + @Override + public void bitOpNot() { + jedis.setbit("key", 0, true); + jedis.setbit("key", 4, true); + + jedis.bitop(BitOP.NOT, "resultNot{key}", "key"); + String resultNot = jedis.get("resultNot{key}"); + assertEquals("\u0077", resultNot); + } + + @Ignore + @Override + public void bitOpBinary() { + } + + @Test(expected = JedisDataException.class) + @Override + public void bitOpNotMultiSourceShouldFail() { + jedis.bitop(BitOP.NOT, "{!}dest", "{!}src1", "{!}src2"); + } + +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterCommandsTestHelper.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterCommandsTestHelper.java new file mode 100644 index 0000000000..497b99cdb8 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterCommandsTestHelper.java @@ -0,0 +1,82 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static redis.clients.jedis.Protocol.CLUSTER_HASHSLOTS; + +import java.util.Collections; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisCluster; +import redis.clients.jedis.args.ClusterResetType; +import redis.clients.jedis.HostAndPorts; +import redis.clients.jedis.util.JedisClusterTestUtil; + +public class ClusterCommandsTestHelper { + + private static final HostAndPort nodeInfo1 = HostAndPorts.getClusterServers().get(0); + private static final HostAndPort nodeInfo2 = HostAndPorts.getClusterServers().get(1); + private static final HostAndPort nodeInfo3 = HostAndPorts.getClusterServers().get(2); + + private static Jedis node1; + private static Jedis node2; + private static Jedis node3; + + static JedisCluster initAndGetCluster() throws InterruptedException { + + node1 = new Jedis(nodeInfo1); + node1.auth("cluster"); + node1.flushAll(); + + node2 = new Jedis(nodeInfo2); + node2.auth("cluster"); + node2.flushAll(); + + node3 = new Jedis(nodeInfo3); + node3.auth("cluster"); + node3.flushAll(); + + // ---- configure cluster + // add nodes to cluster + node1.clusterMeet("127.0.0.1", nodeInfo2.getPort()); + node1.clusterMeet("127.0.0.1", nodeInfo3.getPort()); + + // split available slots across the three nodes + int slotsPerNode = CLUSTER_HASHSLOTS / 3; + int[] node1Slots = new int[slotsPerNode]; + int[] node2Slots = new int[slotsPerNode + 1]; + int[] node3Slots = new int[slotsPerNode]; + for (int i = 0, slot1 = 0, slot2 = 0, slot3 = 0; i < CLUSTER_HASHSLOTS; i++) { + if (i < slotsPerNode) { + node1Slots[slot1++] = i; + } else if (i > slotsPerNode * 2) { + node3Slots[slot3++] = i; + } else { + node2Slots[slot2++] = i; + } + } + + node1.clusterAddSlots(node1Slots); + node2.clusterAddSlots(node2Slots); + node3.clusterAddSlots(node3Slots); + + JedisClusterTestUtil.waitForClusterReady(node1, node2, node2); + + return new JedisCluster(Collections.singleton( + new HostAndPort("127.0.0.1", nodeInfo1.getPort())), null, "cluster"); + } + + static void tearClusterDown() { + node1.flushDB(); + node2.flushDB(); + node3.flushDB(); + node1.clusterReset(ClusterResetType.SOFT); + node2.clusterReset(ClusterResetType.SOFT); + node3.clusterReset(ClusterResetType.SOFT); + } + + static void clearClusterData() { + node1.flushDB(); + node2.flushDB(); + node3.flushDB(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterGeoCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterGeoCommandsTest.java new file mode 100644 index 0000000000..3a2a4a5d91 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterGeoCommandsTest.java @@ -0,0 +1,89 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import redis.clients.jedis.GeoCoordinate; +import redis.clients.jedis.args.GeoUnit; +import redis.clients.jedis.params.GeoRadiusParam; +import redis.clients.jedis.params.GeoRadiusStoreParam; +import redis.clients.jedis.commands.unified.GeoCommandsTestBase; + +public class ClusterGeoCommandsTest extends GeoCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void georadiusStore() { + // prepare datas + Map coordinateMap = new HashMap<>(); + coordinateMap.put("Palermo", new GeoCoordinate(13.361389, 38.115556)); + coordinateMap.put("Catania", new GeoCoordinate(15.087269, 37.502669)); + jedis.geoadd("Sicily {ITA}", coordinateMap); + + long size = jedis.georadiusStore("Sicily {ITA}", 15, 37, 200, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("{ITA} SicilyStore")); + assertEquals(2, size); + List expected = new ArrayList<>(); + expected.add("Palermo"); + expected.add("Catania"); + assertEquals(expected, jedis.zrange("{ITA} SicilyStore", 0, -1)); + } + + @Ignore + @Override + public void georadiusStoreBinary() { + } + + @Test + @Override + public void georadiusByMemberStore() { + jedis.geoadd("Sicily {ITA}", 13.583333, 37.316667, "Agrigento"); + jedis.geoadd("Sicily {ITA}", 13.361389, 38.115556, "Palermo"); + jedis.geoadd("Sicily {ITA}", 15.087269, 37.502669, "Catania"); + + long size = jedis.georadiusByMemberStore("Sicily {ITA}", "Agrigento", 100, GeoUnit.KM, + GeoRadiusParam.geoRadiusParam(), + GeoRadiusStoreParam.geoRadiusStoreParam().store("{ITA} SicilyStore")); + assertEquals(2, size); + List expected = new ArrayList<>(); + expected.add("Agrigento"); + expected.add("Palermo"); + assertEquals(expected, jedis.zrange("{ITA} SicilyStore", 0, -1)); + } + + @Ignore + @Override + public void georadiusByMemberStoreBinary() { + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHashesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHashesCommandsTest.java new file mode 100644 index 0000000000..ad5d5bd394 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHashesCommandsTest.java @@ -0,0 +1,29 @@ +package redis.clients.jedis.commands.unified.cluster; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.HashesCommandsTestBase; + +public class ClusterHashesCommandsTest extends HashesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHyperLogLogCommandsTest.java new file mode 100644 index 0000000000..5ec491868f --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterHyperLogLogCommandsTest.java @@ -0,0 +1,78 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import redis.clients.jedis.commands.unified.HyperLogLogCommandsTestBase; + +public class ClusterHyperLogLogCommandsTest extends HyperLogLogCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void pfcounts() { + long status = jedis.pfadd("{hll}_1", "foo", "bar", "zap"); + assertEquals(1, status); + status = jedis.pfadd("{hll}_2", "foo", "bar", "zap"); + assertEquals(1, status); + + status = jedis.pfadd("{hll}_3", "foo", "bar", "baz"); + assertEquals(1, status); + status = jedis.pfcount("{hll}_1"); + assertEquals(3, status); + status = jedis.pfcount("{hll}_2"); + assertEquals(3, status); + status = jedis.pfcount("{hll}_3"); + assertEquals(3, status); + + status = jedis.pfcount("{hll}_1", "{hll}_2"); + assertEquals(3, status); + + status = jedis.pfcount("{hll}_1", "{hll}_2", "{hll}_3"); + assertEquals(4, status); + } + + @Test + @Override + public void pfmerge() { + long status = jedis.pfadd("{hll}1", "foo", "bar", "zap", "a"); + assertEquals(1, status); + + status = jedis.pfadd("{hll}2", "a", "b", "c", "foo"); + assertEquals(1, status); + + String mergeStatus = jedis.pfmerge("{hll}3", "{hll}1", "{hll}2"); + assertEquals("OK", mergeStatus); + + status = jedis.pfcount("{hll}3"); + assertEquals(6, status); + } + + @Ignore + @Override + public void pfmergeBinary() { + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterListCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterListCommandsTest.java new file mode 100644 index 0000000000..a14fef81e6 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterListCommandsTest.java @@ -0,0 +1,266 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.logging.log4j.LogManager; +import org.apache.logging.log4j.Logger; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.args.ListDirection; +import redis.clients.jedis.resps.KeyedListElement; +import redis.clients.jedis.commands.unified.ListCommandsTestBase; + +public class ClusterListCommandsTest extends ListCommandsTestBase { + + private static final Logger logger = LogManager.getLogger(); + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void rpoplpush() { + jedis.rpush("foo{|}", "a"); + jedis.rpush("foo{|}", "b"); + jedis.rpush("foo{|}", "c"); + + jedis.rpush("dst{|}", "foo"); + jedis.rpush("dst{|}", "bar"); + + String element = jedis.rpoplpush("foo{|}", "dst{|}"); + + assertEquals("c", element); + + List srcExpected = new ArrayList<>(); + srcExpected.add("a"); + srcExpected.add("b"); + + List dstExpected = new ArrayList<>(); + dstExpected.add("c"); + dstExpected.add("foo"); + dstExpected.add("bar"); + + assertEquals(srcExpected, jedis.lrange("foo{|}", 0, 1000)); + assertEquals(dstExpected, jedis.lrange("dst{|}", 0, 1000)); + } + + @Test + @Override + public void blpop() throws InterruptedException { + List result = jedis.blpop(1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.blpop(1, "foo"); + + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); + + // Multi keys + result = jedis.blpop(1, "{foo}", "{foo}1"); + assertNull(result); + + jedis.lpush("{foo}", "bar"); + jedis.lpush("{foo}1", "bar1"); + result = jedis.blpop(1, "{foo}1", "{foo}"); + + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("{foo}1", result.get(0)); + assertEquals("bar1", result.get(1)); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.blpop(1, bfoo); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + @Override + public void blpopDouble() throws InterruptedException { + KeyedListElement result = jedis.blpop(0.1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.blpop(3.2, "foo"); + + assertNotNull(result); + assertEquals("foo", result.getKey()); + assertEquals("bar", result.getElement()); + + // Multi keys + result = jedis.blpop(0.18, "{foo}", "{foo}1"); + assertNull(result); + + jedis.lpush("{foo}", "bar"); + jedis.lpush("{foo}1", "bar1"); + result = jedis.blpop(1d, "{foo}1", "{foo}"); + + assertNotNull(result); + assertEquals("{foo}1", result.getKey()); + assertEquals("bar1", result.getElement()); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.blpop(3.12, bfoo); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + @Override + public void brpop() throws InterruptedException { + List result = jedis.brpop(1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.brpop(1, "foo"); + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("foo", result.get(0)); + assertEquals("bar", result.get(1)); + + // Multi keys + result = jedis.brpop(1, "{foo}", "{foo}1"); + assertNull(result); + + jedis.lpush("{foo}", "bar"); + jedis.lpush("{foo}1", "bar1"); + result = jedis.brpop(1, "{foo}1", "{foo}"); + + assertNotNull(result); + assertEquals(2, result.size()); + assertEquals("{foo}1", result.get(0)); + assertEquals("bar1", result.get(1)); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.brpop(1, bfoo); + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + @Override + public void brpopDouble() throws InterruptedException { + KeyedListElement result = jedis.brpop(0.1, "foo"); + assertNull(result); + + jedis.lpush("foo", "bar"); + result = jedis.brpop(3.2, "foo"); + + assertNotNull(result); + assertEquals("foo", result.getKey()); + assertEquals("bar", result.getElement()); + + // Multi keys + result = jedis.brpop(0.18, "{foo}", "{foo}1"); + assertNull(result); + + jedis.lpush("{foo}", "bar"); + jedis.lpush("{foo}1", "bar1"); + result = jedis.brpop(1d, "{foo}1", "{foo}"); + + assertNotNull(result); + assertEquals("{foo}1", result.getKey()); + assertEquals("bar1", result.getElement()); + + // Binary + jedis.lpush(bfoo, bbar); + List bresult = jedis.brpop(3.12, bfoo); + + assertNotNull(bresult); + assertEquals(2, bresult.size()); + assertArrayEquals(bfoo, bresult.get(0)); + assertArrayEquals(bbar, bresult.get(1)); + } + + @Test + @Override + public void brpoplpush() { + + new Thread(new Runnable() { + @Override + public void run() { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + jedis.lpush("foo{|}", "a"); + } + }).start(); + + String element = jedis.brpoplpush("foo{|}", "bar{|}", 0); + + assertEquals("a", element); + assertEquals(1, jedis.llen("bar{|}")); + assertEquals("a", jedis.lrange("bar{|}", 0, -1).get(0)); + } + + @Test + @Override + public void lmove() { + jedis.rpush("{|}foo", "bar1", "bar2", "bar3"); + assertEquals("bar3", jedis.lmove("{|}foo", "{|}bar", ListDirection.RIGHT, ListDirection.LEFT)); + assertEquals(Collections.singletonList("bar3"), jedis.lrange("{|}bar", 0, -1)); + assertEquals(Arrays.asList("bar1", "bar2"), jedis.lrange("{|}foo", 0, -1)); + } + + @Test + @Override + public void blmove() { + new Thread(() -> { + try { + Thread.sleep(100); + } catch (InterruptedException e) { + logger.error("", e); + } + jedis.rpush("{|}foo", "bar1", "bar2", "bar3"); + }).start(); + + assertEquals("bar3", jedis.blmove("{|}foo", "{|}bar", ListDirection.RIGHT, ListDirection.LEFT, 0)); + assertEquals(Collections.singletonList("bar3"), jedis.lrange("{|}bar", 0, -1)); + assertEquals(Arrays.asList("bar1", "bar2"), jedis.lrange("{|}foo", 0, -1)); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSetCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSetCommandsTest.java new file mode 100644 index 0000000000..4c7c13111b --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSetCommandsTest.java @@ -0,0 +1,175 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; + +import java.util.HashSet; +import java.util.Set; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import redis.clients.jedis.commands.unified.SetCommandsTestBase; + +public class ClusterSetCommandsTest extends SetCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void smove() { + jedis.sadd("{.}foo", "a"); + jedis.sadd("{.}foo", "b"); + + jedis.sadd("{.}bar", "c"); + + long status = jedis.smove("{.}foo", "{.}bar", "a"); + assertEquals(status, 1); + + Set expectedSrc = new HashSet<>(); + expectedSrc.add("b"); + + Set expectedDst = new HashSet<>(); + expectedDst.add("c"); + expectedDst.add("a"); + + assertEquals(expectedSrc, jedis.smembers("{.}foo")); + assertEquals(expectedDst, jedis.smembers("{.}bar")); + + status = jedis.smove("{.}foo", "{.}bar", "a"); + assertEquals(status, 0); + } + + @Test + @Override + public void sinter() { + jedis.sadd("foo{.}", "a"); + jedis.sadd("foo{.}", "b"); + + jedis.sadd("bar{.}", "b"); + jedis.sadd("bar{.}", "c"); + + Set expected = new HashSet<>(); + expected.add("b"); + + Set intersection = jedis.sinter("foo{.}", "bar{.}"); + assertEquals(expected, intersection); + } + + @Test + @Override + public void sinterstore() { + jedis.sadd("foo{.}", "a"); + jedis.sadd("foo{.}", "b"); + + jedis.sadd("bar{.}", "b"); + jedis.sadd("bar{.}", "c"); + + Set expected = new HashSet<>(); + expected.add("b"); + + long status = jedis.sinterstore("car{.}", "foo{.}", "bar{.}"); + assertEquals(1, status); + + assertEquals(expected, jedis.smembers("car{.}")); + } + + @Test + @Override + public void sunion() { + jedis.sadd("{.}foo", "a"); + jedis.sadd("{.}foo", "b"); + + jedis.sadd("{.}bar", "b"); + jedis.sadd("{.}bar", "c"); + + Set expected = new HashSet<>(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + + Set union = jedis.sunion("{.}foo", "{.}bar"); + assertEquals(expected, union); + } + + @Test + @Override + public void sunionstore() { + jedis.sadd("{.}foo", "a"); + jedis.sadd("{.}foo", "b"); + + jedis.sadd("{.}bar", "b"); + jedis.sadd("{.}bar", "c"); + + Set expected = new HashSet<>(); + expected.add("a"); + expected.add("b"); + expected.add("c"); + + long status = jedis.sunionstore("{.}car", "{.}foo", "{.}bar"); + assertEquals(3, status); + + assertEquals(expected, jedis.smembers("{.}car")); + } + + @Test + @Override + public void sdiff() { + jedis.sadd("foo{.}", "x"); + jedis.sadd("foo{.}", "a"); + jedis.sadd("foo{.}", "b"); + jedis.sadd("foo{.}", "c"); + + jedis.sadd("bar{.}", "c"); + + jedis.sadd("car{.}", "a"); + jedis.sadd("car{.}", "d"); + + Set expected = new HashSet<>(); + expected.add("x"); + expected.add("b"); + + Set diff = jedis.sdiff("foo{.}", "bar{.}", "car{.}"); + assertEquals(expected, diff); + } + + @Test + @Override + public void sdiffstore() { + jedis.sadd("foo{.}", "x"); + jedis.sadd("foo{.}", "a"); + jedis.sadd("foo{.}", "b"); + jedis.sadd("foo{.}", "c"); + + jedis.sadd("bar{.}", "c"); + + jedis.sadd("car{.}", "a"); + jedis.sadd("car{.}", "d"); + + Set expected = new HashSet<>(); + expected.add("x"); + expected.add("b"); + + long status = jedis.sdiffstore("tar{.}", "foo{.}", "bar{.}", "car{.}"); + assertEquals(2, status); + assertEquals(expected, jedis.smembers("tar{.}")); + } + +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSortedSetCommandsTest.java new file mode 100644 index 0000000000..b7d1295e10 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterSortedSetCommandsTest.java @@ -0,0 +1,190 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.params.ZAddParams; +import redis.clients.jedis.params.ZParams; +import redis.clients.jedis.resps.KeyedZSetElement; +import redis.clients.jedis.resps.Tuple; +import redis.clients.jedis.commands.unified.SortedSetCommandsTestBase; + +public class ClusterSortedSetCommandsTest extends SortedSetCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void zunion() { + jedis.zadd("{:}foo", 1, "a"); + jedis.zadd("{:}foo", 2, "b"); + jedis.zadd("{:}bar", 2, "a"); + jedis.zadd("{:}bar", 2, "b"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + Set expected = new LinkedHashSet<>(); + expected.add("a"); + expected.add("b"); + assertEquals(expected, jedis.zunion(params, "{:}foo", "{:}bar")); + + Set expectedTuple = new LinkedHashSet<>(); + expectedTuple.add(new Tuple("b", new Double(9))); + expectedTuple.add(new Tuple("a", new Double(7))); + assertEquals(expectedTuple, jedis.zunionWithScores(params, "{:}foo", "{:}bar")); + } + + @Test + @Override + public void zunionstore() { + jedis.zadd("{:}foo", 1, "a"); + jedis.zadd("{:}foo", 2, "b"); + jedis.zadd("{:}bar", 2, "a"); + jedis.zadd("{:}bar", 2, "b"); + + assertEquals(2, jedis.zunionstore("{:}dst", "{:}foo", "{:}bar")); + + List expected = new ArrayList<>(); + expected.add(new Tuple("a", new Double(3))); + expected.add(new Tuple("b", new Double(4))); + assertEquals(expected, jedis.zrangeWithScores("{:}dst", 0, 100)); + } + + @Test + @Override + public void zunionstoreParams() { + jedis.zadd("{:}foo", 1, "a"); + jedis.zadd("{:}foo", 2, "b"); + jedis.zadd("{:}bar", 2, "a"); + jedis.zadd("{:}bar", 2, "b"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + + assertEquals(2, jedis.zunionstore("{:}dst", params, "{:}foo", "{:}bar")); + + List expected = new ArrayList<>(); + expected.add(new Tuple("a", new Double(7))); + expected.add(new Tuple("b", new Double(9))); + assertEquals(expected, jedis.zrangeWithScores("{:}dst", 0, 100)); + } + + @Test + @Override + public void zinter() { + jedis.zadd("foo{:}", 1, "a"); + jedis.zadd("foo{:}", 2, "b"); + jedis.zadd("bar{:}", 2, "a"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + assertEquals(Collections.singleton("a"), jedis.zinter(params, "foo{:}", "bar{:}")); + + assertEquals(Collections.singleton(new Tuple("a", new Double(7))), + jedis.zinterWithScores(params, "foo{:}", "bar{:}")); + } + + @Test + @Override + public void zinterstore() { + jedis.zadd("foo{:}", 1, "a"); + jedis.zadd("foo{:}", 2, "b"); + jedis.zadd("bar{:}", 2, "a"); + + assertEquals(1, jedis.zinterstore("dst{:}", "foo{:}", "bar{:}")); + + assertEquals(Collections.singletonList(new Tuple("a", new Double(3))), + jedis.zrangeWithScores("dst{:}", 0, 100)); + } + + @Test + @Override + public void zintertoreParams() { + jedis.zadd("foo{:}", 1, "a"); + jedis.zadd("foo{:}", 2, "b"); + jedis.zadd("bar{:}", 2, "a"); + + ZParams params = new ZParams(); + params.weights(2, 2.5); + params.aggregate(ZParams.Aggregate.SUM); + + assertEquals(1, jedis.zinterstore("dst{:}", params, "foo{:}", "bar{:}")); + + assertEquals(Collections.singletonList(new Tuple("a", new Double(7))), + jedis.zrangeWithScores("dst{:}", 0, 100)); + } + + @Test + @Override + public void bzpopmax() { + jedis.zadd("f{:}oo", 1d, "a", ZAddParams.zAddParams().nx()); + jedis.zadd("f{:}oo", 10d, "b", ZAddParams.zAddParams().nx()); + jedis.zadd("b{:}ar", 0.1d, "c", ZAddParams.zAddParams().nx()); + assertEquals(new KeyedZSetElement("f{:}oo", "b", 10d), jedis.bzpopmax(0, "f{:}oo", "b{:}ar")); + } + + @Test + @Override + public void bzpopmin() { + jedis.zadd("fo{:}o", 1d, "a", ZAddParams.zAddParams().nx()); + jedis.zadd("fo{:}o", 10d, "b", ZAddParams.zAddParams().nx()); + jedis.zadd("ba{:}r", 0.1d, "c", ZAddParams.zAddParams().nx()); + assertEquals(new KeyedZSetElement("ba{:}r", "c", 0.1d), jedis.bzpopmin(0, "ba{:}r", "fo{:}o")); + } + + @Test + @Override + public void zdiff() { + jedis.zadd("{:}foo", 1.0, "a"); + jedis.zadd("{:}foo", 2.0, "b"); + jedis.zadd("{:}bar", 1.0, "a"); + + assertEquals(0, jedis.zdiff("{bar}1", "{bar}2").size()); + assertEquals(Collections.singleton("b"), jedis.zdiff("{:}foo", "{:}bar")); + assertEquals(Collections.singleton(new Tuple("b", 2.0d)), jedis.zdiffWithScores("{:}foo", "{:}bar")); + } + + @Test + @Override + public void zdiffStore() { + jedis.zadd("foo{:}", 1.0, "a"); + jedis.zadd("foo{:}", 2.0, "b"); + jedis.zadd("bar{:}", 1.0, "a"); + + assertEquals(0, jedis.zdiffStore("{bar}3", "{bar}1", "{bar}2")); + assertEquals(1, jedis.zdiffStore("bar{:}3", "foo{:}", "bar{:}")); + assertEquals(Collections.singletonList("b"), jedis.zrange("bar{:}3", 0, -1)); + } + +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterStringValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterStringValuesCommandsTest.java new file mode 100644 index 0000000000..d1fe660834 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/cluster/ClusterStringValuesCommandsTest.java @@ -0,0 +1,85 @@ +package redis.clients.jedis.commands.unified.cluster; + +import static org.junit.Assert.assertEquals; + +import java.util.ArrayList; +import java.util.List; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import redis.clients.jedis.commands.unified.StringValuesCommandsTestBase; + +public class ClusterStringValuesCommandsTest extends StringValuesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = ClusterCommandsTestHelper.initAndGetCluster(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @AfterClass + public static void resetCluster() { + ClusterCommandsTestHelper.tearClusterDown(); + } + + @Before + public void setUp() { + ClusterCommandsTestHelper.clearClusterData(); + } + + @Test + @Override + public void mget() { + List values = jedis.mget("foo{^}", "bar{^}"); + List expected = new ArrayList<>(); + expected.add(null); + expected.add(null); + + assertEquals(expected, values); + + jedis.set("foo{^}", "bar"); + + expected = new ArrayList<>(); + expected.add("bar"); + expected.add(null); + values = jedis.mget("foo{^}", "bar{^}"); + + assertEquals(expected, values); + + jedis.set("bar{^}", "foo"); + + expected = new ArrayList<>(); + expected.add("bar"); + expected.add("foo"); + values = jedis.mget("foo{^}", "bar{^}"); + + assertEquals(expected, values); + } + + @Test + @Override + public void mset() { + String status = jedis.mset("{^}foo", "bar", "{^}bar", "foo"); + assertEquals("OK", status); + assertEquals("bar", jedis.get("{^}foo")); + assertEquals("foo", jedis.get("{^}bar")); + } + + @Test + @Override + public void msetnx() { + assertEquals(1, jedis.msetnx("{^}foo", "bar", "{^}bar", "foo")); + assertEquals("bar", jedis.get("{^}foo")); + assertEquals("foo", jedis.get("{^}bar")); + + assertEquals(0, jedis.msetnx("{^}foo", "bar1", "{^}bar2", "foo2")); + assertEquals("bar", jedis.get("{^}foo")); + assertEquals("foo", jedis.get("{^}bar")); + } + +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledAllKindOfValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledAllKindOfValuesCommandsTest.java new file mode 100644 index 0000000000..3e1d8a0c39 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledAllKindOfValuesCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.AllKindOfValuesCommandsTestBase; + +public class PooledAllKindOfValuesCommandsTest extends AllKindOfValuesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBinaryValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBinaryValuesCommandsTest.java new file mode 100644 index 0000000000..63adddb561 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBinaryValuesCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.BinaryValuesCommandsTestBase; + +public class PooledBinaryValuesCommandsTest extends BinaryValuesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBitCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBitCommandsTest.java new file mode 100644 index 0000000000..0d0522f282 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledBitCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.BitCommandsTestBase; + +public class PooledBitCommandsTest extends BitCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledCommandsTestHelper.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledCommandsTestHelper.java new file mode 100644 index 0000000000..733945db5f --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledCommandsTestHelper.java @@ -0,0 +1,26 @@ +package redis.clients.jedis.commands.unified.pooled; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.JedisPooled; +import redis.clients.jedis.HostAndPorts; + +public class PooledCommandsTestHelper { + + private static final HostAndPort nodeInfo = HostAndPorts.getRedisServers().get(0); + + private static Jedis node; + + static JedisPooled getPooled() throws InterruptedException { + + node = new Jedis(nodeInfo); + node.auth("foobared"); + node.flushAll(); + + return new JedisPooled(nodeInfo.getHost(), nodeInfo.getPort(), null, "foobared"); + } + + static void clearData() { + node.flushDB(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledGeoCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledGeoCommandsTest.java new file mode 100644 index 0000000000..95e698d790 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledGeoCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.GeoCommandsTestBase; + +public class PooledGeoCommandsTest extends GeoCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHashesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHashesCommandsTest.java new file mode 100644 index 0000000000..d7251d1206 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHashesCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.HashesCommandsTestBase; + +public class PooledHashesCommandsTest extends HashesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHyperLogLogCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHyperLogLogCommandsTest.java new file mode 100644 index 0000000000..9519a81c81 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledHyperLogLogCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.HyperLogLogCommandsTestBase; + +public class PooledHyperLogLogCommandsTest extends HyperLogLogCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledListCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledListCommandsTest.java new file mode 100644 index 0000000000..414cd52c64 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledListCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.ListCommandsTestBase; + +public class PooledListCommandsTest extends ListCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSetCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSetCommandsTest.java new file mode 100644 index 0000000000..c2fcf96bf2 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSetCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.SetCommandsTestBase; + +public class PooledSetCommandsTest extends SetCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSortedSetCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSortedSetCommandsTest.java new file mode 100644 index 0000000000..9868cbb927 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledSortedSetCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.SortedSetCommandsTestBase; + +public class PooledSortedSetCommandsTest extends SortedSetCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledStringValuesCommandsTest.java b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledStringValuesCommandsTest.java new file mode 100644 index 0000000000..d7b510b050 --- /dev/null +++ b/src/test/java/redis/clients/jedis/commands/unified/pooled/PooledStringValuesCommandsTest.java @@ -0,0 +1,24 @@ +package redis.clients.jedis.commands.unified.pooled; + +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.commands.unified.StringValuesCommandsTestBase; + +public class PooledStringValuesCommandsTest extends StringValuesCommandsTestBase { + + @BeforeClass + public static void prepare() throws InterruptedException { + jedis = PooledCommandsTestHelper.getPooled(); + } + + @AfterClass + public static void closeCluster() { + jedis.close(); + } + + @Before + public void setUp() { + PooledCommandsTestHelper.clearData(); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/ExceptionsTest.java b/src/test/java/redis/clients/jedis/exceptions/ExceptionsTest.java similarity index 80% rename from src/test/java/redis/clients/jedis/tests/ExceptionsTest.java rename to src/test/java/redis/clients/jedis/exceptions/ExceptionsTest.java index 83650c03a3..9bdd77371b 100644 --- a/src/test/java/redis/clients/jedis/tests/ExceptionsTest.java +++ b/src/test/java/redis/clients/jedis/exceptions/ExceptionsTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis.exceptions; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; @@ -6,9 +6,7 @@ import org.junit.BeforeClass; import org.junit.Test; - import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.exceptions.*; public class ExceptionsTest { @@ -186,33 +184,6 @@ public void cluster() { } } - @Test - public void maxAttempts() { - try { - throw new JedisClusterMaxAttemptsException(MESSAGE); - } catch (Exception e) { - assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertNull(e.getCause()); - } - - try { - throw new JedisClusterMaxAttemptsException(CAUSE); - } catch (Exception e) { - assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); - assertEquals(CAUSE, e.getCause()); - assertEquals(CAUSE.toString(), e.getMessage()); - } - - try { - throw new JedisClusterMaxAttemptsException(MESSAGE, CAUSE); - } catch (Exception e) { - assertSame(JedisClusterMaxAttemptsException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertEquals(CAUSE, e.getCause()); - } - } - @Test public void clusterOperation() { try { @@ -321,33 +292,6 @@ public void jedis() { } } - @Test - public void exhaustedPool() { - try { - throw new JedisExhaustedPoolException(MESSAGE); - } catch (Exception e) { - assertSame(JedisExhaustedPoolException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertNull(e.getCause()); - } - - try { - throw new JedisExhaustedPoolException(CAUSE); - } catch (Exception e) { - assertSame(JedisExhaustedPoolException.class, e.getClass()); - assertEquals(CAUSE, e.getCause()); - assertEquals(CAUSE.toString(), e.getMessage()); - } - - try { - throw new JedisExhaustedPoolException(MESSAGE, CAUSE); - } catch (Exception e) { - assertSame(JedisExhaustedPoolException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertEquals(CAUSE, e.getCause()); - } - } - @Test public void movedData() { HostAndPort hap = new HostAndPort("", 0); @@ -378,33 +322,6 @@ public void movedData() { } } - @Test - public void noReachableNode() { - try { - throw new JedisNoReachableClusterNodeException(MESSAGE); - } catch (Exception e) { - assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertNull(e.getCause()); - } - - try { - throw new JedisNoReachableClusterNodeException(CAUSE); - } catch (Exception e) { - assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); - assertEquals(CAUSE, e.getCause()); - assertEquals(CAUSE.toString(), e.getMessage()); - } - - try { - throw new JedisNoReachableClusterNodeException(MESSAGE, CAUSE); - } catch (Exception e) { - assertSame(JedisNoReachableClusterNodeException.class, e.getClass()); - assertEquals(MESSAGE, e.getMessage()); - assertEquals(CAUSE, e.getCause()); - } - } - @Test public void noScript() { try { diff --git a/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java b/src/test/java/redis/clients/jedis/exceptions/FailoverAbortedException.java similarity index 90% rename from src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java rename to src/test/java/redis/clients/jedis/exceptions/FailoverAbortedException.java index 547d1b69b3..4ca85ce25e 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/FailoverAbortedException.java +++ b/src/test/java/redis/clients/jedis/exceptions/FailoverAbortedException.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.exceptions; public class FailoverAbortedException extends RuntimeException { private static final long serialVersionUID = 1925110762858409954L; diff --git a/src/test/java/redis/clients/jedis/modules/RedisModuleCommandsTestBase.java b/src/test/java/redis/clients/jedis/modules/RedisModuleCommandsTestBase.java new file mode 100644 index 0000000000..31ae550590 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/RedisModuleCommandsTestBase.java @@ -0,0 +1,56 @@ +package redis.clients.jedis.modules; + +import static org.junit.Assume.assumeTrue; + +import org.junit.After; +import org.junit.Before; +import org.junit.BeforeClass; +import redis.clients.jedis.Connection; + +import redis.clients.jedis.HostAndPort; +import redis.clients.jedis.Jedis; +import redis.clients.jedis.Protocol; +import redis.clients.jedis.UnifiedJedis; +import redis.clients.jedis.exceptions.JedisConnectionException; +import redis.clients.jedis.providers.PooledConnectionProvider; + +public abstract class RedisModuleCommandsTestBase { + + protected static final HostAndPort hnp = new HostAndPort(Protocol.DEFAULT_HOST, 6479); + + private static final PooledConnectionProvider provider = new PooledConnectionProvider(hnp); + protected UnifiedJedis client; + + public RedisModuleCommandsTestBase() { + super(); + } + + public static void prepare() { + try (Connection connection = new Connection(hnp)) { + assumeTrue("No Redis running on 6479 port. Ignoring modules tests.", connection.ping()); + } catch (JedisConnectionException jce) { + assumeTrue(false); + } + } + + @Before + public void setUp() { + try (Jedis jedis = createJedis()) { + jedis.flushAll(); + } + client = new UnifiedJedis(provider); + } +// +// @After +// public void tearDown() throws Exception { +// client.close(); +// } +// +// public static void tearDown() { +// client.close(); +// } + + protected static Jedis createJedis() { + return new Jedis(hnp); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/json/Path2Test.java b/src/test/java/redis/clients/jedis/modules/json/Path2Test.java new file mode 100644 index 0000000000..ce27749cc6 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/json/Path2Test.java @@ -0,0 +1,43 @@ +package redis.clients.jedis.modules.json; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; +import redis.clients.jedis.json.Path2; + +public class Path2Test { + + @Test(expected = NullPointerException.class) + public void _null() { + Path2.of(null); + } + + @Test(expected = IllegalArgumentException.class) + public void empty() { + Path2.of(""); + } + + @Test + public void root() { + assertEquals("$", Path2.ROOT_PATH.toString()); + assertEquals(Path2.ROOT_PATH, new Path2("$")); + assertEquals(Path2.ROOT_PATH, Path2.of("$")); + } + + @Test + public void test() { + assertEquals("$.a.b", Path2.of("$.a.b").toString()); + assertEquals("$.a.b", new Path2("$.a.b").toString()); + assertEquals("$.a.b", Path2.of(".a.b").toString()); + assertEquals("$.a.b", new Path2(".a.b").toString()); + assertEquals("$.a.b", Path2.of("a.b").toString()); + assertEquals("$.a.b", new Path2("a.b").toString()); + } + + @Test + public void equals() { + assertTrue(new Path2("a.b").equals(Path2.of(".a.b"))); + assertTrue(Path2.of("a.b").equals(new Path2(".a.b"))); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/json/PathTest.java b/src/test/java/redis/clients/jedis/modules/json/PathTest.java new file mode 100644 index 0000000000..15e014f226 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/json/PathTest.java @@ -0,0 +1,36 @@ +package redis.clients.jedis.modules.json; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import org.junit.Test; +import redis.clients.jedis.json.Path; + +public class PathTest { + + @Test + public void testRootPathConstant() { + assertEquals(".", Path.ROOT_PATH.toString()); + } + + @Test + public void testStaticFactoryMethod() { + assertEquals(".a.b", Path.of(".a.b").toString()); + } + + @Test + public void testPathEquals() { + assertEquals(Path.of(".a.b.c"), Path.of(".a.b.c")); + assertNotEquals(Path.of(".a.b.c"), Path.of(".b.c")); + assertNotEquals(Path.of(".a.b.c"), null); + assertNotEquals(Path.of(".a.b.c"), ".a.b.c"); + Path aPath = Path.of(".a"); + assertEquals(aPath, aPath); + } + + @Test + public void testPathHashCode() { + assertEquals(Path.of(".a.b.c").hashCode(), Path.of(".a.b.c").hashCode()); + assertNotEquals(Path.of(".a.b.c").hashCode(), Path.of(".b.c").hashCode()); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/json/RedisJsonV1Test.java b/src/test/java/redis/clients/jedis/modules/json/RedisJsonV1Test.java new file mode 100644 index 0000000000..e7e18c1e48 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/json/RedisJsonV1Test.java @@ -0,0 +1,516 @@ +package redis.clients.jedis.modules.json; + +import static org.junit.Assert.*; +import static redis.clients.jedis.json.Path.ROOT_PATH; + +import com.google.gson.Gson; +import com.google.gson.JsonArray; +import com.google.gson.JsonObject; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path; +import redis.clients.jedis.modules.RedisModuleCommandsTestBase; + +public class RedisJsonV1Test extends RedisModuleCommandsTestBase { + + @BeforeClass + public static void prepare() { + RedisModuleCommandsTestBase.prepare(); + } + + /* A simple class that represents an object in real life */ + @SuppressWarnings("unused") + private static class IRLObject { + + public String str; + public boolean bool; + + public IRLObject() { + this.str = "string"; + this.bool = true; + } + } + + @SuppressWarnings("unused") + private static class FooBarObject { + + public String foo; + public boolean fooB; + public int fooI; + public float fooF; + public String[] fooArr; + + public FooBarObject() { + this.foo = "bar"; + this.fooB = true; + this.fooI = 6574; + this.fooF = 435.345f; + this.fooArr = new String[]{"a", "b", "c"}; + } + } + + private static class Baz { + + private String quuz; + private String grault; + private String waldo; + + public Baz(final String quuz, final String grault, final String waldo) { + this.quuz = quuz; + this.grault = grault; + this.waldo = waldo; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + if (getClass() != o.getClass()) { + return false; + } + Baz other = (Baz) o; + + return Objects.equals(quuz, other.quuz) + && Objects.equals(grault, other.grault) + && Objects.equals(waldo, other.waldo); + } + } + + private static class Qux { + + private String quux; + private String corge; + private String garply; + private Baz baz; + + public Qux(final String quux, final String corge, final String garply, final Baz baz) { + this.quux = quux; + this.corge = corge; + this.garply = garply; + this.baz = baz; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + if (getClass() != o.getClass()) { + return false; + } + Qux other = (Qux) o; + + return Objects.equals(quux, other.quux) + && Objects.equals(corge, other.corge) + && Objects.equals(garply, other.garply) + && Objects.equals(baz, other.baz); + } + } + + private final Gson gson = new Gson(); + + @Test + public void basicSetGetShouldSucceed() { + + // naive set with a path +// client.jsonSet("null", null, ROOT_PATH); + client.jsonSet("null", ROOT_PATH, (Object) null); + assertNull(client.jsonGet("null", String.class, ROOT_PATH)); + + // real scalar value and no path + client.jsonSet("str", ROOT_PATH, "strong"); + assertEquals("strong", client.jsonGet("str")); + + // a slightly more complex object + IRLObject obj = new IRLObject(); + client.jsonSet("obj", ROOT_PATH, obj); + Object expected = gson.fromJson(gson.toJson(obj), Object.class); + assertTrue(expected.equals(client.jsonGet("obj"))); + + // check an update + Path p = Path.of(".str"); + client.jsonSet("obj", p, "strung"); + assertEquals("strung", client.jsonGet("obj", String.class, p)); + } + + @Test + public void setExistingPathOnlyIfExistsShouldSucceed() { + client.jsonSet("obj", ROOT_PATH, new IRLObject()); + Path p = Path.of(".str"); + client.jsonSet("obj", p, "strangle", JsonSetParams.jsonSetParams().xx()); + assertEquals("strangle", client.jsonGet("obj", String.class, p)); + } + + @Test + public void setNonExistingOnlyIfNotExistsShouldSucceed() { + client.jsonSet("obj", ROOT_PATH, new IRLObject()); + Path p = Path.of(".none"); + client.jsonSet("obj", p, "strangle", JsonSetParams.jsonSetParams().nx()); + assertEquals("strangle", client.jsonGet("obj", String.class, p)); + } + + @Test + public void setWithoutAPathDefaultsToRootPath() { + client.jsonSet("obj1", ROOT_PATH, new IRLObject()); +// client.jsonSet("obj1", "strangle", JsonSetParams.jsonSetParams().xx()); + client.jsonSetLegacy("obj1", (Object) "strangle", JsonSetParams.jsonSetParams().xx()); + assertEquals("strangle", client.jsonGet("obj1", String.class, ROOT_PATH)); + } + + @Test + public void setExistingPathOnlyIfNotExistsShouldFail() { + client.jsonSet("obj", ROOT_PATH, new IRLObject()); + Path p = Path.of(".str"); + assertNull(client.jsonSet("obj", p, "strangle", JsonSetParams.jsonSetParams().nx())); + } + + @Test + public void setNonExistingPathOnlyIfExistsShouldFail() { + client.jsonSet("obj", ROOT_PATH, new IRLObject()); + Path p = Path.of(".none"); + assertNull(client.jsonSet("obj", p, "strangle", JsonSetParams.jsonSetParams().xx())); + } + + @Test(expected = JedisDataException.class) + public void setException() { + // should error on non root path for new key + client.jsonSet("test", Path.of(".foo"), "bar"); + } + + @Test + public void getMultiplePathsShouldSucceed() { + // check multiple paths + IRLObject obj = new IRLObject(); + client.jsonSet("obj", gson.toJson(obj)); + Object expected = gson.fromJson(gson.toJson(obj), Object.class); + assertTrue(expected.equals(client.jsonGet("obj", Object.class, Path.of("bool"), Path.of("str")))); + } + + @Test + public void getMultiplePathsShouldSucceedWithLegacy() { + // check multiple paths + IRLObject obj = new IRLObject(); + client.jsonSetLegacy("obj", obj); + Object expected = gson.fromJson(gson.toJson(obj), Object.class); + assertTrue(expected.equals(client.jsonGet("obj", Object.class, Path.of("bool"), Path.of("str")))); + } + + @Test + public void toggle() { + + IRLObject obj = new IRLObject(); + client.jsonSetLegacy("obj", obj); + + Path pbool = Path.of(".bool"); + // check initial value + assertTrue(client.jsonGet("obj", Boolean.class, pbool)); + + // true -> false + client.jsonToggle("obj", pbool); + assertFalse(client.jsonGet("obj", Boolean.class, pbool)); + + // false -> true + client.jsonToggle("obj", pbool); + assertTrue(client.jsonGet("obj", Boolean.class, pbool)); + + // ignore non-boolean field + Path pstr = Path.of(".str"); + try { + client.jsonToggle("obj", pstr); + fail("String not a bool"); + } catch (JedisDataException jde) { + assertTrue(jde.getMessage().contains("not a bool")); + } + assertEquals("string", client.jsonGet("obj", String.class, pstr)); + } + + @Test(expected = JedisDataException.class) + public void getException() { + client.jsonSet("test", ROOT_PATH, "foo"); + client.jsonGet("test", String.class, Path.of(".bar")); + } + + @Test + public void delValidShouldSucceed() { + // check deletion of a single path + client.jsonSet("obj", ROOT_PATH, new IRLObject()); + assertEquals(1L, client.jsonDel("obj", Path.of(".str"))); + assertTrue(client.exists("obj")); + + // check deletion root using default root -> key is removed + assertEquals(1L, client.jsonDel("obj")); + assertFalse(client.exists("obj")); + } + + @Test + public void delNonExistingPathsAreIgnored() { + client.jsonSet("foobar", ROOT_PATH, new FooBarObject()); + assertEquals(0L, client.jsonDel("foobar", Path.of(".foo[1]"))); + } + + @Test + public void typeChecksShouldSucceed() { + assertNull(client.jsonType("foobar")); + client.jsonSet("foobar", ROOT_PATH, new FooBarObject()); + assertSame(Object.class, client.jsonType("foobar")); + assertSame(Object.class, client.jsonType("foobar", ROOT_PATH)); + assertSame(String.class, client.jsonType("foobar", Path.of(".foo"))); + assertSame(int.class, client.jsonType("foobar", Path.of(".fooI"))); + assertSame(float.class, client.jsonType("foobar", Path.of(".fooF"))); + assertSame(List.class, client.jsonType("foobar", Path.of(".fooArr"))); + assertSame(boolean.class, client.jsonType("foobar", Path.of(".fooB"))); + assertNull(client.jsonType("foobar", Path.of(".fooErr"))); + } + + @Test + public void mgetWithPathWithAllKeysExist() { + Baz baz1 = new Baz("quuz1", "grault1", "waldo1"); + Baz baz2 = new Baz("quuz2", "grault2", "waldo2"); + Qux qux1 = new Qux("quux1", "corge1", "garply1", baz1); + Qux qux2 = new Qux("quux2", "corge2", "garply2", baz2); + + client.jsonSetLegacy("qux1", qux1); + client.jsonSetLegacy("qux2", qux2); + + List allBaz = client.jsonMGet(Path.of("baz"), Baz.class, "qux1", "qux2"); + + assertEquals(2, allBaz.size()); + + Baz testBaz1 = allBaz.stream() // + .filter(b -> b.quuz.equals("quuz1")) // + .findFirst() // + .orElseThrow(() -> new NullPointerException("")); + Baz testBaz2 = allBaz.stream() // + .filter(q -> q.quuz.equals("quuz2")) // + .findFirst() // + .orElseThrow(() -> new NullPointerException("")); + + assertEquals(baz1, testBaz1); + assertEquals(baz2, testBaz2); + } + + @Test + public void mgetAtRootPathWithMissingKeys() { + Baz baz1 = new Baz("quuz1", "grault1", "waldo1"); + Baz baz2 = new Baz("quuz2", "grault2", "waldo2"); + Qux qux1 = new Qux("quux1", "corge1", "garply1", baz1); + Qux qux2 = new Qux("quux2", "corge2", "garply2", baz2); + + client.jsonSet("qux1", gson.toJson(qux1)); + client.jsonSet("qux2", gson.toJson(qux2)); + + List allQux = client.jsonMGet(Qux.class, "qux1", "qux2", "qux3"); + + assertEquals(3, allQux.size()); + assertNull(allQux.get(2)); + allQux.removeAll(Collections.singleton(null)); + assertEquals(2, allQux.size()); + } + + @Test + public void arrLen() { + client.jsonSet("foobar", ROOT_PATH, new FooBarObject()); + assertEquals(Long.valueOf(3), client.jsonArrLen("foobar", Path.of(".fooArr"))); + } + + @Test + public void arrLenDefaultPath() { + assertNull(client.jsonArrLen("array")); + client.jsonSetLegacy("array", new int[]{1, 2, 3}); + assertEquals(Long.valueOf(3), client.jsonArrLen("array")); + } + + @Test + public void clearArray() { + client.jsonSet("foobar", ROOT_PATH, new FooBarObject()); + + Path arrPath = Path.of(".fooArr"); + assertEquals(Long.valueOf(3), client.jsonArrLen("foobar", arrPath)); + + assertEquals(1L, client.jsonClear("foobar", arrPath)); + assertEquals(Long.valueOf(0), client.jsonArrLen("foobar", arrPath)); + + // ignore non-array + Path strPath = Path.of("foo"); + assertEquals(0L, client.jsonClear("foobar", strPath)); + assertEquals("bar", client.jsonGet("foobar", String.class, strPath)); + } + + @Test + public void clearObject() { + Baz baz = new Baz("quuz", "grault", "waldo"); + Qux qux = new Qux("quux", "corge", "garply", baz); + + client.jsonSet("qux", gson.toJson(qux)); + Path objPath = Path.of("baz"); + assertEquals(baz, client.jsonGet("qux", Baz.class, objPath)); + + assertEquals(1L, client.jsonClear("qux", objPath)); + assertEquals(new Baz(null, null, null), client.jsonGet("qux", Baz.class, objPath)); + } + + @Test + public void arrAppendSameType() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); + + client.jsonSet("test_arrappend", ROOT_PATH, jsonObject); + assertEquals(Long.valueOf(6), client.jsonArrAppend("test_arrappend", Path.of(".b"), 4, 5, 6)); + + Integer[] array = client.jsonGet("test_arrappend", Integer[].class, Path.of(".b")); + assertArrayEquals(new Integer[]{1, 2, 3, 4, 5, 6}, array); + } + + @Test + public void arrAppendMultipleTypes() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); + + client.jsonSet("test_arrappend", ROOT_PATH, jsonObject); + assertEquals(Long.valueOf(6), client.jsonArrAppend("test_arrappend", Path.of(".b"), "foo", true, null)); + + Object[] array = client.jsonGet("test_arrappend", Object[].class, Path.of(".b")); + + // NOTE: GSon converts numeric types to the most accommodating type (Double) + // when type information is not provided (as in the Object[] below) + assertArrayEquals(new Object[]{1.0, 2.0, 3.0, "foo", true, null}, array); + } + + @Test + public void arrAppendMultipleTypesWithDeepPath() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); + + client.jsonSet("test_arrappend", ROOT_PATH, jsonObject); + assertEquals(Long.valueOf(4), client.jsonArrAppend("test_arrappend", Path.of(".c.d"), "foo", true, null)); + + Object[] array = client.jsonGet("test_arrappend", Object[].class, Path.of(".c.d")); + assertArrayEquals(new Object[]{"ello", "foo", true, null}, array); + } + + @Test + public void arrAppendAgaintsEmptyArray() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: [] }}"; + JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); + + client.jsonSet("test_arrappend", ROOT_PATH, jsonObject); + assertEquals(Long.valueOf(3), client.jsonArrAppend("test_arrappend", Path.of(".c.d"), "a", "b", "c")); + + String[] array = client.jsonGet("test_arrappend", String[].class, Path.of(".c.d")); + assertArrayEquals(new String[]{"a", "b", "c"}, array); + } + + @Test(expected = JedisDataException.class) + public void arrAppendPathIsNotArray() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); + + client.jsonSet("test_arrappend", ROOT_PATH, jsonObject); + client.jsonArrAppend("test_arrappend", Path.of(".a"), 1); + } + + @Test(expected = JedisDataException.class) + public void arrIndexAbsentKey() { + client.jsonArrIndex("quxquux", ROOT_PATH, gson.toJson(new Object())); + } + + @Test + public void arrIndexWithInts() { + client.jsonSet("quxquux", ROOT_PATH, new int[]{8, 6, 7, 5, 3, 0, 9}); + assertEquals(2L, client.jsonArrIndex("quxquux", ROOT_PATH, 7)); + assertEquals(-1L, client.jsonArrIndex("quxquux", ROOT_PATH, "7")); + } + + @Test + public void arrIndexWithStrings() { + client.jsonSet("quxquux", ROOT_PATH, new String[]{"8", "6", "7", "5", "3", "0", "9"}); + assertEquals(2L, client.jsonArrIndex("quxquux", ROOT_PATH, "7")); + } + + @Test + public void arrIndexWithStringsAndPath() { + client.jsonSet("foobar", ROOT_PATH, new FooBarObject()); + assertEquals(1L, client.jsonArrIndex("foobar", Path.of(".fooArr"), "b")); + } + + @Test(expected = JedisDataException.class) + public void arrIndexNonExistentPath() { + client.jsonSet("foobar", ROOT_PATH, new FooBarObject()); + assertEquals(1L, client.jsonArrIndex("foobar", Path.of(".barArr"), "x")); + } + + @Test + public void arrInsert() { + String json = "['hello', 'world', true, 1, 3, null, false]"; + JsonArray jsonArray = new Gson().fromJson(json, JsonArray.class); + + client.jsonSet("test_arrinsert", ROOT_PATH, jsonArray); + assertEquals(8L, client.jsonArrInsert("test_arrinsert", ROOT_PATH, 1, "foo")); + + Object[] array = client.jsonGet("test_arrinsert", Object[].class, ROOT_PATH); + + // NOTE: GSon converts numeric types to the most accommodating type (Double) + // when type information is not provided (as in the Object[] below) + assertArrayEquals(new Object[]{"hello", "foo", "world", true, 1.0, 3.0, null, false}, array); + } + + @Test + public void arrInsertWithNegativeIndex() { + String json = "['hello', 'world', true, 1, 3, null, false]"; + JsonArray jsonArray = new Gson().fromJson(json, JsonArray.class); + + client.jsonSet("test_arrinsert", ROOT_PATH, jsonArray); + assertEquals(8L, client.jsonArrInsert("test_arrinsert", ROOT_PATH, -1, "foo")); + + Object[] array = client.jsonGet("test_arrinsert", Object[].class, ROOT_PATH); + assertArrayEquals(new Object[]{"hello", "world", true, 1.0, 3.0, null, "foo", false}, array); + } + + @Test + public void testArrayPop() { + client.jsonSet("arr", ROOT_PATH, new int[]{0, 1, 2, 3, 4}); + assertEquals(Long.valueOf(4), client.jsonArrPop("arr", Long.class, ROOT_PATH)); + assertEquals(Long.valueOf(3), client.jsonArrPop("arr", Long.class, ROOT_PATH, -1)); + assertEquals(Long.valueOf(2), client.jsonArrPop("arr", Long.class)); + assertEquals(Long.valueOf(0), client.jsonArrPop("arr", Long.class, ROOT_PATH, 0)); + assertEquals(Double.valueOf(1), client.jsonArrPop("arr")); + } + + @Test + public void arrTrim() { + client.jsonSet("arr", ROOT_PATH, new int[]{0, 1, 2, 3, 4}); + assertEquals(Long.valueOf(3), client.jsonArrTrim("arr", ROOT_PATH, 1, 3)); + assertArrayEquals(new Integer[]{1, 2, 3}, client.jsonGet("arr", Integer[].class, ROOT_PATH)); + } + + @Test + public void strAppend() { + client.jsonSet("str", ROOT_PATH, "foo"); + assertEquals(6L, client.jsonStrAppend("str", ROOT_PATH, "bar")); + assertEquals("foobar", client.jsonGet("str", String.class, ROOT_PATH)); + assertEquals(8L, client.jsonStrAppend("str", "ed")); +// assertEquals("foobared", client.jsonGet("str", String.class)); + assertEquals("foobared", client.jsonGet("str")); + } + + @Test + public void strLen() { + assertNull(client.jsonStrLen("str")); + client.jsonSet("str", ROOT_PATH, "foo"); + assertEquals(Long.valueOf(3), client.jsonStrLen("str")); + assertEquals(Long.valueOf(3), client.jsonStrLen("str", ROOT_PATH)); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/json/RedisJsonV2Test.java b/src/test/java/redis/clients/jedis/modules/json/RedisJsonV2Test.java new file mode 100644 index 0000000000..9a1362bcdf --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/json/RedisJsonV2Test.java @@ -0,0 +1,535 @@ +package redis.clients.jedis.modules.json; + +import static java.util.Collections.emptyList; +import static java.util.Collections.singletonList; +import static org.junit.Assert.*; +import static redis.clients.jedis.json.Path2.ROOT_PATH; + +import com.google.gson.Gson; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import org.json.JSONArray; +import org.json.JSONObject; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.json.JsonSetParams; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.modules.RedisModuleCommandsTestBase; + +public class RedisJsonV2Test extends RedisModuleCommandsTestBase { + + @BeforeClass + public static void prepare() { + RedisModuleCommandsTestBase.prepare(); + } + + /* A simple class that represents an object in real life */ + @SuppressWarnings("unused") + private static class IRLObject { + + public String str; + public boolean bool; + + public IRLObject() { + this.str = "string"; + this.bool = true; + } + } + + @SuppressWarnings("unused") + private static class FooBarObject { + + public String foo; + public boolean fooB; + public int fooI; + public float fooF; + public String[] fooArr; + + public FooBarObject() { + this.foo = "bar"; + this.fooB = true; + this.fooI = 6574; + this.fooF = 435.345f; + this.fooArr = new String[]{"a", "b", "c"}; + } + } + + private static class Baz { + + private String quuz; + private String grault; + private String waldo; + + public Baz(final String quuz, final String grault, final String waldo) { + this.quuz = quuz; + this.grault = grault; + this.waldo = waldo; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + if (getClass() != o.getClass()) { + return false; + } + Baz other = (Baz) o; + + return Objects.equals(quuz, other.quuz) + && Objects.equals(grault, other.grault) + && Objects.equals(waldo, other.waldo); + } + } + + private static class Qux { + + private String quux; + private String corge; + private String garply; + private Baz baz; + + public Qux(final String quux, final String corge, final String garply, final Baz baz) { + this.quux = quux; + this.corge = corge; + this.garply = garply; + this.baz = baz; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null) { + return false; + } + if (getClass() != o.getClass()) { + return false; + } + Qux other = (Qux) o; + + return Objects.equals(quux, other.quux) + && Objects.equals(corge, other.corge) + && Objects.equals(garply, other.garply) + && Objects.equals(baz, other.baz); + } + } + + private static final Gson gson = new Gson(); + + @Test + public void basicSetGetShouldSucceed() { + + // naive set with a path +// client.jsonSet("null", null, ROOT_PATH); + client.jsonSetWithEscape("null", ROOT_PATH, (Object) null); + assertJsonArrayEquals(singletonJSONArray(null), client.jsonGet("null", ROOT_PATH)); + + // real scalar value and no path + client.jsonSetWithEscape("str", "strong"); + assertEquals("strong", client.jsonGet("str")); + + // a slightly more complex object + IRLObject obj = new IRLObject(); + client.jsonSetWithEscape("obj", obj); + Object expected = gson.fromJson(gson.toJson(obj), Object.class); + assertTrue(expected.equals(client.jsonGet("obj"))); + + // check an update + Path2 p = Path2.of(".str"); + client.jsonSet("obj", p, gson.toJson("strung")); + assertJsonArrayEquals(singletonJSONArray("strung"), client.jsonGet("obj", p)); + } + + @Test + public void setExistingPathOnlyIfExistsShouldSucceed() { + client.jsonSetWithEscape("obj", new IRLObject()); + Path2 p = Path2.of(".str"); + client.jsonSetWithEscape("obj", p, "strangle", JsonSetParams.jsonSetParams().xx()); + assertJsonArrayEquals(singletonJSONArray("strangle"), client.jsonGet("obj", p)); + } + + @Test + public void setNonExistingOnlyIfNotExistsShouldSucceed() { + client.jsonSet("obj", gson.toJson(new IRLObject())); + Path2 p = Path2.of(".none"); + client.jsonSet("obj", p, gson.toJson("strangle"), JsonSetParams.jsonSetParams().nx()); + assertJsonArrayEquals(singletonJSONArray("strangle"), client.jsonGet("obj", p)); + } + + @Test + public void setWithoutAPathDefaultsToRootPath() { + String objStr = gson.toJson(new IRLObject()); + client.jsonSet("obj1", new JSONObject(objStr)); +// client.jsonSet("obj1", "strangle", JsonSetParams.jsonSetParams().xx()); + client.jsonSetWithEscape("obj1", (Object) "strangle", JsonSetParams.jsonSetParams().xx()); + assertJsonArrayEquals(singletonJSONArray("strangle"), client.jsonGet("obj1", ROOT_PATH)); + } + + @Test + public void setExistingPathOnlyIfNotExistsShouldFail() { + client.jsonSetWithEscape("obj", new IRLObject()); + Path2 p = Path2.of(".str"); + assertNull(client.jsonSetWithEscape("obj", p, "strangle", JsonSetParams.jsonSetParams().nx())); + } + + @Test + public void setNonExistingPathOnlyIfExistsShouldFail() { + client.jsonSetWithEscape("obj", new IRLObject()); + Path2 p = Path2.of(".none"); + assertNull(client.jsonSetWithEscape("obj", p, "strangle", JsonSetParams.jsonSetParams().xx())); + } + + @Test(expected = JedisDataException.class) + public void setException() { + // should error on non root path for new key + client.jsonSet("test", Path2.of(".foo"), "bar"); + } + + @Test + public void getMultiplePathsShouldSucceed() { + // check multiple paths + IRLObject obj = new IRLObject(); + client.jsonSetWithEscape("obj", obj); + JSONObject result = (JSONObject) client.jsonGet("obj", Path2.of("bool"), Path2.of("str")); + assertJsonArrayEquals(singletonJSONArray(true), result.get("$.bool")); + assertJsonArrayEquals(singletonJSONArray("string"), result.get("$.str")); + } + + @Test + public void getMultiLevels() { + JSONObject obj = new JSONObject(); + obj.put("foo", "John"); + JSONObject inner = new JSONObject(); + inner.put("foo", "Jane"); + obj.put("bar", inner); + client.jsonSet("multi", obj); + assertJsonArrayEquals(new JSONArray(new String[]{"John", "Jane"}), + client.jsonGet("multi", new Path2("..foo"))); + } + + @Test + public void toggle() { + + IRLObject obj = new IRLObject(); + client.jsonSetWithEscape("obj", obj); + + Path2 pbool = Path2.of(".bool"); + // check initial value + assertJsonArrayEquals(singletonJSONArray(true), client.jsonGet("obj", pbool)); + + // true -> false + client.jsonToggle("obj", pbool); + assertJsonArrayEquals(singletonJSONArray(false), client.jsonGet("obj", pbool)); + + // false -> true + client.jsonToggle("obj", pbool); + assertJsonArrayEquals(singletonJSONArray(true), client.jsonGet("obj", pbool)); + + // ignore non-boolean field + Path2 pstr = Path2.of(".str"); + assertEquals(singletonList(null), client.jsonToggle("obj", pstr)); + assertJsonArrayEquals(singletonJSONArray("string"), client.jsonGet("obj", pstr)); + } + + @Test + public void getException() { + client.jsonSetWithEscape("test", ROOT_PATH, "foo"); + assertJsonArrayEquals(new JSONArray(), client.jsonGet("test", Path2.of(".bar"))); + } + + @Test + public void delValidShouldSucceed() { + // check deletion of a single path + client.jsonSetWithEscape("obj", ROOT_PATH, new IRLObject()); + assertEquals(1L, client.jsonDel("obj", Path2.of(".str"))); + assertTrue(client.exists("obj")); + + // check deletion root using default root -> key is removed + assertEquals(1L, client.jsonDel("obj")); + assertFalse(client.exists("obj")); + } + + @Test + public void delNonExistingPathsAreIgnored() { + client.jsonSetWithEscape("foobar", ROOT_PATH, new FooBarObject()); + assertEquals(0L, client.jsonDel("foobar", Path2.of(".foo[1]"))); + } + + @Test + public void typeChecksShouldSucceed() { + client.jsonSet("foobar", ROOT_PATH, new JSONObject(gson.toJson(new FooBarObject()))); + assertSame(Object.class, client.jsonType("foobar")); + assertEquals(singletonList(Object.class), client.jsonType("foobar", ROOT_PATH)); + assertEquals(singletonList(String.class), client.jsonType("foobar", Path2.of(".foo"))); + assertEquals(singletonList(int.class), client.jsonType("foobar", Path2.of(".fooI"))); + assertEquals(singletonList(float.class), client.jsonType("foobar", Path2.of(".fooF"))); + assertEquals(singletonList(List.class), client.jsonType("foobar", Path2.of(".fooArr"))); + assertEquals(singletonList(boolean.class), client.jsonType("foobar", Path2.of(".fooB"))); + assertEquals(emptyList(), client.jsonType("foobar", Path2.of(".fooErr"))); + } + + @Test + public void mgetWithPathWithAllKeysExist() { + Baz baz1 = new Baz("quuz1", "grault1", "waldo1"); + Baz baz2 = new Baz("quuz2", "grault2", "waldo2"); + Qux qux1 = new Qux("quux1", "corge1", "garply1", baz1); + Qux qux2 = new Qux("quux2", "corge2", "garply2", baz2); + + client.jsonSet("qux1", new JSONObject(gson.toJson(qux1))); + client.jsonSet("qux2", new JSONObject(gson.toJson(qux2))); + + List list = client.jsonMGet(Path2.of("baz"), "qux1", "qux2"); + assertEquals(2, list.size()); + assertJsonArrayEquals(singletonJSONArray(new JSONObject(gson.toJson(baz1))), list.get(0)); + assertJsonArrayEquals(singletonJSONArray(new JSONObject(gson.toJson(baz2))), list.get(1)); + } + + @Test + public void mgetAtRootPathWithMissingKeys() { + Baz baz1 = new Baz("quuz1", "grault1", "waldo1"); + Baz baz2 = new Baz("quuz2", "grault2", "waldo2"); + Qux qux1 = new Qux("quux1", "corge1", "garply1", baz1); + Qux qux2 = new Qux("quux2", "corge2", "garply2", baz2); + + client.jsonSetWithEscape("qux1", qux1); + client.jsonSetWithEscape("qux2", qux2); + + List list = client.jsonMGet("qux1", "qux2", "qux3"); + + assertEquals(3, list.size()); + assertNull(list.get(2)); + list.removeAll(singletonList(null)); + assertEquals(2, list.size()); + } + + @Test + public void arrLen() { + client.jsonSet("arr", ROOT_PATH, new JSONArray(new int[]{0, 1, 2, 3, 4})); + assertEquals(singletonList(5L), client.jsonArrLen("arr", ROOT_PATH)); + } + + @Test + public void clearArray() { + client.jsonSet("foobar", ROOT_PATH, gson.toJson(new FooBarObject())); + + Path2 arrPath = Path2.of(".fooArr"); + assertEquals(singletonList(3L), client.jsonArrLen("foobar", arrPath)); + + assertEquals(1L, client.jsonClear("foobar", arrPath)); + assertEquals(singletonList(0L), client.jsonArrLen("foobar", arrPath)); + + // ignore non-array + Path2 strPath = Path2.of(".foo"); + assertEquals(0L, client.jsonClear("foobar", strPath)); + assertJsonArrayEquals(singletonJSONArray("bar"), client.jsonGet("foobar", strPath)); + } + + @Test + public void clearObject() { + Baz baz = new Baz("quuz", "grault", "waldo"); + Qux qux = new Qux("quux", "corge", "garply", baz); + + client.jsonSet("qux", gson.toJson(qux)); + Path2 objPath = Path2.of(".baz"); +// assertEquals(baz, client.jsonGet("qux", objPath)); + + assertEquals(1L, client.jsonClear("qux", objPath)); +// assertEquals(new Baz(null, null, null), client.jsonGet("qux", objPath)); + assertJsonArrayEquals(singletonJSONArray(new JSONObject()), client.jsonGet("qux", objPath)); + } + + @Test + public void arrAppendSameType() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + client.jsonSet("test_arrappend", ROOT_PATH, new JSONObject(json)); + assertEquals(singletonList(6L), client.jsonArrAppend("test_arrappend", Path2.of(".b"), 4, 5, 6)); + + assertJsonArrayEquals(singletonJSONArray(new JSONArray(new Integer[]{1, 2, 3, 4, 5, 6})), + client.jsonGet("test_arrappend", Path2.of(".b"))); + } + + @Test + public void arrAppendMultipleTypes() { + Object fooObject = gson.toJson("foo"); + Object trueObject = gson.toJson(true); + Object nullObject = gson.toJson(null); + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + client.jsonSet("test_arrappend", ROOT_PATH, new JSONObject(json)); + assertEquals(singletonList(6L), client.jsonArrAppend("test_arrappend", Path2.of(".b"), fooObject, trueObject, nullObject)); + + assertJsonArrayEquals(singletonJSONArray(new JSONArray(new Object[]{1, 2, 3, "foo", true, null})), + client.jsonGet("test_arrappend", Path2.of(".b"))); + } + + @Test + public void arrAppendMultipleTypesWithDeepPath() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + client.jsonSet("test_arrappend", ROOT_PATH, new JSONObject(json)); + assertEquals(singletonList(4L), client.jsonArrAppendWithEscape("test_arrappend", Path2.of(".c.d"), "foo", true, null)); + + assertJsonArrayEquals(singletonJSONArray(new JSONArray(new Object[]{"ello", "foo", true, null})), + client.jsonGet("test_arrappend", Path2.of(".c.d"))); + } + + @Test + public void arrAppendAgaintsEmptyArray() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: [] }}"; + client.jsonSet("test_arrappend", ROOT_PATH, new JSONObject(json)); + assertEquals(singletonList(3L), client.jsonArrAppendWithEscape("test_arrappend", Path2.of(".c.d"), "a", "b", "c")); + + assertJsonArrayEquals(singletonJSONArray(new JSONArray(new String[]{"a", "b", "c"})), + client.jsonGet("test_arrappend", Path2.of(".c.d"))); + } + + @Test + public void arrAppendPathIsNotArray() { + String json = "{ a: 'hello', b: [1, 2, 3], c: { d: ['ello'] }}"; + client.jsonSet("test_arrappend", ROOT_PATH, new JSONObject(json)); + assertEquals(singletonList(null), client.jsonArrAppend("test_arrappend", Path2.of(".a"), 1)); + assertEquals(singletonList(null), client.jsonArrAppend("test_arrappend", Path2.of(".a"), gson.toJson(1))); + assertEquals(singletonList(null), client.jsonArrAppendWithEscape("test_arrappend", Path2.of(".a"), 1)); + } + + @Test(expected = JedisDataException.class) + public void arrIndexAbsentKey() { + client.jsonArrIndexWithEscape("quxquux", ROOT_PATH, new JSONObject()); + } + + @Test + public void arrIndexWithInts() { + client.jsonSetWithEscape("quxquux", ROOT_PATH, new int[]{8, 6, 7, 5, 3, 0, 9}); + assertEquals(singletonList(2L), client.jsonArrIndexWithEscape("quxquux", ROOT_PATH, 7)); + assertEquals(singletonList(-1L), client.jsonArrIndexWithEscape("quxquux", ROOT_PATH, "7")); + } + + @Test + public void arrIndexWithStrings() { + client.jsonSetWithEscape("quxquux", ROOT_PATH, new String[]{"8", "6", "7", "5", "3", "0", "9"}); + assertEquals(singletonList(2L), client.jsonArrIndexWithEscape("quxquux", ROOT_PATH, "7")); + } + + @Test + public void arrIndexWithStringsAndPath() { + client.jsonSetWithEscape("foobar", ROOT_PATH, new FooBarObject()); + assertEquals(singletonList(1L), client.jsonArrIndexWithEscape("foobar", Path2.of(".fooArr"), "b")); + } + + @Test + public void arrIndexNonExistentPath() { + client.jsonSet("foobar", ROOT_PATH, gson.toJson(new FooBarObject())); + assertEquals(emptyList(), client.jsonArrIndex("foobar", Path2.of(".barArr"), gson.toJson("x"))); + } + + @Test + public void arrInsert() { + String json = "['hello', 'world', true, 1, 3, null, false]"; + client.jsonSet("test_arrinsert", ROOT_PATH, new JSONArray(json)); + assertEquals(singletonList(8L), client.jsonArrInsertWithEscape("test_arrinsert", ROOT_PATH, 1, "foo")); + + assertJsonArrayEquals(singletonJSONArray(new JSONArray(new Object[]{"hello", "foo", "world", true, 1, 3, null, false})), + client.jsonGet("test_arrinsert", ROOT_PATH)); + } + + @Test + public void arrInsertWithNegativeIndex() { + String json = "['hello', 'world', true, 1, 3, null, false]"; + client.jsonSet("test_arrinsert", ROOT_PATH, new JSONArray(json)); + assertEquals(singletonList(8L), client.jsonArrInsertWithEscape("test_arrinsert", ROOT_PATH, -1, "foo")); + + assertJsonArrayEquals(singletonJSONArray(new JSONArray(Arrays.asList("hello", "world", true, 1, 3, null, "foo", false))), + client.jsonGet("test_arrinsert", ROOT_PATH)); + } + + @Test + public void arrPop() { + client.jsonSet("arr", ROOT_PATH, new JSONArray(new int[]{0, 1, 2, 3, 4})); + assertEquals(singletonList(4d), client.jsonArrPop("arr", ROOT_PATH)); + assertEquals(singletonList(3d), client.jsonArrPop("arr", ROOT_PATH, -1)); + assertEquals(singletonList(0d), client.jsonArrPop("arr", ROOT_PATH, 0)); + } + + @Test + public void arrTrim() { +// client.jsonSet("arr", ROOT_PATH, new int[]{0, 1, 2, 3, 4}); + client.jsonSet("arr", ROOT_PATH, new JSONArray(Arrays.asList(0, 1, 2, 3, 4))); + assertEquals(singletonList(3L), client.jsonArrTrim("arr", ROOT_PATH, 1, 3)); +// assertArrayEquals(new Integer[]{1, 2, 3}, client.jsonGet("arr", Integer[].class, ROOT_PATH)); + assertJsonArrayEquals(singletonJSONArray(new JSONArray(new int[]{1, 2, 3})), client.jsonGet("arr", ROOT_PATH)); + } + + @Test + public void strAppend() { +// client.jsonSet("str", ROOT_PATH, "foo"); + client.jsonSet("str", ROOT_PATH, gson.toJson("foo")); + assertEquals(singletonList(6L), client.jsonStrAppend("str", ROOT_PATH, "bar")); + assertEquals("foobar", client.jsonGet("str")); + } + + @Test + public void strLen() { + client.jsonSetWithEscape("str", "foobar"); + assertEquals(singletonList(6L), client.jsonStrLen("str", ROOT_PATH)); + } + + private void assertJsonArrayEquals(JSONArray a, Object _b) { + if (!(_b instanceof JSONArray)) { + fail("Actual value is not JSONArray."); + } + JSONArray b = (JSONArray) _b; + assertEquals("JSONArray length mismatch", a.length(), b.length()); + int length = a.length(); + for (int index = 0; index < length; index++) { + if (a.isNull(index)) { + assertTrue(index + "'th element is not null", b.isNull(index)); + continue; + } + Object ia = a.get(index); + Object ib = b.get(index); + if (ia instanceof JSONArray) { + assertJsonArrayEquals((JSONArray) ia, ib); + } else if (ia instanceof JSONObject) { + assertJsonObjectEquals((JSONObject) ia, ib); + } else { + assertEquals(index + "'th element mismatch", ia, ib); + } + } + } + + private void assertJsonObjectEquals(JSONObject a, Object _b) { + if (!(_b instanceof JSONObject)) { + fail("Actual value is not JSONObject."); + } + JSONObject b = (JSONObject) _b; + assertEquals("JSONObject length mismatch", a.length(), b.length()); + assertEquals(a.keySet(), b.keySet()); + for (String key : a.keySet()) { + if (a.isNull(key)) { + assertTrue(key + "'s value is not null", b.isNull(key)); + continue; + } + Object oa = a.get(key); + Object ob = b.get(key); + if (oa instanceof JSONArray) { + assertJsonArrayEquals((JSONArray) oa, ob); + } else if (oa instanceof JSONObject) { + assertJsonObjectEquals((JSONObject) oa, ob); + } else { + assertEquals(key + "'s value mismatch", oa, ob); + } + } + } + + private static JSONArray singletonJSONArray(Object o) { + JSONArray arr = new JSONArray(); + arr.put(o); + return arr; + } +} diff --git a/src/test/java/redis/clients/jedis/modules/search/AggregationBuilderTest.java b/src/test/java/redis/clients/jedis/modules/search/AggregationBuilderTest.java new file mode 100644 index 0000000000..d7742be1ba --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/AggregationBuilderTest.java @@ -0,0 +1,244 @@ +package redis.clients.jedis.modules.search; + +import redis.clients.jedis.exceptions.JedisDataException; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.Assert.*; +import redis.clients.jedis.search.Document; +import redis.clients.jedis.search.FieldName; +import redis.clients.jedis.search.IndexOptions; +import redis.clients.jedis.search.Schema; +import redis.clients.jedis.search.aggr.AggregationBuilder; +import redis.clients.jedis.search.aggr.AggregationResult; +import redis.clients.jedis.search.aggr.Reducers; +import redis.clients.jedis.search.aggr.Row; +import redis.clients.jedis.search.aggr.SortedField; +import redis.clients.jedis.modules.RedisModuleCommandsTestBase; + +public class AggregationBuilderTest extends RedisModuleCommandsTestBase { + + private static final String index = "aggbindex"; + + @BeforeClass + public static void prepare() { + RedisModuleCommandsTestBase.prepare(); + } + + @AfterClass + public static void tearDown() { +// RedisModuleCommandsTestBase.tearDown(); + } + + private void addDocument(Document doc) { + String key = doc.getId(); + Map map = new LinkedHashMap<>(); + doc.getProperties().forEach(entry -> map.put(entry.getKey(), String.valueOf(entry.getValue()))); + client.hset(key, map); + } + + private void addDocument(String key, Map objMap) { + Map strMap = new HashMap<>(); + objMap.entrySet().forEach(entry -> strMap.put(entry.getKey(), String.valueOf(entry.getValue()))); + client.hset(key, strMap); + } + + @Test + public void testAggregations() { + Schema sc = new Schema(); + sc.addSortableTextField("name", 1.0); + sc.addSortableNumericField("count"); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); +// client.addDocument(new Document("data1").set("name", "abc").set("count", 10)); +// client.addDocument(new Document("data2").set("name", "def").set("count", 5)); +// client.addDocument(new Document("data3").set("name", "def").set("count", 25)); + addDocument(new Document("data1").set("name", "abc").set("count", 10)); + addDocument(new Document("data2").set("name", "def").set("count", 5)); + addDocument(new Document("data3").set("name", "def").set("count", 25)); + + AggregationBuilder r = new AggregationBuilder() + .groupBy("@name", Reducers.sum("@count").as("sum")) + .sortBy(10, SortedField.desc("@sum")); + + // actual search + AggregationResult res = client.ftAggregate(index, r); + assertEquals(2, res.totalResults); + + Row r1 = res.getRow(0); + assertNotNull(r1); + assertEquals("def", r1.getString("name")); + assertEquals(30, r1.getLong("sum")); + assertEquals(30., r1.getDouble("sum"), 0); + + assertEquals(0L, r1.getLong("nosuchcol")); + assertEquals(0.0, r1.getDouble("nosuchcol"), 0); + assertEquals("", r1.getString("nosuchcol")); + + Row r2 = res.getRow(1); + assertNotNull(r2); + assertEquals("abc", r2.getString("name")); + assertEquals(10, r2.getLong("sum")); + } + + @Test + public void testApplyAndFilterAggregations() { + Schema sc = new Schema(); + sc.addSortableTextField("name", 1.0); + sc.addSortableNumericField("subj1"); + sc.addSortableNumericField("subj2"); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); +// client.addDocument(new Document("data1").set("name", "abc").set("subj1", 20).set("subj2", 70)); +// client.addDocument(new Document("data2").set("name", "def").set("subj1", 60).set("subj2", 40)); +// client.addDocument(new Document("data3").set("name", "ghi").set("subj1", 50).set("subj2", 80)); +// client.addDocument(new Document("data4").set("name", "abc").set("subj1", 30).set("subj2", 20)); +// client.addDocument(new Document("data5").set("name", "def").set("subj1", 65).set("subj2", 45)); +// client.addDocument(new Document("data6").set("name", "ghi").set("subj1", 70).set("subj2", 70)); + addDocument(new Document("data1").set("name", "abc").set("subj1", 20).set("subj2", 70)); + addDocument(new Document("data2").set("name", "def").set("subj1", 60).set("subj2", 40)); + addDocument(new Document("data3").set("name", "ghi").set("subj1", 50).set("subj2", 80)); + addDocument(new Document("data4").set("name", "abc").set("subj1", 30).set("subj2", 20)); + addDocument(new Document("data5").set("name", "def").set("subj1", 65).set("subj2", 45)); + addDocument(new Document("data6").set("name", "ghi").set("subj1", 70).set("subj2", 70)); + + AggregationBuilder r = new AggregationBuilder().apply("(@subj1+@subj2)/2", "attemptavg") + .groupBy("@name", Reducers.avg("@attemptavg").as("avgscore")) + .filter("@avgscore>=50") + .sortBy(10, SortedField.asc("@name")); + + // actual search + AggregationResult res = client.ftAggregate(index, r); + assertEquals(3, res.totalResults); + + Row r1 = res.getRow(0); + assertNotNull(r1); + assertEquals("def", r1.getString("name")); + assertEquals(52.5, r1.getDouble("avgscore"), 0); + + Row r2 = res.getRow(1); + assertNotNull(r2); + assertEquals("ghi", r2.getString("name")); + assertEquals(67.5, r2.getDouble("avgscore"), 0); + } + + @Test + public void testLoadAsAggregations() { + Schema sc = new Schema(); + sc.addSortableTextField("name", 1.0); + sc.addSortableNumericField("subj1"); + sc.addSortableNumericField("subj2"); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); +// client.addDocument(new Document("data1").set("name", "abc").set("subj1", 20).set("subj2", 70)); +// client.addDocument(new Document("data2").set("name", "def").set("subj1", 60).set("subj2", 40)); + addDocument(new Document("data1").set("name", "abc").set("subj1", 20).set("subj2", 70)); + addDocument(new Document("data2").set("name", "def").set("subj1", 60).set("subj2", 40)); + + AggregationBuilder builder = new AggregationBuilder() + .load(FieldName.of("@subj1").as("a"), FieldName.of("@subj2").as("b")) + .apply("(@a+@b)/2", "avg").sortByDesc("@avg"); + + AggregationResult result = client.ftAggregate(index, builder); + assertEquals(50.0, result.getRow(0).getDouble("avg"), 0d); + assertEquals(45.0, result.getRow(1).getDouble("avg"), 0d); + } + + @Test + public void testCursor() throws InterruptedException { + Schema sc = new Schema(); + sc.addSortableTextField("name", 1.0); + sc.addSortableNumericField("count"); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); +// client.addDocument(new Document("data1").set("name", "abc").set("count", 10)); +// client.addDocument(new Document("data2").set("name", "def").set("count", 5)); +// client.addDocument(new Document("data3").set("name", "def").set("count", 25)); + addDocument(new Document("data1").set("name", "abc").set("count", 10)); + addDocument(new Document("data2").set("name", "def").set("count", 5)); + addDocument(new Document("data3").set("name", "def").set("count", 25)); + + AggregationBuilder r = new AggregationBuilder() + .groupBy("@name", Reducers.sum("@count").as("sum")) + .sortBy(10, SortedField.desc("@sum")) + .cursor(1, 3000); + + // actual search + AggregationResult res = client.ftAggregate(index, r); + assertEquals(2, res.totalResults); + + Row row = res.getRow(0); + assertNotNull(row); + assertEquals("def", row.getString("name")); + assertEquals(30, row.getLong("sum")); + assertEquals(30., row.getDouble("sum"), 0); + + assertEquals(0L, row.getLong("nosuchcol")); + assertEquals(0.0, row.getDouble("nosuchcol"), 0); + assertEquals("", row.getString("nosuchcol")); + + res = client.ftCursorRead(index, res.getCursorId(), 1); + Row row2 = res.getRow(0); + assertNotNull(row2); + assertEquals("abc", row2.getString("name")); + assertEquals(10, row2.getLong("sum")); + + assertEquals("OK", client.ftCursorDel(index, res.getCursorId())); + + try { + client.ftCursorRead(index, res.getCursorId(), 1); + fail(); + } catch (JedisDataException e) { + } + + AggregationBuilder r2 = new AggregationBuilder() + .groupBy("@name", Reducers.sum("@count").as("sum")) + .sortBy(10, SortedField.desc("@sum")) + .cursor(1, 1000); + + Thread.sleep(1000); + + try { + client.ftCursorRead(index, res.getCursorId(), 1); + fail(); + } catch (JedisDataException e) { + } + } + + @Test + public void testWrongAggregation() throws InterruptedException { + Schema sc = new Schema() + .addTextField("title", 5.0) + .addTextField("body", 1.0) + .addTextField("state", 1.0) + .addNumericField("price"); + + client.ftCreate(index, IndexOptions.defaultOptions(), sc); + + // insert document(s) + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + fields.put("state", "NY"); + fields.put("body", "lorem ipsum"); + fields.put("price", "1337"); +// client.addDocument("doc1", fields); + addDocument("doc1", fields); + + // wrong aggregation query + AggregationBuilder builder = new AggregationBuilder("hello") + .apply("@price/1000", "k") + .groupBy("@state", Reducers.avg("@k").as("avgprice")) + .filter("@avgprice>=2") + .sortBy(10, SortedField.asc("@state")); + + try { + client.ftAggregate(index, builder); + fail(); + } catch (JedisDataException e) { + // should throw JedisDataException on wrong aggregation query + } + + } +} diff --git a/src/test/java/redis/clients/jedis/modules/search/CreateTest.java b/src/test/java/redis/clients/jedis/modules/search/CreateTest.java new file mode 100644 index 0000000000..64aee4d035 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/CreateTest.java @@ -0,0 +1,70 @@ +//package redis.clients.jedis.modules.search; +// +//import static org.junit.Assert.*; +// +//import java.util.ArrayList; +//import java.util.Arrays; +//import java.util.List; +//import org.junit.Test; +// +//import redis.clients.jedis.search.IndexDefinition; +//import redis.clients.jedis.search.IndexOptions; +// +//public class CreateTest { +// +// @Test +// public void defaultOptions() throws Exception { +// IndexOptions defaultOptions = IndexOptions.defaultOptions(); +// List arrayList = new ArrayList<>(); +// defaultOptions.serializeRedisArgs(arrayList); +// +// assertEquals(Arrays.asList(), arrayList); +// } +// +// @Test +// public void allOptions() throws Exception { +// IndexOptions defaultOptions = new Client.IndexOptions(0); +// +// defaultOptions.setStopwords("stop", "run"); +// defaultOptions.setTemporary(1234L); +// defaultOptions.setDefinition(new IndexDefinition()); +// +// List arrayList = new ArrayList<>(); +// defaultOptions.serializeRedisArgs(arrayList); +// +// assertEquals( +// Arrays.asList("NOOFFSETS", "NOFIELDS", "NOFREQS", "TEMPORARY", "1234", "STOPWORDS", "2", "stop", "run"), +// arrayList); +// } +// +// @Test +// public void allIndexDefinition() throws Exception { +// IndexDefinition indexRule = new IndexDefinition(IndexDefinition.Type.HASH); +// +// indexRule.setAsync(true); +// indexRule.setFilter("@sum<30"); +// indexRule.setLanguage("FR"); +// indexRule.setLanguageField("myLanguage"); +// indexRule.setPayloadField("myPayload"); +// indexRule.setPrefixes("person:"); +// indexRule.setScore(0.818656); +// indexRule.setScoreFiled("myScore"); +// +// List arrayList = new ArrayList<>(); +// indexRule.serializeRedisArgs(arrayList); +// +// assertEquals(Arrays.asList("ON", "HASH", "ASYNC", "PREFIX", "1", "person:", "FILTER", "@sum<30", "LANGUAGE_FIELD", +// "myLanguage", "LANGUAGE", "FR", "SCORE_FIELD", "myScore", "SCORE", "0.818656", "PAYLOAD_FIELD", "myPayload"), +// arrayList); +// +// assertEquals(true, indexRule.isAsync()); +// assertEquals("@sum<30", indexRule.getFilter()); +// assertEquals("FR", indexRule.getLanguage()); +// assertEquals("myLanguage", indexRule.getLanguageField()); +// assertEquals("myPayload", indexRule.getPayloadField()); +// assertArrayEquals(new String[]{"person:"}, indexRule.getPrefixes()); +// assertEquals(0.818656, indexRule.getScore(), 0.0); +// assertEquals("myScore", indexRule.getScoreFiled()); +// assertEquals(IndexDefinition.Type.HASH, indexRule.getType()); +// } +//} diff --git a/src/test/java/redis/clients/jedis/modules/search/DocumentTest.java b/src/test/java/redis/clients/jedis/modules/search/DocumentTest.java new file mode 100644 index 0000000000..6e02235fca --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/DocumentTest.java @@ -0,0 +1,49 @@ +package redis.clients.jedis.modules.search; + +import static org.junit.Assert.assertArrayEquals; +import static org.junit.Assert.assertEquals; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.HashMap; +import java.util.Map; +import org.junit.Test; +import redis.clients.jedis.search.Document; +import redis.clients.jedis.util.SafeEncoder; + +public class DocumentTest { + + @Test + public void serialize() throws IOException, ClassNotFoundException { + String id = "9f"; + double score = 10d; + Map map = new HashMap<>(); + map.put("string", "c"); + map.put("float", 12d); + byte[] payload = "1a".getBytes(); + Document document = new Document(id, map, score, payload); + + ByteArrayOutputStream aos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(aos); + oos.writeObject(document); + oos.flush(); + oos.close(); + + ByteArrayInputStream ais = new ByteArrayInputStream(aos.toByteArray()); + ObjectInputStream ois = new ObjectInputStream(ais); + Document read = (Document) ois.readObject(); + ois.close(); + + assertEquals(id, read.getId()); + assertEquals(score, read.getScore(), 0d); + assertArrayEquals(payload, read.getPayload()); + String exp = String.format("id:%s, score: %.1f, payload:%s, properties:%s", + id, score, SafeEncoder.encode(payload), "[string=c, float=12.0]") ; + assertEquals(exp, read.toString()); + assertEquals("c", read.getString("string")); + assertEquals(Double.valueOf(12d), read.get("float")); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/search/JsonSearchTest.java b/src/test/java/redis/clients/jedis/modules/search/JsonSearchTest.java new file mode 100644 index 0000000000..83145db0cb --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/JsonSearchTest.java @@ -0,0 +1,225 @@ +package redis.clients.jedis.modules.search; + +import static org.junit.Assert.*; + +import org.json.JSONObject; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; +import redis.clients.jedis.BuilderFactory; +import redis.clients.jedis.CommandArguments; +import redis.clients.jedis.CommandObject; + +import redis.clients.jedis.json.JsonProtocol; +import redis.clients.jedis.json.Path2; +import redis.clients.jedis.search.*; +import redis.clients.jedis.search.Schema.*; +import redis.clients.jedis.search.SearchResult; +import redis.clients.jedis.modules.RedisModuleCommandsTestBase; + +public class JsonSearchTest extends RedisModuleCommandsTestBase { + + public static final String JSON_ROOT = "$"; + + private static final String index = "json-index"; + + @BeforeClass + public static void prepare() { + RedisModuleCommandsTestBase.prepare(); + } + + @AfterClass + public static void tearDown() { +// RedisModuleCommandsTestBase.tearDown(); + } + + private void setJson(String key, JSONObject json) { + CommandObject command = new CommandObject<>( + new CommandArguments(JsonProtocol.JsonCommand.SET).key(key).add(Path2.ROOT_PATH).add(json), + BuilderFactory.STRING); + client.executeCommand(command); + } + + private JSONObject toJson(Object... values) { + JSONObject json = new JSONObject(); + for (int i = 0; i < values.length; i += 2) { + json.put((String) values[i], values[i + 1]); + } + return json; + } + + @Test + public void create() { + Schema schema = new Schema().addTextField("$.first", 1.0).addTextField("$.last", 1.0) + .addNumericField("$.age"); + IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON) + .setPrefixes(new String[]{"student:", "pupil:"}); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), schema)); + +// try (Jedis jedis = client.connection()) { +// setJson(jedis, "profesor:5555", toJson("first", "Albert", "last", "Blue", "age", 55)); +// setJson(jedis, "student:1111", toJson("first", "Joe", "last", "Dod", "age", 18)); +// setJson(jedis, "pupil:2222", toJson("first", "Jen", "last", "Rod", "age", 14)); +// setJson(jedis, "student:3333", toJson("first", "El", "last", "Mark", "age", 17)); +// setJson(jedis, "pupil:4444", toJson("first", "Pat", "last", "Shu", "age", 21)); +// setJson(jedis, "student:5555", toJson("first", "Joen", "last", "Ko", "age", 20)); +// setJson(jedis, "teacher:6666", toJson("first", "Pat", "last", "Rod", "age", 20)); +// } + setJson("profesor:5555", toJson("first", "Albert", "last", "Blue", "age", 55)); + setJson("student:1111", toJson("first", "Joe", "last", "Dod", "age", 18)); + setJson("pupil:2222", toJson("first", "Jen", "last", "Rod", "age", 14)); + setJson("student:3333", toJson("first", "El", "last", "Mark", "age", 17)); + setJson("pupil:4444", toJson("first", "Pat", "last", "Shu", "age", 21)); + setJson("student:5555", toJson("first", "Joen", "last", "Ko", "age", 20)); + setJson("teacher:6666", toJson("first", "Pat", "last", "Rod", "age", 20)); + + SearchResult noFilters = client.ftSearch(index, new Query()); + assertEquals(5, noFilters.getTotalResults()); + + SearchResult res1 = client.ftSearch(index, new Query("@\\$\\.first:Jo*")); + assertEquals(2, res1.getTotalResults()); + + SearchResult res2 = client.ftSearch(index, new Query("@\\$\\.first:Pat")); + assertEquals(1, res2.getTotalResults()); + } + + @Test + public void createWithFieldNames() { + Schema schema = new Schema() + .addField(new TextField(FieldName.of("$.first").as("first"))) + .addField(new TextField(FieldName.of("$.last"))) + .addField(new Field(FieldName.of("$.age").as("age"), FieldType.NUMERIC)); + IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON) + .setPrefixes(new String[]{"student:", "pupil:"}); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), schema)); + +// try (Jedis jedis = client.connection()) { +// setJson(jedis, "profesor:5555", toJson("first", "Albert", "last", "Blue", "age", 55)); +// setJson(jedis, "student:1111", toJson("first", "Joe", "last", "Dod", "age", 18)); +// setJson(jedis, "pupil:2222", toJson("first", "Jen", "last", "Rod", "age", 14)); +// setJson(jedis, "student:3333", toJson("first", "El", "last", "Mark", "age", 17)); +// setJson(jedis, "pupil:4444", toJson("first", "Pat", "last", "Shu", "age", 21)); +// setJson(jedis, "student:5555", toJson("first", "Joen", "last", "Ko", "age", 20)); +// setJson(jedis, "teacher:6666", toJson("first", "Pat", "last", "Rod", "age", 20)); +// } + setJson("profesor:5555", toJson("first", "Albert", "last", "Blue", "age", 55)); + setJson("student:1111", toJson("first", "Joe", "last", "Dod", "age", 18)); + setJson("pupil:2222", toJson("first", "Jen", "last", "Rod", "age", 14)); + setJson("student:3333", toJson("first", "El", "last", "Mark", "age", 17)); + setJson("pupil:4444", toJson("first", "Pat", "last", "Shu", "age", 21)); + setJson("student:5555", toJson("first", "Joen", "last", "Ko", "age", 20)); + setJson("teacher:6666", toJson("first", "Pat", "last", "Rod", "age", 20)); + + SearchResult noFilters = client.ftSearch(index, new Query()); + assertEquals(5, noFilters.getTotalResults()); + + SearchResult asOriginal = client.ftSearch(index, new Query("@\\$\\.first:Jo*")); + assertEquals(0, asOriginal.getTotalResults()); + + SearchResult asAttribute = client.ftSearch(index, new Query("@first:Jo*")); + assertEquals(2, asAttribute.getTotalResults()); + + SearchResult nonAttribute = client.ftSearch(index, new Query("@\\$\\.last:Rod")); + assertEquals(1, nonAttribute.getTotalResults()); + } + + @Test + public void parseJson() { + Schema schema = new Schema(); + IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), schema)); + + String id = "student:1111"; + JSONObject json = toJson("first", "Joe", "last", "Dod", "age", 18); +// try (Jedis jedis = client.connection()) { +// setJson(jedis, id, json); +// } + setJson(id, json); + + // query + SearchResult sr = client.ftSearch(index, new Query().setWithScores().setWithPayload()); + assertEquals(1, sr.getTotalResults()); + + Document doc = sr.getDocuments().get(0); + assertEquals(Double.POSITIVE_INFINITY, doc.getScore(), 0); + assertNull(doc.getPayload()); + assertEquals(json.toString(), doc.get(JSON_ROOT)); + + // query repeat + sr = client.ftSearch(index, new Query().setWithScores().setWithPayload()); + + doc = sr.getDocuments().get(0); + JSONObject jsonRead = new JSONObject((String) doc.get(JSON_ROOT)); + assertEquals(json.toString(), jsonRead.toString()); + + // query repeat + sr = client.ftSearch(index, new Query().setWithScores().setWithPayload()); + + doc = sr.getDocuments().get(0); + jsonRead = new JSONObject(doc.getString(JSON_ROOT)); + assertEquals(json.toString(), jsonRead.toString()); + } + + @Test + public void parseJsonPartial() { + Schema schema = new Schema(); + IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), schema)); + + String id = "student:1111"; + JSONObject json = toJson("first", "Joe", "last", "Dod", "age", 18); +// try (Jedis jedis = client.connection()) { +// setJson(jedis, id, json); +// } + setJson(id, json); + + // query + SearchResult sr = client.ftSearch(index, new Query().returnFields("$.first", "$.last", "$.age")); + assertEquals(1, sr.getTotalResults()); + + Document doc = sr.getDocuments().get(0); + assertEquals("Joe", doc.get("$.first")); + assertEquals("Dod", doc.get("$.last")); + assertEquals(Integer.toString(18), doc.get("$.age")); + + // query repeat + sr = client.ftSearch(index, new Query().returnFields("$.first", "$.last", "$.age")); + + doc = sr.getDocuments().get(0); + assertEquals("Joe", doc.getString("$.first")); + assertEquals("Dod", doc.getString("$.last")); + assertEquals(18, Integer.parseInt((String) doc.get("$.age"))); + } + + @Test + public void parseJsonPartialWithFieldNames() { + Schema schema = new Schema(); + IndexDefinition rule = new IndexDefinition(IndexDefinition.Type.JSON); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), schema)); + + String id = "student:1111"; + JSONObject json = toJson("first", "Joe", "last", "Dod", "age", 18); +// try (Jedis jedis = client.connection()) { +// setJson(jedis, id, json); +// } + setJson(id, json); + + // query + SearchResult sr = client.ftSearch(index, new Query().returnFields(FieldName.of("$.first").as("first"), + FieldName.of("$.last").as("last"), FieldName.of("$.age"))); + assertEquals(1, sr.getTotalResults()); + + Document doc = sr.getDocuments().get(0); + assertNull(doc.get("$.first")); + assertNull(doc.get("$.last")); + assertEquals(Integer.toString(18), doc.get("$.age")); + assertEquals("Joe", doc.get("first")); + assertEquals("Dod", doc.get("last")); + assertNull(doc.get("age")); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/search/QueryTest.java b/src/test/java/redis/clients/jedis/modules/search/QueryTest.java new file mode 100644 index 0000000000..738f2c3385 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/QueryTest.java @@ -0,0 +1,153 @@ +//package redis.clients.jedis.modules.search; +// +//import static org.junit.Assert.*; +// +//import java.util.ArrayList; +//import org.junit.Before; +//import org.junit.Test; +//import redis.clients.jedis.search.Query; +// +//public class QueryTest { +// +// Query query; +// +// @Before +// public void setUp() throws Exception { +// query = new Query("hello world"); +// } +// +// @Test +// public void getNoContent() throws Exception { +// assertFalse(query.getNoContent()); +// assertEquals(query, query.setNoContent()); +// assertTrue(query.getNoContent()); +// } +// +// @Test +// public void getWithScores() throws Exception { +// assertFalse(query.getWithScores()); +// assertEquals(query, query.setWithScores()); +// assertTrue(query.getWithScores()); +// } +// +// @Test +// public void serializeRedisArgs() throws Exception { +// query.setNoContent().setLanguage("xx").setNoStopwords().setVerbatim().setWithPayload().setWithScores().setScorer("My.Scorer"); +// +// ArrayList args = new ArrayList<>(1); +// query.serializeRedisArgs(args); +// +// assertEquals(10, args.size()); +// assertEquals(query._queryString, new String(args.get(0))); +//// assertTrue(args.contains("xx".getBytes())); +//// assertTrue(args.contains("NOSTOPWORDS".getBytes())); +//// assertTrue(args.contains("VERBATIM".getBytes())); +//// assertTrue(args.contains("PAYLOADS".getBytes())); +//// assertTrue(args.contains("WITHSCORES".getBytes())); +// } +// +// @Test +// public void limit() throws Exception { +// assertEquals(0, query._paging.offset); +// assertEquals(10, query._paging.num); +// assertEquals(query, query.limit(1, 30)); +// assertEquals(1, query._paging.offset); +// assertEquals(30, query._paging.num); +// +// } +// +// @Test +// public void addFilter() throws Exception { +// assertEquals(0, query._filters.size()); +// Query.NumericFilter f = new Query.NumericFilter("foo", 0, 100); +// assertEquals(query, query.addFilter(f)); +// assertEquals(f, query._filters.get(0)); +// } +// +// @Test +// public void setVerbatim() throws Exception { +// assertFalse(query._verbatim); +// assertEquals(query, query.setVerbatim()); +// assertTrue(query._verbatim); +// } +// +// @Test +// public void setNoStopwords() throws Exception { +// assertFalse(query._noStopwords); +// assertEquals(query, query.setNoStopwords()); +// assertTrue(query._noStopwords); +// +// } +// +// @Test +// public void setLanguage() throws Exception { +// assertEquals(null, query._language); +// assertEquals(query, query.setLanguage("chinese")); +// assertEquals("chinese", query._language); +// } +// +// @Test +// public void setScorer() throws Exception { +// assertEquals(null, query._scorer); +// assertEquals(query, query.setScorer("the.scroer")); +// assertEquals("the.scroer", query._scorer); +// } +// +// @Test +// public void limitFields() throws Exception { +// assertNull(query._fields); +// assertEquals(query, query.limitFields("foo", "bar")); +// assertEquals(2, query._fields.length); +// } +// +// @Test +// public void returnFields() throws Exception { +// assertNull(query._returnFields); +// assertEquals(query, query.returnFields("foo", "bar")); +// assertEquals(2, query._returnFields.length); +// } +// +// @Test +// public void highlightFields() throws Exception { +// assertEquals(false, query.wantsHighlight); +// assertNull(query.highlightFields); +// +// query = new Query("Hello"); +// assertEquals(query, query.highlightFields("foo", "bar")); +// assertEquals(2, query.highlightFields.length); +// assertNull(query.highlightTags); +// assertEquals(true, query.wantsHighlight); +// +// query = new Query("Hello").highlightFields(); +// assertNull(query.highlightFields); +// assertNull(query.highlightTags); +// assertEquals(true, query.wantsHighlight); +// +// assertEquals(query, query.highlightFields(new Query.HighlightTags("", ""))); +// assertNull(query.highlightFields); +// assertEquals(2, query.highlightTags.length); +// assertEquals("", query.highlightTags[0]); +// assertEquals("", query.highlightTags[1]); +// } +// +// @Test +// public void summarizeFields() throws Exception { +// assertEquals(false, query.wantsSummarize); +// assertNull(query.summarizeFields); +// +// query = new Query("Hello"); +// assertEquals(query, query.summarizeFields()); +// assertEquals(true, query.wantsSummarize); +// assertNull(query.summarizeFields); +// assertEquals(-1, query.summarizeFragmentLen); +// assertEquals(-1, query.summarizeNumFragments); +// +// query = new Query("Hello"); +// assertEquals(query, query.summarizeFields("someField")); +// assertEquals(true, query.wantsSummarize); +// assertEquals(1, query.summarizeFields.length); +// assertEquals(-1, query.summarizeFragmentLen); +// assertEquals(-1, query.summarizeNumFragments); +// } +// +//} diff --git a/src/test/java/redis/clients/jedis/modules/search/SchemaTest.java b/src/test/java/redis/clients/jedis/modules/search/SchemaTest.java new file mode 100644 index 0000000000..091ed9940c --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/SchemaTest.java @@ -0,0 +1,31 @@ +package redis.clients.jedis.modules.search; + +import org.hamcrest.CoreMatchers; +import org.junit.Assert; +import org.junit.Test; +import redis.clients.jedis.search.Schema; + +public class SchemaTest { + + private final static String TITLE = "title"; + private final static String GENRE = "genre"; + private final static String VOTES = "votes"; + private final static String RATING = "rating"; + private final static String RELEASE_YEAR = "release_year"; + private final static String PLOT = "plot"; + + @Test + public void printSchemaTest() throws Exception { + Schema sc = new Schema() + .addTextField(TITLE, 5.0) + .addSortableTextField(PLOT, 1.0) + .addSortableTagField(GENRE, ",") + .addSortableNumericField(RELEASE_YEAR) + .addSortableNumericField(RATING) + .addSortableNumericField(VOTES); + + String schemaPrint = sc.toString(); + Assert.assertThat(schemaPrint, CoreMatchers.startsWith("Schema{fields=[TextField{name='title'")); + Assert.assertThat(schemaPrint, CoreMatchers.containsString("{name='release_year', type=NUMERIC, sortable=true, noindex=false}")); + } +} diff --git a/src/test/java/redis/clients/jedis/modules/search/SearchTest.java b/src/test/java/redis/clients/jedis/modules/search/SearchTest.java new file mode 100644 index 0000000000..a56f970575 --- /dev/null +++ b/src/test/java/redis/clients/jedis/modules/search/SearchTest.java @@ -0,0 +1,1300 @@ +package redis.clients.jedis.modules.search; + +import static org.junit.Assert.*; +import static redis.clients.jedis.search.RediSearchUtil.toStringMap; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import redis.clients.jedis.exceptions.JedisDataException; +import redis.clients.jedis.search.*; +import redis.clients.jedis.search.Schema.*; +import redis.clients.jedis.modules.RedisModuleCommandsTestBase; +import redis.clients.jedis.util.SafeEncoder; + +public class SearchTest extends RedisModuleCommandsTestBase { + + private static final String index = "testindex"; + + @BeforeClass + public static void prepare() { + RedisModuleCommandsTestBase.prepare(); + } + + @AfterClass + public static void tearDown() { +// RedisModuleCommandsTestBase.tearDown(); + } + + private void addDocument(String key, Map map) { + client.hset(key, toStringMap(map)); + } + + private static Map toMap(Object... values) { + Map map = new HashMap<>(); + for (int i = 0; i < values.length; i += 2) { + map.put((String) values[i], values[i + 1]); + } + return map; + } + + private static Map toMap(String... values) { + Map map = new HashMap<>(); + for (int i = 0; i < values.length; i += 2) { + map.put(values[i], values[i + 1]); + } + return map; + } + + @Test + public void creatDefinion() throws Exception { + Schema sc = new Schema().addTextField("first", 1.0).addTextField("last", 1.0).addNumericField("age"); + IndexDefinition rule = new IndexDefinition() + .setFilter("@age>16") + .setPrefixes(new String[]{"student:", "pupil:"}); + + try { + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), sc)); + } catch (JedisDataException e) { + // ON was only supported from RediSearch 2.0 + assertEquals("Unknown argument `ON`", e.getMessage()); + return; + } + + client.hset("profesor:5555", toMap("first", "Albert", "last", "Blue", "age", "55")); + client.hset("student:1111", toMap("first", "Joe", "last", "Dod", "age", "18")); + client.hset("pupil:2222", toMap("first", "Jen", "last", "Rod", "age", "14")); + client.hset("student:3333", toMap("first", "El", "last", "Mark", "age", "17")); + client.hset("pupil:4444", toMap("first", "Pat", "last", "Shu", "age", "21")); + client.hset("student:5555", toMap("first", "Joen", "last", "Ko", "age", "20")); + client.hset("teacher:6666", toMap("first", "Pat", "last", "Rod", "age", "20")); + + SearchResult noFilters = client.ftSearch(index, new Query()); + assertEquals(4, noFilters.getTotalResults()); + + SearchResult res1 = client.ftSearch(index, new Query("@first:Jo*")); + assertEquals(2, res1.getTotalResults()); + + SearchResult res2 = client.ftSearch(index, new Query("@first:Pat")); + assertEquals(1, res2.getTotalResults()); + + SearchResult res3 = client.ftSearch(index, new Query("@last:Rod")); + assertEquals(0, res3.getTotalResults()); + } + + @Test + public void withObjectMap() throws Exception { + Schema sc = new Schema().addTextField("first", 1.0).addTextField("last", 1.0).addNumericField("age"); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + addDocument("student:1111", toMap("first", "Joe", "last", "Dod", "age", 18)); + addDocument("student:3333", toMap("first", "El", "last", "Mark", "age", 17)); + addDocument("pupil:4444", toMap("first", "Pat", "last", "Shu", "age", 21)); + addDocument("student:5555", toMap("first", "Joen", "last", "Ko", "age", 20)); + + SearchResult noFilters = client.ftSearch(index, new Query()); + assertEquals(4, noFilters.getTotalResults()); + + SearchResult res1 = client.ftSearch(index, new Query("@first:Jo*")); + assertEquals(2, res1.getTotalResults()); + + SearchResult res2 = client.ftSearch(index, new Query("@first:Pat")); + assertEquals(1, res2.getTotalResults()); + + SearchResult res3 = client.ftSearch(index, new Query("@last:Rod")); + assertEquals(0, res3.getTotalResults()); + } + + @Test + public void createWithFieldNames() throws Exception { + Schema sc = new Schema().addField(new TextField(FieldName.of("first").as("given"))) + .addField(new TextField(FieldName.of("last"))); + IndexDefinition rule = new IndexDefinition() + //.setFilter("@age>16") + .setPrefixes(new String[]{"student:", "pupil:"}); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions().setDefinition(rule), sc)); + + client.hset("profesor:5555", toMap("first", "Albert", "last", "Blue", "age", "55")); + client.hset("student:1111", toMap("first", "Joe", "last", "Dod", "age", "18")); + client.hset("pupil:2222", toMap("first", "Jen", "last", "Rod", "age", "14")); + client.hset("student:3333", toMap("first", "El", "last", "Mark", "age", "17")); + client.hset("pupil:4444", toMap("first", "Pat", "last", "Shu", "age", "21")); + client.hset("student:5555", toMap("first", "Joen", "last", "Ko", "age", "20")); + client.hset("teacher:6666", toMap("first", "Pat", "last", "Rod", "age", "20")); + + SearchResult noFilters = client.ftSearch(index, new Query()); + assertEquals(5, noFilters.getTotalResults()); + + SearchResult asOriginal = client.ftSearch(index, new Query("@first:Jo*")); + assertEquals(0, asOriginal.getTotalResults()); + + SearchResult asAttribute = client.ftSearch(index, new Query("@given:Jo*")); + assertEquals(2, asAttribute.getTotalResults()); + + SearchResult nonAttribute = client.ftSearch(index, new Query("@last:Rod")); + assertEquals(1, nonAttribute.getTotalResults()); + } + + @Test + public void search() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0).addTextField("body", 1.0); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + fields.put("body", "lorem ipsum"); + for (int i = 0; i < 100; i++) { +// assertTrue(client.addDocument(String.format("doc%d", i), (double) i / 100.0, fields)); + addDocument(String.format("doc%d", i), fields); + } + + SearchResult res = client.ftSearch(index, new Query("hello world").limit(0, 5).setWithScores()); + assertEquals(100, res.getTotalResults()); + assertEquals(5, res.getDocuments().size()); + for (Document d : res.getDocuments()) { + assertTrue(d.getId().startsWith("doc")); + assertTrue(d.getScore() < 100); +// assertEquals( +// String.format( +// "{\"id\":\"%s\",\"score\":%s,\"properties\":{\"title\":\"hello world\",\"body\":\"lorem ipsum\"}}", +// d.getId(), Double.toString(d.getScore())), +// d.toString()); + } + +// assertTrue(client.deleteDocument("doc0", true)); +// assertFalse(client.deleteDocument("doc0")); + client.del("doc0"); + + res = client.ftSearch(index, new Query("hello world")); + assertEquals(99, res.getTotalResults()); + + assertEquals("OK", client.ftDropIndex(index)); + try { + client.ftSearch(index, new Query("hello world")); + fail(); + } catch (JedisDataException e) { + } + } +// +// @Test +// public void searchBatch() throws Exception { +// Schema sc = new Schema().addTextField("title", 1.0).addTextField("body", 1.0); +// +// assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); +// Map fields = new HashMap<>(); +// fields.put("title", "hello world"); +// fields.put("body", "lorem ipsum"); +// for (int i = 0; i < 50; i++) { +// fields.put("title", "hello world"); +//// assertTrue(client.addDocument(String.format("doc%d", i), (double) i / 100.0, fields)); +// addDocument(String.format("doc%d", i), fields); +// } +// +// for (int i = 50; i < 100; i++) { +// fields.put("title", "good night"); +//// assertTrue(client.addDocument(String.format("doc%d", i), (double) i / 100.0, fields)); +// addDocument(String.format("doc%d", i), fields); +// } +// +// SearchResult[] res = client.searchBatch( +// new Query("hello world").limit(0, 5).setWithScores(), +// new Query("good night").limit(0, 5).setWithScores() +// ); +// +// assertEquals(2, res.length); +// assertEquals(50, res[0].getTotalResults()); +// assertEquals(50, res[1].getTotalResults()); +// assertEquals(5, res[0].getDocuments().size()); +// for (Document d : res[0].getDocuments()) { +// assertTrue(d.getId().startsWith("doc")); +// assertTrue(d.getScore() < 100); +// assertEquals( +// String.format( +// "{\"id\":\"%s\",\"score\":%s,\"properties\":{\"title\":\"hello world\",\"body\":\"lorem ipsum\"}}", +// d.getId(), Double.toString(d.getScore())), +// d.toString()); +// } +// } + + @Test + public void testNumericFilter() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0).addNumericField("price"); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + + for (int i = 0; i < 100; i++) { + fields.put("price", i); +// assertTrue(client.addDocument(String.format("doc%d", i), fields)); + addDocument(String.format("doc%d", i), fields); + } + + SearchResult res = client.ftSearch(index, new Query("hello world"). + addFilter(new Query.NumericFilter("price", 0, 49))); + assertEquals(50, res.getTotalResults()); + assertEquals(10, res.getDocuments().size()); + for (Document d : res.getDocuments()) { + long price = Long.valueOf((String) d.get("price")); + assertTrue(price >= 0); + assertTrue(price <= 49); + } + + res = client.ftSearch(index, new Query("hello world"). + addFilter(new Query.NumericFilter("price", 0, true, 49, true))); + assertEquals(48, res.getTotalResults()); + assertEquals(10, res.getDocuments().size()); + for (Document d : res.getDocuments()) { + long price = Long.valueOf((String) d.get("price")); + assertTrue(price > 0); + assertTrue(price < 49); + } + res = client.ftSearch(index, new Query("hello world"). + addFilter(new Query.NumericFilter("price", 50, 100))); + assertEquals(50, res.getTotalResults()); + assertEquals(10, res.getDocuments().size()); + for (Document d : res.getDocuments()) { + long price = Long.valueOf((String) d.get("price")); + assertTrue(price >= 50); + assertTrue(price <= 100); + } + + res = client.ftSearch(index, new Query("hello world"). + addFilter(new Query.NumericFilter("price", 20, Double.POSITIVE_INFINITY))); + assertEquals(80, res.getTotalResults()); + assertEquals(10, res.getDocuments().size()); + + res = client.ftSearch(index, new Query("hello world"). + addFilter(new Query.NumericFilter("price", Double.NEGATIVE_INFINITY, 10))); + assertEquals(11, res.getTotalResults()); + assertEquals(10, res.getDocuments().size()); + + } + + @Test + public void testStopwords() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0); + + assertEquals("OK", client.ftCreate(index, + IndexOptions.defaultOptions().setStopwords("foo", "bar", "baz"), sc)); + + Map fields = new HashMap<>(); + fields.put("title", "hello world foo bar"); +// assertTrue(client.addDocument("doc1", fields)); + addDocument("doc1", fields); + SearchResult res = client.ftSearch(index, new Query("hello world")); + assertEquals(1, res.getTotalResults()); + res = client.ftSearch(index, new Query("foo bar")); + assertEquals(0, res.getTotalResults()); +// +// client.connection().flushDB(); +// +// assertEquals("OK", client.ftCreate(index, sc, +// IndexOptions.defaultOptions().setNoStopwords())); +// fields.put("title", "hello world foo bar to be or not to be"); +// assertTrue(client.addDocument("doc1", fields)); +// +// assertEquals(1, client.ftSearch(index, new Query("hello world")).getTotalResults()); +// assertEquals(1, client.ftSearch(index, new Query("foo bar")).getTotalResults()); +// assertEquals(1, client.ftSearch(index, new Query("to be or not to be")).getTotalResults()); + } + + @Test + public void testStopwordsMore() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0); + + assertEquals("OK", client.ftCreate(index, + IndexOptions.defaultOptions().setNoStopwords(), sc)); + Map fields = new HashMap<>(); + fields.put("title", "hello world foo bar"); + fields.put("title", "hello world foo bar to be or not to be"); + addDocument("doc1", fields); + + assertEquals(1, client.ftSearch(index, new Query("hello world")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("foo bar")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("to be or not to be")).getTotalResults()); + } + + @Test + public void testGeoFilter() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0).addGeoField("loc"); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + fields.put("loc", "-0.441,51.458"); +// assertTrue(client.addDocument("doc1", fields)); + addDocument("doc1", fields); + fields.put("loc", "-0.1,51.2"); +// assertTrue(client.addDocument("doc2", fields)); + addDocument("doc2", fields); + + SearchResult res = client.ftSearch(index, new Query("hello world"). + addFilter( + new Query.GeoFilter("loc", -0.44, 51.45, + 10, Query.GeoFilter.KILOMETERS) + )); + + assertEquals(1, res.getTotalResults()); + res = client.ftSearch(index, new Query("hello world"). + addFilter( + new Query.GeoFilter("loc", -0.44, 51.45, + 100, Query.GeoFilter.KILOMETERS) + )); + assertEquals(2, res.getTotalResults()); + } + + @Test + public void geoFilterAndGeoCoordinateObject() throws Exception { + Schema schema = new Schema().addTextField("title", 1.0).addGeoField("loc"); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), schema)); + + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + fields.put("loc", new redis.clients.jedis.GeoCoordinate(-0.441, 51.458)); +// assertTrue(client.addDocument("doc1", fields)); + addDocument("doc1", fields); + fields.put("loc", new redis.clients.jedis.GeoCoordinate(-0.1, 51.2)); +// assertTrue(client.addDocument("doc2", fields)); + addDocument("doc2", fields); + + SearchResult res = client.ftSearch(index, new Query("hello world").addFilter( + new Query.GeoFilter("loc", -0.44, 51.45, 10, Query.GeoFilter.KILOMETERS))); + assertEquals(1, res.getTotalResults()); + + res = client.ftSearch(index, new Query("hello world").addFilter( + new Query.GeoFilter("loc", -0.44, 51.45, 100, Query.GeoFilter.KILOMETERS))); + assertEquals(2, res.getTotalResults()); + } +// +// // TODO: This test was broken in master branch +// @Test +// public void testPayloads() throws Exception { +// Schema sc = new Schema().addTextField("title", 1.0); +// +// assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); +// +// Map fields = new HashMap<>(); +// fields.put("title", "hello world"); +// String payload = "foo bar"; +//// assertTrue(client.addDocument("doc1", 1.0, fields, false, false, payload.getBytes())); +// addDocument("doc1", fields); +// +// SearchResult res = client.ftSearch(index, new Query("hello world").setWithPayload()); +// assertEquals(1, res.getTotalResults()); +// assertEquals(1, res.getDocuments().size()); +// +// assertEquals(payload, new String(res.getDocuments().get(0).getPayload())); +// } + + @Test + public void testQueryFlags() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields = new HashMap<>(); + + for (int i = 0; i < 100; i++) { + fields.put("title", i % 2 != 0 ? "hello worlds" : "hello world"); +// assertTrue(client.addDocument(String.format("doc%d", i), (double) i / 100.0, fields)); + addDocument(String.format("doc%d", i), fields); + } + + Query q = new Query("hello").setWithScores(); + SearchResult res = client.ftSearch(index, q); + + assertEquals(100, res.getTotalResults()); + assertEquals(10, res.getDocuments().size()); + + for (Document d : res.getDocuments()) { + assertTrue(d.getId().startsWith("doc")); +// assertNotEquals(1.0, d.getScore()); + assertTrue(((String) d.get("title")).startsWith("hello world")); + } + + q = new Query("hello").setNoContent(); + res = client.ftSearch(index, q); + for (Document d : res.getDocuments()) { + assertTrue(d.getId().startsWith("doc")); + assertEquals(1.0, d.getScore(), 0); + assertEquals(null, d.get("title")); + } + + // test verbatim vs. stemming + res = client.ftSearch(index, new Query("hello worlds")); + assertEquals(100, res.getTotalResults()); + res = client.ftSearch(index, new Query("hello worlds").setVerbatim()); + assertEquals(50, res.getTotalResults()); + + res = client.ftSearch(index, new Query("hello a world").setVerbatim()); + assertEquals(50, res.getTotalResults()); + res = client.ftSearch(index, new Query("hello a worlds").setVerbatim()); + assertEquals(50, res.getTotalResults()); + res = client.ftSearch(index, new Query("hello a world").setVerbatim().setNoStopwords()); + assertEquals(0, res.getTotalResults()); + } + + @Test + public void testSortQueryFlags() throws Exception { + Schema sc = new Schema().addSortableTextField("title", 1.0); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields = new HashMap<>(); + + fields.put("title", "b title"); +// client.addDocument("doc1", 1.0, fields, false, true, null); + addDocument("doc1", fields); + + fields.put("title", "a title"); +// client.addDocument("doc2", 1.0, fields, false, true, null); + addDocument("doc2", fields); + + fields.put("title", "c title"); +// client.addDocument("doc3", 1.0, fields, false, true, null); + addDocument("doc3", fields); + + Query q = new Query("title").setSortBy("title", true); + SearchResult res = client.ftSearch(index, q); + + assertEquals(3, res.getTotalResults()); + Document doc1 = res.getDocuments().get(0); + assertEquals("a title", doc1.get("title")); + + doc1 = res.getDocuments().get(1); + assertEquals("b title", doc1.get("title")); + + doc1 = res.getDocuments().get(2); + assertEquals("c title", doc1.get("title")); + } + + @Test + public void testNullField() throws Exception { + Schema sc = new Schema() + .addTextField("title", 1.0) + .addTextField("genre", 1.0) + .addTextField("plot", 1.0) + .addSortableNumericField("release_year") + .addTagField("tag") + .addGeoField("loc"); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + // create a document with a field set to null + Map fields = new HashMap<>(); + fields.put("title", "another test with title "); + fields.put("genre", "Comedy"); + fields.put("plot", "this is the plot for the test"); + fields.put("tag", "fun"); + fields.put("release_year", 2019); + fields.put("loc", "-0.1,51.2"); + +// client.addDocument("doc1", fields); + addDocument("doc1", fields); + SearchResult res = client.ftSearch(index, new Query("title")); + assertEquals(1, res.getTotalResults()); + + fields = new HashMap<>(); + fields.put("title", "another title another test"); + fields.put("genre", "Action"); + fields.put("plot", null); + fields.put("tag", null); + + try { +// client.addDocument("doc2", fields); + addDocument("doc2", fields); + fail("Should throw NullPointerException."); + } catch (NullPointerException e) { +// assertEquals("Document attribute 'tag' is null. (Remove it, or set a value)", e.getMessage()); + } + + res = client.ftSearch(index, new Query("title")); + assertEquals(1, res.getTotalResults()); + + // Testing with numerical value + fields = new HashMap<>(); + fields.put("title", "another title another test"); + fields.put("genre", "Action"); + fields.put("release_year", null); + try { +// client.addDocument("doc2", fields); + addDocument("doc2", fields); + fail("Should throw NullPointerException."); + } catch (NullPointerException e) { +// assertEquals("Document attribute 'release_year' is null. (Remove it, or set a value)", e.getMessage()); + } + res = client.ftSearch(index, new Query("title")); + assertEquals(1, res.getTotalResults()); + } + + @Test + public void dropIndex() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + for (int i = 0; i < 100; i++) { + addDocument(String.format("doc%d", i), fields); + } + + SearchResult res = client.ftSearch(index, new Query("hello world")); + assertEquals(100, res.getTotalResults()); + + assertEquals("OK", client.ftDropIndex(index)); + + try { + client.ftSearch(index, new Query("hello world")); + fail("Index should not exist."); + } catch (JedisDataException de) { + assertTrue(de.getMessage().contains("no such index")); + } + assertEquals(100, client.dbSize()); + } + + @Test + public void dropIndexDD() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + for (int i = 0; i < 100; i++) { + addDocument(String.format("doc%d", i), fields); + } + + SearchResult res = client.ftSearch(index, new Query("hello world")); + assertEquals(100, res.getTotalResults()); + + assertEquals("OK", client.ftDropIndexDD(index)); + + Set keys = client.keys("*"); + assertTrue(keys.isEmpty()); + assertEquals(0, client.dbSize()); + } + + @Test + public void testDropMissing() throws Exception { + try { + client.ftDropIndex(index); + fail(); + } catch (JedisDataException ex) { + } + } + + @Test + public void alterAdd() throws Exception { + Schema sc = new Schema().addTextField("title", 1.0); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields = new HashMap<>(); + fields.put("title", "hello world"); + for (int i = 0; i < 100; i++) { + addDocument(String.format("doc%d", i), fields); + } + + SearchResult res = client.ftSearch(index, new Query("hello world")); + assertEquals(100, res.getTotalResults()); + + assertEquals("OK", client.ftAlter(index, new TagField("tags", ","), new TextField("name", 0.5))); + for (int i = 0; i < 100; i++) { + Map fields2 = new HashMap<>(); + fields2.put("name", "name" + i); + fields2.put("tags", String.format("tagA,tagB,tag%d", i)); +// assertTrue(client.updateDocument(String.format("doc%d", i), 1.0, fields2)); + addDocument(String.format("doc%d", i), fields2); + } + SearchResult res2 = client.ftSearch(index, new Query("@tags:{tagA}")); + assertEquals(100, res2.getTotalResults()); + + Map info = client.ftInfo(index); + assertEquals(index, info.get("index_name")); + assertEquals("identifier", ((List) ((List) info.get("attributes")).get(1)).get(0)); + assertEquals("attribute", ((List) ((List) info.get("attributes")).get(1)).get(2)); + } + + @Test + public void noStem() throws Exception { + Schema sc = new Schema().addTextField("stemmed", 1.0).addField(new Schema.TextField("notStemmed", 1.0, false, true)); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map doc = new HashMap<>(); + doc.put("stemmed", "located"); + doc.put("notStemmed", "located"); + // Store it +// assertTrue(client.addDocument("doc", doc)); + addDocument("doc", doc); + + // Query + SearchResult res = client.ftSearch(index, new Query("@stemmed:location")); + assertEquals(1, res.getTotalResults()); + + res = client.ftSearch(index, new Query("@notStemmed:location")); + assertEquals(0, res.getTotalResults()); + } + + @Test + public void phoneticMatch() throws Exception { + Schema sc = new Schema() + .addTextField("noPhonetic", 1.0) + .addField(new Schema.TextField("withPhonetic", 1.0, false, false, false, "dm:en")); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map doc = new HashMap<>(); + doc.put("noPhonetic", "morfix"); + doc.put("withPhonetic", "morfix"); + + // Store it +// assertTrue(client.addDocument("doc", doc)); + addDocument("doc", doc); + + // Query + SearchResult res = client.ftSearch(index, new Query("@withPhonetic:morphix=>{$phonetic:true}")); + assertEquals(1, res.getTotalResults()); + + try { + client.ftSearch(index, new Query("@noPhonetic:morphix=>{$phonetic:true}")); + fail(); + } catch (JedisDataException e) {/*field does not support phonetics*/ + } + + SearchResult res3 = client.ftSearch(index, new Query("@withPhonetic:morphix=>{$phonetic:false}")); + assertEquals(0, res3.getTotalResults()); + } + + @Test + public void info() throws Exception { + String MOVIE_ID = "movie_id"; + String TITLE = "title"; + String GENRE = "genre"; + String VOTES = "votes"; + String RATING = "rating"; + String RELEASE_YEAR = "release_year"; + String PLOT = "plot"; + String POSTER = "poster"; + + Schema sc = new Schema() + .addTextField(TITLE, 5.0) + .addSortableTextField(PLOT, 1.0) + .addSortableTagField(GENRE, ",") + .addSortableNumericField(RELEASE_YEAR) + .addSortableNumericField(RATING) + .addSortableNumericField(VOTES); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map info = client.ftInfo(index); + assertEquals(index, info.get("index_name")); + + assertEquals(6, ((List) info.get("attributes")).size()); + assertEquals("global_idle", ((List) info.get("cursor_stats")).get(0)); + assertEquals(0L, ((List) info.get("cursor_stats")).get(1)); + } + + @Test + public void noIndex() throws Exception { + Schema sc = new Schema() + .addField(new Schema.TextField("f1", 1.0, true, false, true)) + .addField(new Schema.TextField("f2", 1.0)); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); + + Map mm = new HashMap<>(); + + mm.put("f1", "MarkZZ"); + mm.put("f2", "MarkZZ"); +// client.addDocument("doc1", mm); + addDocument("doc1", mm); + + mm.clear(); + mm.put("f1", "MarkAA"); + mm.put("f2", "MarkBB"); +// client.addDocument("doc2", mm); + addDocument("doc2", mm); + + SearchResult res = client.ftSearch(index, new Query("@f1:Mark*")); + assertEquals(0, res.getTotalResults()); + + res = client.ftSearch(index, new Query("@f2:Mark*")); + assertEquals(2, res.getTotalResults()); + + Document[] docs = new Document[2]; + + res = client.ftSearch(index, new Query("@f2:Mark*").setSortBy("f1", false)); + assertEquals(2, res.getTotalResults()); + + res.getDocuments().toArray(docs); + assertEquals("doc1", docs[0].getId()); + + res = client.ftSearch(index, new Query("@f2:Mark*").setSortBy("f1", true)); + res.getDocuments().toArray(docs); + assertEquals("doc2", docs[0].getId()); + } +// +// @Test +// public void testReplacePartial() throws Exception { +// Schema sc = new Schema() +// .addTextField("f1", 1.0) +// .addTextField("f2", 1.0) +// .addTextField("f3", 1.0); +// assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); +// +// Map mm = new HashMap<>(); +// mm.put("f1", "f1_val"); +// mm.put("f2", "f2_val"); +// +//// assertTrue(client.addDocument("doc1", mm)); +// addDocument("doc1", mm); +//// assertTrue(client.addDocument("doc2", mm)); +// addDocument("doc2", mm); +// +// mm.clear(); +// mm.put("f3", "f3_val"); +// +//// assertTrue(client.updateDocument("doc1", 1.0, mm)); +// addDocument("doc1", mm); +//// assertTrue(client.replaceDocument("doc2", 1.0, mm)); +// addDocument("doc2", mm); +// +// // Search for f3 value. All documents should have it. +// SearchResult res = client.ftSearch(index, new Query(("@f3:f3_Val"))); +// assertEquals(2, res.getTotalResults()); +// +// res = client.ftSearch(index, new Query("@f3:f3_val @f2:f2_val @f1:f1_val")); +// assertEquals(1, res.getTotalResults()); +// } +// +// @Test +// public void testReplaceIf() throws Exception { +// Schema sc = new Schema() +// .addTextField("f1", 1.0) +// .addTextField("f2", 1.0) +// .addTextField("f3", 1.0); +// assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); +// +// Map mm = new HashMap<>(); +// mm.put("f1", "v1_val"); +// mm.put("f2", "v2_val"); +// +// assertTrue(client.addDocument("doc1", mm)); +// assertTrue(client.addDocument("doc2", mm)); +// +// mm.clear(); +// mm.put("f3", "v3_val"); +// +// assertFalse(client.updateDocument("doc1", 1.0, mm, "@f1=='vv1_val'")); +// // Search for f3 value. No documents should not have it. +// SearchResult res1 = client.ftSearch(index, new Query(("@f3:f3_Val"))); +// assertEquals(0, res1.getTotalResults()); +// +// assertTrue(client.updateDocument("doc1", 1.0, mm, "@f2=='v2_val'")); +// // Search for f3 value. All documents should have it. +// SearchResult res2 = client.ftSearch(index, new Query(("@f3:v3_Val"))); +// assertEquals(1, res2.getTotalResults()); +// +// assertFalse(client.replaceDocument("doc2", 1.0, mm, "@f1=='vv3_Val'")); +// +// // Search for f3 value. Only one document should have it. +// SearchResult res3 = client.ftSearch(index, new Query(("@f3:v3_Val"))); +// assertEquals(1, res3.getTotalResults()); +// +// assertTrue(client.replaceDocument("doc2", 1.0, mm, "@f1=='v1_val'")); +// +// // Search for f3 value. All documents should have it. +// SearchResult res4 = client.ftSearch(index, new Query(("@f3:v3_Val"))); +// assertEquals(2, res4.getTotalResults()); +// } + + @Test + public void testExplain() throws Exception { + Schema sc = new Schema() + .addTextField("f1", 1.0) + .addTextField("f2", 1.0) + .addTextField("f3", 1.0); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); + + String res = client.ftExplain(index, new Query("@f3:f3_val @f2:f2_val @f1:f1_val")); + assertNotNull(res); + assertFalse(res.isEmpty()); + } + + @Test + public void testHighlightSummarize() throws Exception { + Schema sc = new Schema().addTextField("text", 1.0); + client.ftCreate(index, IndexOptions.defaultOptions(), sc); + + Map doc = new HashMap<>(); + doc.put("text", "Redis is often referred as a data structures server. What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a server-client model with TCP sockets and a simple protocol. So different processes can query and modify the same data structures in a shared way"); + // Add a document +// client.addDocument("foo", 1.0, doc); + addDocument("foo", doc); + Query q = new Query("data").highlightFields().summarizeFields(); + SearchResult res = client.ftSearch(index, q); + + assertEquals("is often referred as a data structures server. What this means is that Redis provides... What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a... So different processes can query and modify the same data structures in a shared... ", + res.getDocuments().get(0).get("text")); + + q = new Query("data").highlightFields(new Query.HighlightTags("", "")).summarizeFields(); + res = client.ftSearch(index, q); + + assertEquals("is often referred as a data structures server. What this means is that Redis provides... What this means is that Redis provides access to mutable data structures via a set of commands, which are sent using a... So different processes can query and modify the same data structures in a shared... ", + res.getDocuments().get(0).get("text")); + + } +// +// @Test +// public void testLanguage() throws Exception { +// Schema sc = new Schema().addTextField("text", 1.0); +// client.ftCreate(index, IndexOptions.defaultOptions(), sc); +// +// Document d = new Document("doc1").set("text", "hello"); +// AddOptions options = new AddOptions().setLanguage("spanish"); +// assertTrue(client.addDocument(d, options)); +// boolean caught = false; +// +// options.setLanguage("ybreski"); +// client.deleteDocument(d.getId()); +// +// try { +// client.addDocument(d, options); +// } catch (JedisDataException t) { +// caught = true; +// } +// assertTrue(caught); +// } +// +// @Test +// public void testGet() throws Exception { +// client.ftCreate(index, IndexOptions.defaultOptions(), new Schema().addTextField("txt1", 1.0)); +// client.addDocument(new Document("doc1").set("txt1", "Hello World!"), new AddOptions()); +// Document d = client.getDocument("doc1"); +// assertNotNull(d); +// assertEquals("Hello World!", d.get("txt1")); +// +// // Get something that does not exist. Shouldn't explode +// assertNull(client.getDocument("nonexist")); +// +// // Test decode=false mode +// d = client.getDocument("doc1", false); +// assertNotNull(d); +// assertTrue(Arrays.equals(SafeEncoder.encode("Hello World!"), (byte[]) d.get("txt1"))); +// } +// +// @Test +// public void testMGet() throws Exception { +// client.ftCreate(index, IndexOptions.defaultOptions(), new Schema().addTextField("txt1", 1.0)); +// client.addDocument(new Document("doc1").set("txt1", "Hello World!1"), new AddOptions()); +// client.addDocument(new Document("doc2").set("txt1", "Hello World!2"), new AddOptions()); +// client.addDocument(new Document("doc3").set("txt1", "Hello World!3"), new AddOptions()); +// +// List docs = client.getDocuments(); +// assertEquals(0, docs.size()); +// +// docs = client.getDocuments("doc1", "doc3", "doc4"); +// assertEquals(3, docs.size()); +// assertEquals("Hello World!1", docs.get(0).get("txt1")); +// assertEquals("Hello World!3", docs.get(1).get("txt1")); +// assertNull(docs.get(2)); +// +// // Test decode=false mode +// docs = client.getDocuments(false, "doc2"); +// assertEquals(1, docs.size()); +// assertTrue(Arrays.equals(SafeEncoder.encode("Hello World!2"), (byte[]) docs.get(0).get("txt1"))); +// } +// +// private static void assertUnknownIndex(JedisDataException jde) { +// assertTrue(jde.getMessage().toLowerCase().contains("unknown index")); +// } +// +// @Test +// public void testAddSuggestionGetSuggestionFuzzy() throws Exception { +// Suggestion suggestion = Suggestion.builder().str("TOPIC OF WORDS").score(1).build(); +// // test can add a suggestion string +// assertTrue(suggestion.toString() + " insert should of returned at least 1", client.addSuggestion(suggestion, true) > 0); +// // test that the partial part of that string will be returned using fuzzy +// +// assertEquals(suggestion.toString() + " suppose to be returned", suggestion, client.getSuggestion(suggestion.getString().substring(0, 3), SuggestionOptions.builder().build()).get(0)); +// } +// +// @Test +// public void testAddSuggestionGetSuggestion() throws Exception { +// try { +// Suggestion.builder().str("ANOTHER_WORD").score(3).build(); +// fail("Illegal score"); +// } catch (IllegalStateException e) { +// } +// +// try { +// Suggestion.builder().score(1).build(); +// fail("Missing required string"); +// } catch (IllegalStateException e) { +// } +// +// Suggestion suggestion = Suggestion.builder().str("ANOTHER_WORD").score(1).build(); +// Suggestion noMatch = Suggestion.builder().str("_WORD MISSED").score(1).build(); +// +// assertTrue(suggestion.toString() + " should of inserted at least 1", client.addSuggestion(suggestion, false) > 0); +// assertTrue(noMatch.toString() + " should of inserted at least 1", client.addSuggestion(noMatch, false) > 0); +// +// // test that with a partial part of that string will have the entire word returned SuggestionOptions.builder().build() +// assertEquals(suggestion.getString() + " did not get a match with 3 characters", 1, client.getSuggestion(suggestion.getString().substring(0, 3), SuggestionOptions.builder().fuzzy().build()).size()); +// +// // turn off fuzzy start at second word no hit +// assertEquals(noMatch.getString() + " no fuzzy and starting at 1, should not match", 0, client.getSuggestion(noMatch.getString().substring(1, 6), SuggestionOptions.builder().build()).size()); +// // my attempt to trigger the fuzzy by 1 character +// assertEquals(noMatch.getString() + " fuzzy is on starting at 1 position should match", 1, client.getSuggestion(noMatch.getString().substring(1, 6), SuggestionOptions.builder().fuzzy().build()).size()); +// } +// +// @Test +// public void testAddSuggestionGetSuggestionPayloadScores() throws Exception { +// Suggestion suggestion = Suggestion.builder().str("COUNT_ME TOO").payload("PAYLOADS ROCK ").score(0.2).build(); +// assertTrue(suggestion.toString() + " insert should of at least returned 1", client.addSuggestion(suggestion, false) > 0); +// assertTrue("Count single added should return more than 1", client.addSuggestion(suggestion.toBuilder().str("COUNT").payload("My PAYLOAD is better").build(), false) > 1); +// assertTrue("Count single added should return more than 1", client.addSuggestion(suggestion.toBuilder().str("COUNT_ANOTHER").score(1).payload(null).build(), false) > 1); +// +// Suggestion noScoreOrPayload = Suggestion.builder().str("COUNT NO PAYLOAD OR COUNT").build(); +// assertTrue("Count single added should return more than 1", client.addSuggestion(noScoreOrPayload, true) > 1); +// +// List payloads = client.getSuggestion(suggestion.getString().substring(0, 3), SuggestionOptions.builder().with(SuggestionOptions.With.PAYLOAD_AND_SCORES).build()); +// assertEquals("4 suggestions with scores and payloads ", 4, payloads.size()); +// assertTrue("Assert that a suggestion has a payload ", payloads.get(2).getPayload().length() > 0); +// assertTrue("Assert that a suggestion has a score not default 1 ", payloads.get(1).getScore() < .299); +// +// } +// +// @Test +// public void testAddSuggestionGetSuggestionPayload() throws Exception { +// client.addSuggestion(Suggestion.builder().str("COUNT_ME TOO").payload("PAYLOADS ROCK ").build(), false); +// client.addSuggestion(Suggestion.builder().str("COUNT").payload("ANOTHER PAYLOAD ").build(), false); +// client.addSuggestion(Suggestion.builder().str("COUNTNO PAYLOAD OR COUNT").build(), false); +// +// // test that with a partial part of that string will have the entire word returned +// List payloads = client.getSuggestion("COU", SuggestionOptions.builder().max(3).fuzzy().with(SuggestionOptions.With.PAYLOAD).build()); +// assertEquals("3 suggestions payloads ", 3, payloads.size()); +// +// } +// +// @Test +// public void testGetSuggestionNoPayloadTwoOnly() throws Exception { +// client.addSuggestion(Suggestion.builder().str("DIFF_WORD").score(0.4).payload("PAYLOADS ROCK ").build(), false); +// client.addSuggestion(Suggestion.builder().str("DIFF wording").score(0.5).payload("ANOTHER PAYLOAD ").build(), false); +// client.addSuggestion(Suggestion.builder().str("DIFFERENT").score(0.7).payload("I am a payload").build(), false); +// +// List payloads = client.getSuggestion("DIF", SuggestionOptions.builder().max(2).build()); +// assertEquals("3 suggestions should match but only asking for 2 and payloads should have 2 items in array", 2, payloads.size()); +// +// List three = client.getSuggestion("DIF", SuggestionOptions.builder().max(3).build()); +// assertEquals("3 suggestions and payloads should have 3 items in array", 3, three.size()); +// +// } +// +// @Test +// public void testGetSuggestionWithScore() throws Exception { +// client.addSuggestion(Suggestion.builder().str("DIFF_WORD").score(0.4).payload("PAYLOADS ROCK ").build(), true); +// List list = client.getSuggestion("DIF", SuggestionOptions.builder().max(2).with(SuggestionOptions.With.SCORES).build()); +// assertTrue(list.get(0).getScore() <= .2); +// } +// +// @Test +// public void testGetSuggestionAllNoHit() throws Exception { +// client.addSuggestion(Suggestion.builder().str("NO WORD").score(0.4).build(), false); +// +// List none = client.getSuggestion("DIF", SuggestionOptions.builder().max(3).with(SuggestionOptions.With.SCORES).build()); +// assertEquals("Empty list not hit in index for partial word", 0, none.size()); +// } +// +// @Test +// public void testAddSuggestionDeleteSuggestionLength() throws Exception { +// client.addSuggestion(Suggestion.builder().str("TOPIC OF WORDS").score(1).build(), true); +// client.addSuggestion(Suggestion.builder().str("ANOTHER ENTRY").score(1).build(), true); +// +// long result = client.deleteSuggestion("ANOTHER ENTRY"); +// assertEquals("The delete of the suggestion should return 1", 1, result); +// assertEquals(1L, client.getSuggestionLength().longValue()); +// +// result = client.deleteSuggestion("ANOTHER ENTRY THAT IS NOT PRESENT"); +// assertEquals("The delete of the suggestion should return 0", 0, result); +// assertEquals(1L, client.getSuggestionLength().longValue()); +// } +// +// @Test +// public void testAddSuggestionGetSuggestionLength() throws Exception { +// client.addSuggestion(Suggestion.builder().str("TOPIC OF WORDS").score(1).build(), true); +// client.addSuggestion(Suggestion.builder().str("ANOTHER ENTRY").score(1).build(), true); +// assertEquals(2L, client.getSuggestionLength().longValue()); +// +// client.addSuggestion(Suggestion.builder().str("FINAL ENTRY").score(1).build(), true); +// assertEquals(3L, client.getSuggestionLength().longValue()); +// } + + @Test + public void getTagField() { + Schema sc = new Schema() + .addTextField("title", 1.0) + .addTagField("category"); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields1 = new HashMap<>(); + fields1.put("title", "hello world"); + fields1.put("category", "red"); +// assertTrue(client.addDocument("foo", fields1)); + addDocument("foo", fields1); + Map fields2 = new HashMap<>(); + fields2.put("title", "hello world"); + fields2.put("category", "blue"); +// assertTrue(client.addDocument("bar", fields2)); + addDocument("bar", fields2); + Map fields3 = new HashMap<>(); + fields3.put("title", "hello world"); + fields3.put("category", "green,yellow"); +// assertTrue(client.addDocument("baz", fields3)); + addDocument("baz", fields3); + Map fields4 = new HashMap<>(); + fields4.put("title", "hello world"); + fields4.put("category", "orange;purple"); +// assertTrue(client.addDocument("qux", fields4)); + addDocument("qux", fields4); + + assertEquals(1, client.ftSearch(index, new Query("@category:{red}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("@category:{blue}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("hello @category:{red}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("hello @category:{blue}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("@category:{yellow}")).getTotalResults()); + assertEquals(0, client.ftSearch(index, new Query("@category:{purple}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("@category:{orange\\;purple}")).getTotalResults()); + assertEquals(4, client.ftSearch(index, new Query("hello")).getTotalResults()); + } + + @Test + public void testGetTagFieldWithNonDefaultSeparator() { + Schema sc = new Schema() + .addTextField("title", 1.0) + .addTagField("category", ";"); + + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map fields1 = new HashMap<>(); + fields1.put("title", "hello world"); + fields1.put("category", "red"); +// assertTrue(client.addDocument("foo", fields1)); + addDocument("foo", fields1); + Map fields2 = new HashMap<>(); + fields2.put("title", "hello world"); + fields2.put("category", "blue"); +// assertTrue(client.addDocument("bar", fields2)); + addDocument("bar", fields2); + Map fields3 = new HashMap<>(); + fields3.put("title", "hello world"); + fields3.put("category", "green;yellow"); + addDocument("baz", fields3); +// assertTrue(client.addDocument("baz", fields3)); + Map fields4 = new HashMap<>(); + fields4.put("title", "hello world"); + fields4.put("category", "orange,purple"); +// assertTrue(client.addDocument("qux", fields4)); + addDocument("qux", fields4); + + assertEquals(1, client.ftSearch(index, new Query("@category:{red}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("@category:{blue}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("hello @category:{red}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("hello @category:{blue}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("hello @category:{yellow}")).getTotalResults()); + assertEquals(0, client.ftSearch(index, new Query("@category:{purple}")).getTotalResults()); + assertEquals(1, client.ftSearch(index, new Query("@category:{orange\\,purple}")).getTotalResults()); + assertEquals(4, client.ftSearch(index, new Query("hello")).getTotalResults()); + } +// +// @Test +// public void testMultiDocuments() { +// Schema sc = new Schema().addTextField("title", 1.0).addTextField("body", 1.0); +// +// assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); +// +// Map fields = new HashMap<>(); +// fields.put("title", "hello world"); +// fields.put("body", "lorem ipsum"); +// +// boolean[] results = client.addDocuments(new Document("doc1", fields), new Document("doc2", fields), new Document("doc3", fields)); +// +// assertArrayEquals(new boolean[]{true, true, true}, results); +// +// assertEquals(3, client.ftSearch(index, new Query("hello world")).getTotalResults()); +// +// results = client.addDocuments(new Document("doc4", fields), new Document("doc2", fields), new Document("doc5", fields)); +// assertArrayEquals(new boolean[]{true, false, true}, results); +// +// results = client.deleteDocuments(true, "doc1", "doc2", "doc36"); +// assertArrayEquals(new boolean[]{true, true, false}, results); +// } + + @Test + public void testReturnFields() throws Exception { + Schema sc = new Schema().addTextField("field1", 1.0).addTextField("field2", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map doc = new HashMap<>(); + doc.put("field1", "value1"); + doc.put("field2", "value2"); + // Store it +// assertTrue(client.addDocument("doc", doc)); + addDocument("doc", doc); + + // Query + SearchResult res = client.ftSearch(index, new Query("*").returnFields("field1")); + assertEquals(1, res.getTotalResults()); + assertEquals("value1", res.getDocuments().get(0).get("field1")); + assertNull(res.getDocuments().get(0).get("field2")); + } + + @Test + public void returnWithFieldNames() throws Exception { + Schema sc = new Schema().addTextField("a", 1).addTextField("b", 1).addTextField("c", 1); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map map = new HashMap<>(); + map.put("a", "value1"); + map.put("b", "value2"); + map.put("c", "value3"); +// assertTrue(client.addDocument("doc", map)); + addDocument("doc", map); + + // Query + SearchResult res = client.ftSearch(index, new Query() + .returnFields(FieldName.of("a"), FieldName.of("b").as("d"))); + assertEquals(1, res.getTotalResults()); + Document doc = res.getDocuments().get(0); + assertEquals("value1", doc.get("a")); + assertNull(doc.get("b")); + assertEquals("value2", doc.get("d")); + assertNull(doc.get("c")); + } + + @Test + public void inKeys() throws Exception { + Schema sc = new Schema().addTextField("field1", 1.0).addTextField("field2", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + Map doc = new HashMap<>(); + doc.put("field1", "value"); + doc.put("field2", "not"); + + // Store it +// assertTrue(client.addDocument("doc1", doc)); + addDocument("doc1", doc); +// assertTrue(client.addDocument("doc2", doc)); + addDocument("doc2", doc); + + // Query + SearchResult res = client.ftSearch(index, new Query("value").limitKeys("doc1")); + assertEquals(1, res.getTotalResults()); + assertEquals("doc1", res.getDocuments().get(0).getId()); + assertEquals("value", res.getDocuments().get(0).get("field1")); + assertEquals(null, res.getDocuments().get(0).get("value")); + } + + @Test + public void blobField() throws Exception { + Schema sc = new Schema().addTextField("field1", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + byte[] blob = new byte[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + + Map doc = new HashMap<>(); + doc.put("field1", "value"); + doc.put("field2", blob); + + // Store it +// assertTrue(client.addDocument("doc1", doc)); + addDocument("doc1", doc); + + // Query +// SearchResult res = client.ftSearch(index, new Query("value"), false); + SearchResult res = client.ftSearch(SafeEncoder.encode(index), new Query("value")); + assertEquals(1, res.getTotalResults()); + assertEquals("doc1", res.getDocuments().get(0).getId()); + assertEquals("value", res.getDocuments().get(0).getString("field1")); + assertArrayEquals(blob, (byte[]) res.getDocuments().get(0).get("field2")); + } + + @Test + public void config() throws Exception { + assertEquals("OK", client.ftConfigSet("timeout", "100")); + Map configMap = client.ftConfigGet("*"); + assertEquals("100", configMap.get("TIMEOUT")); + } + + @Test + public void configOnTimeout() throws Exception { + assertEquals("OK", client.ftConfigSet("ON_TIMEOUT", "fail")); + assertEquals(Collections.singletonMap("ON_TIMEOUT", "fail"), client.ftConfigGet("ON_TIMEOUT")); + + try { + client.ftConfigSet("ON_TIMEOUT", "null"); + fail("null is not valid value for ON_TIMEOUT"); + } catch (JedisDataException e) { + // Should throw an exception after RediSearch 2.2 + } + } + + @Test + public void alias() throws Exception { + Schema sc = new Schema().addTextField("field1", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + Map doc = new HashMap<>(); + doc.put("field1", "value"); +// assertTrue(client.addDocument("doc1", doc)); + addDocument("doc1", doc); + + assertEquals("OK", client.ftAliasAdd("ALIAS1", index)); + SearchResult res1 = client.ftSearch("ALIAS1", new Query("*").returnFields("field1")); + assertEquals(1, res1.getTotalResults()); + assertEquals("value", res1.getDocuments().get(0).get("field1")); + + assertEquals("OK", client.ftAliasUpdate("ALIAS2", index)); + SearchResult res2 = client.ftSearch("ALIAS2", new Query("*").returnFields("field1")); + assertEquals(1, res2.getTotalResults()); + assertEquals("value", res2.getDocuments().get(0).get("field1")); + + try { + client.ftAliasDel("ALIAS3"); + fail("Should throw JedisDataException"); + } catch (JedisDataException e) { + // Alias does not exist + } + assertEquals("OK", client.ftAliasDel("ALIAS2")); + try { + client.ftAliasDel("ALIAS2"); + fail("Should throw JedisDataException"); + } catch (JedisDataException e) { + // Alias does not exist + } + } + + @Test + public void syn() throws Exception { + Schema sc = new Schema().addTextField("name", 1.0).addTextField("addr", 1.0); + assertEquals("OK", client.ftCreate(index, IndexOptions.defaultOptions(), sc)); + + long group1 = 345L; + long group2 = 789L; + String group1_str = Long.toString(group1); + String group2_str = Long.toString(group2); + assertEquals("OK", client.ftSynUpdate(index, group1_str, "girl", "baby")); + assertEquals("OK", client.ftSynUpdate(index, group1_str, "child")); + assertEquals("OK", client.ftSynUpdate(index, group2_str, "child")); + + Map> dump = client.ftSynDump(index); + + Map> expected = new HashMap<>(); + expected.put("girl", Arrays.asList(group1_str)); + expected.put("baby", Arrays.asList(group1_str)); + expected.put("child", Arrays.asList(group1_str, group2_str)); + assertEquals(expected, dump); + } +} diff --git a/src/test/java/redis/clients/jedis/tests/params/ParamsTest.java b/src/test/java/redis/clients/jedis/params/ParamsTest.java similarity index 81% rename from src/test/java/redis/clients/jedis/tests/params/ParamsTest.java rename to src/test/java/redis/clients/jedis/params/ParamsTest.java index d57b11d2c1..6f4dd098de 100644 --- a/src/test/java/redis/clients/jedis/tests/params/ParamsTest.java +++ b/src/test/java/redis/clients/jedis/params/ParamsTest.java @@ -1,11 +1,10 @@ -package redis.clients.jedis.tests.params; +package redis.clients.jedis.params; import static org.hamcrest.MatcherAssert.assertThat; import org.hamcrest.CoreMatchers; import org.junit.Test; - -import redis.clients.jedis.params.ClientKillParams; +import redis.clients.jedis.args.ClientType; public class ParamsTest { @@ -15,7 +14,7 @@ public void toStringTest() { ClientKillParams clientKillParams = ClientKillParams.clientKillParams() .addr("127.0.0.1", 6379) .id("12".getBytes()) - .type(ClientKillParams.Type.NORMAL); + .type(ClientType.NORMAL); String toStringResult = clientKillParams.toString(); assertThat(toStringResult, CoreMatchers.containsString("ID, 12")); diff --git a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java b/src/test/java/redis/clients/jedis/tests/ConnectionTest.java deleted file mode 100644 index a8de1c200a..0000000000 --- a/src/test/java/redis/clients/jedis/tests/ConnectionTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.fail; - -import org.junit.After; -import org.junit.Test; - -import redis.clients.jedis.Connection; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.exceptions.JedisConnectionException; - -public class ConnectionTest { - private Connection client; - - @After - public void tearDown() throws Exception { - if (client != null) { - client.close(); - } - } - - @Test(expected = JedisConnectionException.class) - public void checkUnkownHostBackwardCompatible() { - client = new Connection(); - client.setHost("someunknownhost"); - client.connect(); - } - - @Test(expected = JedisConnectionException.class) - public void checkUnkownHost() { - client = new Connection("someunknownhost", Protocol.DEFAULT_PORT); - client.connect(); - } - - @Test(expected = JedisConnectionException.class) - public void checkWrongPortBackwardCompatible() { - client = new Connection(); - client.setHost("localhost"); - client.setPort(55665); - client.connect(); - } - - @Test(expected = JedisConnectionException.class) - public void checkWrongPort() { - client = new Connection(Protocol.DEFAULT_HOST, 55665); - client.connect(); - } - - @Test - public void connectIfNotConnectedWhenSettingTimeoutInfinite() { - client = new Connection("localhost", 6379); - client.setTimeoutInfinite(); - } - - @Test - public void checkCloseable() { - client = new Connection("localhost", 6379); - client.connect(); - client.close(); - } - - @Test - public void readWithBrokenConnection() { - class BrokenConnection extends Connection { - private BrokenConnection() { - super("nonexistinghost", 0); - try { - connect(); - fail("Client should fail connecting to nonexistinghost"); - } catch (JedisConnectionException ignored) { - } - } - - private Object read() { - return readProtocolWithCheckingBroken(); - } - } - - BrokenConnection conn = new BrokenConnection(); - try { - conn.read(); - fail("Read should fail as connection is broken"); - } catch (JedisConnectionException jce) { - assertEquals("Attempting to read from a broken connection", jce.getMessage()); - } - } -} diff --git a/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java b/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java deleted file mode 100644 index 5776fa318f..0000000000 --- a/src/test/java/redis/clients/jedis/tests/HostAndPortTest.java +++ /dev/null @@ -1,57 +0,0 @@ -package redis.clients.jedis.tests; - -import org.junit.Test; - -import java.util.Arrays; - -import redis.clients.jedis.HostAndPort; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; - -public class HostAndPortTest { - @Test - public void checkExtractParts() throws Exception { - String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e:1999"; - String port = "6379"; - - assertArrayEquals(new String[] { host, port }, HostAndPort.extractParts(host + ":" + port)); - - host = ""; - port = ""; - assertArrayEquals(new String[] { host, port }, HostAndPort.extractParts(host + ":" + port)); - - host = "localhost"; - port = ""; - assertArrayEquals(new String[] { host, port }, HostAndPort.extractParts(host + ":" + port)); - - host = ""; - port = "6379"; - assertArrayEquals(new String[] { host, port }, HostAndPort.extractParts(host + ":" + port)); - - host = "11:22:33:44:55"; - port = ""; - assertArrayEquals(new String[] { host, port }, HostAndPort.extractParts(host + ":" + port)); - } - - @Test - public void checkParseString() throws Exception { - String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e:1999"; - int port = 6379; - HostAndPort hp = HostAndPort.parseString(host + ":" + Integer.toString(port)); - assertEquals(host, hp.getHost()); - assertEquals(port, hp.getPort()); - } - - @Test(expected = IllegalArgumentException.class) - public void checkParseStringWithoutPort() throws Exception { - String host = "localhost"; - HostAndPort.parseString(host + ":"); - } - - @Test - public void checkConvertHost() { - String host = "2a11:1b1:0:111:e111:1f11:1111:1f1e"; - assertEquals(host, HostAndPort.convertHost(host)); - } -} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/JedisClusterCommandTest.java b/src/test/java/redis/clients/jedis/tests/JedisClusterCommandTest.java deleted file mode 100644 index 1541ca9f86..0000000000 --- a/src/test/java/redis/clients/jedis/tests/JedisClusterCommandTest.java +++ /dev/null @@ -1,371 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.ArgumentMatchers.anyLong; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.inOrder; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.when; - -import java.time.Duration; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.LongConsumer; -import org.junit.Test; -import org.mockito.InOrder; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisClusterCommand; -import redis.clients.jedis.JedisClusterConnectionHandler; -import redis.clients.jedis.JedisSlotBasedConnectionHandler; -import redis.clients.jedis.exceptions.JedisAskDataException; -import redis.clients.jedis.exceptions.JedisClusterMaxAttemptsException; -import redis.clients.jedis.exceptions.JedisClusterOperationException; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.exceptions.JedisMovedDataException; -import redis.clients.jedis.exceptions.JedisNoReachableClusterNodeException; - -public class JedisClusterCommandTest { - - private static final Duration ONE_SECOND = Duration.ofSeconds(1); - - @Test - public void runSuccessfulExecute() { - JedisClusterConnectionHandler connectionHandler = mock(JedisClusterConnectionHandler.class); - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, - Duration.ZERO) { - @Override - public String execute(Jedis connection) { - return "foo"; - } - - @Override - protected void sleep(long ignored) { - throw new RuntimeException("This test should never sleep"); - } - }; - String actual = testMe.run(""); - assertEquals("foo", actual); - } - - @Test - public void runFailOnFirstExecSuccessOnSecondExec() { - JedisClusterConnectionHandler connectionHandler = mock(JedisClusterConnectionHandler.class); - - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, - ONE_SECOND) { - boolean isFirstCall = true; - - @Override - public String execute(Jedis connection) { - if (isFirstCall) { - isFirstCall = false; - throw new JedisConnectionException("Borkenz"); - } - - return "foo"; - } - - @Override - protected void sleep(long ignored) { - throw new RuntimeException("This test should never sleep"); - } - }; - - String actual = testMe.run(""); - assertEquals("foo", actual); - } - - @Test - public void runAlwaysFailing() { - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - - final LongConsumer sleep = mock(LongConsumer.class); - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 3, - ONE_SECOND) { - @Override - public String execute(Jedis connection) { - throw new JedisConnectionException("Connection failed"); - } - - @Override - protected void sleep(long sleepMillis) { - sleep.accept(sleepMillis); - } - }; - - try { - testMe.run(""); - fail("cluster command did not fail"); - } catch (JedisClusterMaxAttemptsException e) { - // expected - } - InOrder inOrder = inOrder(connectionHandler, sleep); - inOrder.verify(connectionHandler, times(2)).getConnectionFromSlot(anyInt()); - inOrder.verify(sleep).accept(anyLong()); - inOrder.verify(connectionHandler).renewSlotCache(); - inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void runMovedSuccess() { - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - - final HostAndPort movedTarget = new HostAndPort(null, 0); - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, - ONE_SECOND) { - boolean isFirstCall = true; - - @Override - public String execute(Jedis connection) { - if (isFirstCall) { - isFirstCall = false; - - // Slot 0 moved - throw new JedisMovedDataException("", movedTarget, 0); - } - - return "foo"; - } - - @Override - protected void sleep(long ignored) { - throw new RuntimeException("This test should never sleep"); - } - }; - - String actual = testMe.run(""); - assertEquals("foo", actual); - - InOrder inOrder = inOrder(connectionHandler); - inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); - inOrder.verify(connectionHandler).renewSlotCache(any()); - inOrder.verify(connectionHandler).getConnectionFromNode(movedTarget); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void runAskSuccess() { - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - Jedis connection = mock(Jedis.class); - final HostAndPort askTarget = new HostAndPort(null, 0); - when(connectionHandler.getConnectionFromNode(askTarget)).thenReturn(connection); - - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, - ONE_SECOND) { - boolean isFirstCall = true; - - @Override - public String execute(Jedis connection) { - if (isFirstCall) { - isFirstCall = false; - - // Slot 0 moved - throw new JedisAskDataException("", askTarget, 0); - } - - return "foo"; - } - - @Override - protected void sleep(long ignored) { - throw new RuntimeException("This test should never sleep"); - } - }; - - String actual = testMe.run(""); - assertEquals("foo", actual); - - InOrder inOrder = inOrder(connectionHandler, connection); - inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); - inOrder.verify(connectionHandler).getConnectionFromNode(askTarget); - inOrder.verify(connection).asking(); - inOrder.verify(connection).close(); // From the finally clause in runWithRetries() - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void runMovedThenAllNodesFailing() { - // Test: - // First attempt is a JedisMovedDataException() move, because we asked the wrong node. - // All subsequent attempts are JedisConnectionExceptions, because all nodes are now down. - // In response to the JedisConnectionExceptions, run() retries random nodes until maxAttempts is - // reached. - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - - final Jedis redirecter = mock(Jedis.class); - when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(redirecter); - - final Jedis failer = mock(Jedis.class); - when(connectionHandler.getConnectionFromNode(any(HostAndPort.class))).thenReturn(failer); - doAnswer((Answer) (InvocationOnMock invocation) -> { - when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(failer); - return null; - }).when(connectionHandler).renewSlotCache(); - - final LongConsumer sleep = mock(LongConsumer.class); - final HostAndPort movedTarget = new HostAndPort(null, 0); - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 5, - ONE_SECOND) { - @Override - public String execute(Jedis connection) { - if (redirecter == connection) { - // First attempt, report moved - throw new JedisMovedDataException("Moved", movedTarget, 0); - } - - if (failer == connection) { - // Second attempt in response to the move, report failure - throw new JedisConnectionException("Connection failed"); - } - - throw new IllegalStateException("Should have thrown jedis exception"); - } - - @Override - protected void sleep(long sleepMillis) { - sleep.accept(sleepMillis); - } - }; - - try { - testMe.run(""); - fail("cluster command did not fail"); - } catch (JedisClusterMaxAttemptsException e) { - // expected - } - InOrder inOrder = inOrder(connectionHandler, sleep); - inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); - inOrder.verify(connectionHandler).renewSlotCache(redirecter); - inOrder.verify(connectionHandler, times(2)).getConnectionFromNode(movedTarget); - inOrder.verify(sleep).accept(anyLong()); - inOrder.verify(connectionHandler).renewSlotCache(); - inOrder.verify(connectionHandler, times(2)).getConnectionFromSlot(anyInt()); - inOrder.verify(sleep).accept(anyLong()); - inOrder.verify(connectionHandler).renewSlotCache(); - inOrder.verifyNoMoreInteractions(); - } - - @Test - public void runMasterFailingReplicaRecovering() { - // We have two nodes, master and replica, and master has just gone down permanently. - // - // Test: - // 1. We try to contact master => JedisConnectionException - // 2. We try to contact master => JedisConnectionException - // 3. sleep and renew - // 4. We try to contact replica => Success, because it has now failed over - - final Jedis master = mock(Jedis.class); - when(master.toString()).thenReturn("master"); - - final Jedis replica = mock(Jedis.class); - when(replica.toString()).thenReturn("replica"); - - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - - when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(master); - - doAnswer((Answer) (InvocationOnMock invocation) -> { - when(connectionHandler.getConnectionFromSlot(anyInt())).thenReturn(replica); - return null; - }).when(connectionHandler).renewSlotCache(); - - final AtomicLong totalSleepMs = new AtomicLong(); - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, - ONE_SECOND) { - - @Override - public String execute(Jedis connection) { - assertNotNull(connection); - - if (connection == master) { - throw new JedisConnectionException("Master is down"); - } - - assert connection == replica; - - return "Success!"; - } - - @Override - protected void sleep(long sleepMillis) { - assert sleepMillis > 0; - totalSleepMs.addAndGet(sleepMillis); - } - }; - - assertEquals("Success!", testMe.run("")); - InOrder inOrder = inOrder(connectionHandler); - inOrder.verify(connectionHandler, times(2)).getConnectionFromSlot(anyInt()); - inOrder.verify(connectionHandler).renewSlotCache(); - inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); - inOrder.verifyNoMoreInteractions(); - assertTrue(totalSleepMs.get() > 0); - } - - @Test(expected = JedisNoReachableClusterNodeException.class) - public void runRethrowsJedisNoReachableClusterNodeException() { - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - when(connectionHandler.getConnectionFromSlot(anyInt())).thenThrow( - JedisNoReachableClusterNodeException.class); - - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 10, - Duration.ZERO) { - @Override - public String execute(Jedis connection) { - return null; - } - - @Override - protected void sleep(long ignored) { - throw new RuntimeException("This test should never sleep"); - } - }; - - testMe.run(""); - } - - @Test - public void runStopsRetryingAfterTimeout() { - JedisSlotBasedConnectionHandler connectionHandler = mock(JedisSlotBasedConnectionHandler.class); - - final LongConsumer sleep = mock(LongConsumer.class); - JedisClusterCommand testMe = new JedisClusterCommand(connectionHandler, 3, - Duration.ZERO) { - @Override - public String execute(Jedis connection) { - try { - // exceed deadline - Thread.sleep(2L); - } catch (InterruptedException e) { - throw new RuntimeException(e); - } - throw new JedisConnectionException("Connection failed"); - } - - @Override - protected void sleep(long sleepMillis) { - sleep.accept(sleepMillis); - } - }; - - try { - testMe.run(""); - fail("cluster command did not fail"); - } catch (JedisClusterOperationException e) { - // expected - } - InOrder inOrder = inOrder(connectionHandler, sleep); - inOrder.verify(connectionHandler).getConnectionFromSlot(anyInt()); - inOrder.verifyNoMoreInteractions(); - } -} diff --git a/src/test/java/redis/clients/jedis/tests/KeyMergeUtilTest.java b/src/test/java/redis/clients/jedis/tests/KeyMergeUtilTest.java deleted file mode 100644 index 69ef6da49f..0000000000 --- a/src/test/java/redis/clients/jedis/tests/KeyMergeUtilTest.java +++ /dev/null @@ -1,42 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - -import org.junit.Test; - -import redis.clients.jedis.util.KeyMergeUtil; -import redis.clients.jedis.util.SafeEncoder; - -public class KeyMergeUtilTest { - - @Test - public void testMergeBinaryKeys() throws Exception { - byte[] key = SafeEncoder.encode("hello"); - byte[][] keys = new byte[2][]; - keys[0] = SafeEncoder.encode("world"); - keys[1] = SafeEncoder.encode("jedis"); - - byte[][] mergedKeys = KeyMergeUtil.merge(key, keys); - assertNotNull(mergedKeys); - assertEquals(3, mergedKeys.length); - assertEquals(key, mergedKeys[0]); - assertEquals(keys[0], mergedKeys[1]); - assertEquals(keys[1], mergedKeys[2]); - } - - @Test - public void testMergeStringKeys() throws Exception { - String key = "hello"; - String[] keys = new String[2]; - keys[0] = "world"; - keys[1] = "jedis"; - - String[] mergedKeys = KeyMergeUtil.merge(key, keys); - assertNotNull(mergedKeys); - assertEquals(3, mergedKeys.length); - assertEquals(key, mergedKeys[0]); - assertEquals(keys[0], mergedKeys[1]); - assertEquals(keys[1], mergedKeys[2]); - } -} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java b/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java deleted file mode 100644 index 0b46725fa4..0000000000 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisTest.java +++ /dev/null @@ -1,326 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import java.io.File; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URI; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLException; -import javax.net.ssl.SSLHandshakeException; -import javax.net.ssl.SSLParameters; -import javax.net.ssl.SSLPeerUnverifiedException; -import javax.net.ssl.SSLSession; -import javax.net.ssl.SSLSocketFactory; -import javax.net.ssl.TrustManager; -import javax.net.ssl.TrustManagerFactory; -import javax.net.ssl.X509TrustManager; - -import org.junit.BeforeClass; -import org.junit.Test; - -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisClientConfig; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.exceptions.JedisConnectionException; - -public class SSLJedisTest { - - @BeforeClass - public static void prepare() { - setupTrustStore(); - } - - static void setupTrustStore() { - setJvmTrustStore("src/test/resources/truststore.jceks", "jceks"); - } - - private static void setJvmTrustStore(String trustStoreFilePath, String trustStoreType) { - assertTrue(String.format("Could not find trust store at '%s'.", trustStoreFilePath), - new File(trustStoreFilePath).exists()); - System.setProperty("javax.net.ssl.trustStore", trustStoreFilePath); - System.setProperty("javax.net.ssl.trustStoreType", trustStoreType); - } - - @Test - public void connectWithSsl() { - try (Jedis jedis = new Jedis("localhost", 6390, true)) { - jedis.auth("foobared"); - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithConfig() { - try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig - .builder().ssl(true).build())) { - jedis.auth("foobared"); - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithConfigInterface() { - try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), - new JedisClientConfig() { - @Override - public boolean isSsl() { - return true; - } - })) { - jedis.auth("foobared"); - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening a default SSL/TLS connection to redis using "rediss://" scheme url. - */ - @Test - public void connectWithUrl() { - // The "rediss" scheme instructs jedis to open a SSL/TLS connection. - try (Jedis jedis = new Jedis("rediss://localhost:6390")) { - jedis.auth("foobared"); - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening a default SSL/TLS connection to redis. - */ - @Test - public void connectWithUri() { - // The "rediss" scheme instructs jedis to open a SSL/TLS connection. - try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { - jedis.auth("foobared"); - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis. - */ - @Test - public void connectWithShardInfo() throws Exception { - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - // These SSL parameters ensure that we use the same hostname verifier used - // for HTTPS. - // Note: this options is only available in Java 7. - final SSLParameters sslParameters = new SSLParameters(); - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); - - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null); - shardInfo.setPassword("foobared"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis using the loopback address of 127.0.0.1. This test - * should fail because "127.0.0.1" does not match the certificate subject common name and there - * are no subject alternative names in the certificate. - */ - @Test - public void connectWithShardInfoByIpAddress() throws Exception { - final URI uri = URI.create("rediss://127.0.0.1:6390"); - final SSLSocketFactory sslSocketFactory = createTrustStoreSslSocketFactory(); - // These SSL parameters ensure that we use the same hostname verifier used - // for HTTPS. - // Note: this options is only available in Java 7. - final SSLParameters sslParameters = new SSLParameters(); - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); - - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null); - shardInfo.setPassword("foobared"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - fail("The code did not throw the expected JedisConnectionException."); - } catch (JedisConnectionException e) { - assertEquals("Unexpected first inner exception.", - SSLHandshakeException.class, e.getCause().getClass()); - assertEquals("Unexpected second inner exception.", - CertificateException.class, e.getCause().getCause().getClass()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with a custom hostname verifier. - */ - @Test - public void connectWithShardInfoAndCustomHostnameVerifier() { - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - final SSLParameters sslParameters = new SSLParameters(); - - HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, - hostnameVerifier); - shardInfo.setPassword("foobared"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with a custom socket factory. - */ - @Test - public void connectWithShardInfoAndCustomSocketFactory() throws Exception { - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = createTrustStoreSslSocketFactory(); - final SSLParameters sslParameters = new SSLParameters(); - - HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, - hostnameVerifier); - shardInfo.setPassword("foobared"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with a custom hostname verifier. This test should - * fail because "127.0.0.1" does not match the certificate subject common name and there are no - * subject alternative names in the certificate. - */ - @Test - public void connectWithShardInfoAndCustomHostnameVerifierByIpAddress() { - final URI uri = URI.create("rediss://127.0.0.1:6390"); - final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - final SSLParameters sslParameters = new SSLParameters(); - - HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, - hostnameVerifier); - shardInfo.setPassword("foobared"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - fail("The code did not throw the expected JedisConnectionException."); - } catch (JedisConnectionException e) { - assertEquals("The JedisConnectionException does not contain the expected message.", - "The connection to '127.0.0.1' failed ssl/tls hostname verification.", e.getMessage()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with an empty certificate trust store. This test - * should fail because there is no trust anchor for the redis server certificate. - * @throws Exception - */ - @Test - public void connectWithShardInfoAndEmptyTrustStore() throws Exception { - - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = createTrustNoOneSslSocketFactory(); - - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, null, null); - shardInfo.setPassword("foobared"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - fail("The code did not throw the expected JedisConnectionException."); - } catch (JedisConnectionException e) { - assertSame("Unexpected first inner exception.", SSLException.class, - e.getCause().getClass()); - assertSame("Unexpected second inner exception.", RuntimeException.class, - e.getCause().getCause().getClass()); - assertSame("Unexpected third inner exception.", InvalidAlgorithmParameterException.class, - e.getCause().getCause().getCause().getClass()); - } - } - - /** - * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. - */ - static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { - - KeyStore trustStore = KeyStore.getInstance("jceks"); - - try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { - trustStore.load(inputStream, null); - } - - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); - trustManagerFactory.init(trustStore); - TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, trustManagers, new SecureRandom()); - return sslContext.getSocketFactory(); - } - - /** - * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. - */ - static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { - TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) { - throw new RuntimeException(new InvalidAlgorithmParameterException()); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) { - throw new RuntimeException(new InvalidAlgorithmParameterException()); - } - } }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, unTrustManagers, new SecureRandom()); - return sslContext.getSocketFactory(); - } - - /** - * Very basic hostname verifier implementation for testing. NOT recommended for production. - */ - static class BasicHostnameVerifier implements HostnameVerifier { - - private static final String COMMON_NAME_RDN_PREFIX = "CN="; - - @Override - public boolean verify(String hostname, SSLSession session) { - X509Certificate peerCertificate; - try { - peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; - } catch (SSLPeerUnverifiedException e) { - throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); - } - String peerCertificateCN = getCommonName(peerCertificate); - return hostname.equals(peerCertificateCN); - } - - private String getCommonName(X509Certificate peerCertificate) { - String subjectDN = peerCertificate.getSubjectDN().getName(); - String[] dnComponents = subjectDN.split(","); - for (String dnComponent : dnComponents) { - dnComponent = dnComponent.trim(); - if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { - return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); - } - } - throw new IllegalArgumentException("The certificate has no common name."); - } - } -} diff --git a/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java deleted file mode 100644 index 3002b25da0..0000000000 --- a/src/test/java/redis/clients/jedis/tests/SSLJedisWithCompleteCredentialsTest.java +++ /dev/null @@ -1,324 +0,0 @@ -package redis.clients.jedis.tests; - -import javax.net.ssl.*; -import java.io.FileInputStream; -import java.io.InputStream; -import java.net.URI; -import java.security.InvalidAlgorithmParameterException; -import java.security.KeyStore; -import java.security.SecureRandom; -import java.security.cert.CertificateException; -import java.security.cert.X509Certificate; - -import org.junit.BeforeClass; -import org.junit.Test; - -import redis.clients.jedis.DefaultJedisClientConfig; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.exceptions.JedisConnectionException; -import redis.clients.jedis.tests.utils.RedisVersionUtil; - -import static org.junit.Assert.*; - -/** - * This test class is a copy of {@link SSLJedisTest}. - *

- * This test is only executed when the server/cluster is Redis 6. or more. - */ -public class SSLJedisWithCompleteCredentialsTest { - - @BeforeClass - public static void prepare() { - // Use to check if the ACL test should be ran. ACL are available only in 6.0 and later - org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", - RedisVersionUtil.checkRedisMajorVersionNumber(6)); - - SSLJedisTest.setupTrustStore(); - } - - @Test - public void connectWithSsl() { - try (Jedis jedis = new Jedis("localhost", 6390, true)) { - jedis.auth("acljedis", "fizzbuzz"); - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithConfig() { - try (Jedis jedis = new Jedis(new HostAndPort("localhost", 6390), DefaultJedisClientConfig - .builder().ssl(true).build())) { - jedis.auth("acljedis", "fizzbuzz"); - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithUrl() { - // The "rediss" scheme instructs jedis to open a SSL/TLS connection. - try (Jedis jedis = new Jedis("rediss://localhost:6390")) { - jedis.auth("default", "foobared"); - assertEquals("PONG", jedis.ping()); - } - try (Jedis jedis = new Jedis("rediss://localhost:6390")) { - jedis.auth("acljedis", "fizzbuzz"); - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithCompleteCredentialsUrl() { - // The "rediss" scheme instructs jedis to open a SSL/TLS connection. - try (Jedis jedis = new Jedis("rediss://default:foobared@localhost:6390")) { - assertEquals("PONG", jedis.ping()); - } - try (Jedis jedis = new Jedis("rediss://acljedis:fizzbuzz@localhost:6390")) { - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithUri() { - // The "rediss" scheme instructs jedis to open a SSL/TLS connection. - try (Jedis jedis = new Jedis(URI.create("rediss://localhost:6390"))) { - jedis.auth("acljedis", "fizzbuzz"); - assertEquals("PONG", jedis.ping()); - } - } - - @Test - public void connectWithCompleteCredentialsUri() { - // The "rediss" scheme instructs jedis to open a SSL/TLS connection. - try (Jedis jedis = new Jedis(URI.create("rediss://default:foobared@localhost:6390"))) { - assertEquals("PONG", jedis.ping()); - } - try (Jedis jedis = new Jedis(URI.create("rediss://acljedis:fizzbuzz@localhost:6390"))) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis. NOTE: This test relies on a feature that is only - * available as of Java 7 and later. It is commented out but not removed in case support for Java - * 6 is dropped or we find a way to have the CI run a specific set of tests on Java 7 and above. - */ - @Test - public void connectWithShardInfo() throws Exception { - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - // These SSL parameters ensure that we use the same hostname verifier used - // for HTTPS. - // Note: this options is only available in Java 7. - final SSLParameters sslParameters = new SSLParameters(); - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); - - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis using the loopback address of 127.0.0.1. This test - * should fail because "127.0.0.1" does not match the certificate subject common name and there - * are no subject alternative names in the certificate. NOTE: This test relies on a feature that - * is only available as of Java 7 and later. It is commented out but not removed in case support - * for Java 6 is dropped or we find a way to have the CI run a specific set of tests on Java 7 and - * above. - */ - @Test - public void connectWithShardInfoByIpAddress() throws Exception { - final URI uri = URI.create("rediss://127.0.0.1:6390"); - final SSLSocketFactory sslSocketFactory = createTrustStoreSslSocketFactory(); - // These SSL parameters ensure that we use the same hostname verifier used - // for HTTPS. - // Note: this options is only available in Java 7. - final SSLParameters sslParameters = new SSLParameters(); - sslParameters.setEndpointIdentificationAlgorithm("HTTPS"); - - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, null); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - fail("The code did not throw the expected JedisConnectionException."); - } catch (JedisConnectionException e) { - assertSame("Unexpected first inner exception.", SSLHandshakeException.class, e.getCause() - .getClass()); - assertSame("Unexpected second inner exception.", CertificateException.class, e.getCause() - .getCause().getClass()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with a custom hostname verifier. - */ - @Test - public void connectWithShardInfoAndCustomHostnameVerifier() { - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - final SSLParameters sslParameters = new SSLParameters(); - - HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, - hostnameVerifier); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with a custom socket factory. - */ - @Test - public void connectWithShardInfoAndCustomSocketFactory() throws Exception { - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = createTrustStoreSslSocketFactory(); - final SSLParameters sslParameters = new SSLParameters(); - - HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, - hostnameVerifier); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with a custom hostname verifier. This test should - * fail because "127.0.0.1" does not match the certificate subject common name and there are no - * subject alternative names in the certificate. - */ - @Test - public void connectWithShardInfoAndCustomHostnameVerifierByIpAddress() { - final URI uri = URI.create("rediss://127.0.0.1:6390"); - final SSLSocketFactory sslSocketFactory = (SSLSocketFactory) SSLSocketFactory.getDefault(); - final SSLParameters sslParameters = new SSLParameters(); - - HostnameVerifier hostnameVerifier = new BasicHostnameVerifier(); - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, sslParameters, - hostnameVerifier); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - fail("The code did not throw the expected JedisConnectionException."); - } catch (JedisConnectionException e) { - assertEquals("The JedisConnectionException does not contain the expected message.", - "The connection to '127.0.0.1' failed ssl/tls hostname verification.", e.getMessage()); - } - } - - /** - * Tests opening an SSL/TLS connection to redis with an empty certificate trust store. This test - * should fail because there is no trust anchor for the redis server certificate. - * @throws Exception - */ - @Test - public void connectWithShardInfoAndEmptyTrustStore() throws Exception { - - final URI uri = URI.create("rediss://localhost:6390"); - final SSLSocketFactory sslSocketFactory = createTrustNoOneSslSocketFactory(); - - JedisShardInfo shardInfo = new JedisShardInfo(uri, sslSocketFactory, null, null); - shardInfo.setUser("acljedis"); - shardInfo.setPassword("fizzbuzz"); - - try (Jedis jedis = new Jedis(shardInfo)) { - assertEquals("PONG", jedis.ping()); - fail("The code did not throw the expected JedisConnectionException."); - } catch (JedisConnectionException e) { - assertSame("Unexpected first inner exception.", SSLException.class, e.getCause().getClass()); - assertSame("Unexpected second inner exception.", RuntimeException.class, e.getCause() - .getCause().getClass()); - assertSame("Unexpected third inner exception.", InvalidAlgorithmParameterException.class, e - .getCause().getCause().getCause().getClass()); - } - } - - /** - * Creates an SSLSocketFactory that trusts all certificates in truststore.jceks. - */ - static SSLSocketFactory createTrustStoreSslSocketFactory() throws Exception { - - KeyStore trustStore = KeyStore.getInstance("jceks"); - try (InputStream inputStream = new FileInputStream("src/test/resources/truststore.jceks")) { - trustStore.load(inputStream, null); - } - - TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("PKIX"); - trustManagerFactory.init(trustStore); - TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); - - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, trustManagers, new SecureRandom()); - return sslContext.getSocketFactory(); - } - - /** - * Creates an SSLSocketFactory with a trust manager that does not trust any certificates. - */ - static SSLSocketFactory createTrustNoOneSslSocketFactory() throws Exception { - TrustManager[] unTrustManagers = new TrustManager[] { new X509TrustManager() { - public X509Certificate[] getAcceptedIssuers() { - return new X509Certificate[0]; - } - - public void checkClientTrusted(X509Certificate[] chain, String authType) { - throw new RuntimeException(new InvalidAlgorithmParameterException()); - } - - public void checkServerTrusted(X509Certificate[] chain, String authType) { - throw new RuntimeException(new InvalidAlgorithmParameterException()); - } - } }; - SSLContext sslContext = SSLContext.getInstance("TLS"); - sslContext.init(null, unTrustManagers, new SecureRandom()); - return sslContext.getSocketFactory(); - } - - /** - * Very basic hostname verifier implementation for testing. NOT recommended for production. - */ - static class BasicHostnameVerifier implements HostnameVerifier { - - private static final String COMMON_NAME_RDN_PREFIX = "CN="; - - @Override - public boolean verify(String hostname, SSLSession session) { - X509Certificate peerCertificate; - try { - peerCertificate = (X509Certificate) session.getPeerCertificates()[0]; - } catch (SSLPeerUnverifiedException e) { - throw new IllegalStateException("The session does not contain a peer X.509 certificate.", e); - } - String peerCertificateCN = getCommonName(peerCertificate); - return hostname.equals(peerCertificateCN); - } - - private String getCommonName(X509Certificate peerCertificate) { - String subjectDN = peerCertificate.getSubjectDN().getName(); - String[] dnComponents = subjectDN.split(","); - for (String dnComponent : dnComponents) { - dnComponent = dnComponent.trim(); - if (dnComponent.startsWith(COMMON_NAME_RDN_PREFIX)) { - return dnComponent.substring(COMMON_NAME_RDN_PREFIX.length()); - } - } - throw new IllegalArgumentException("The certificate has no common name."); - } - } -} diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java deleted file mode 100644 index eab05eeef5..0000000000 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolTest.java +++ /dev/null @@ -1,258 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertTrue; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicInteger; - -import org.apache.commons.pool2.PooledObject; -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.junit.Before; -import org.junit.Test; - -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.ShardedJedis; -import redis.clients.jedis.ShardedJedisPool; -import redis.clients.jedis.exceptions.JedisExhaustedPoolException; -import redis.clients.jedis.util.Hashing; - -public class ShardedJedisPoolTest { - private static HostAndPort redis1 = HostAndPortUtil.getRedisServers().get(0); - private static HostAndPort redis2 = HostAndPortUtil.getRedisServers().get(1); - - private List shards; - - @Before - public void startUp() { - shards = new ArrayList<>(); - shards.add(new JedisShardInfo(redis1)); - shards.add(new JedisShardInfo(redis2)); - shards.get(0).setPassword("foobared"); - shards.get(1).setPassword("foobared"); - - for (JedisShardInfo shard : shards) { - try (Jedis j = new Jedis(shard)) { - j.flushAll(); - } - } - } - - @Test - public void checkConnections() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - jedis.close(); - pool.destroy(); - } - - @Test - public void checkCloseableConnections() throws Exception { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - jedis.close(); - pool.close(); - assertTrue(pool.isClosed()); - } - - @Test - public void checkConnectionWithDefaultPort() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - jedis.close(); - pool.destroy(); - } - - @Test - public void checkJedisIsReusedWhenReturned() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "0"); - jedis.close(); - - jedis = pool.getResource(); - jedis.incr("foo"); - jedis.close(); - pool.destroy(); - } - - @Test - public void checkPoolRepairedWhenJedisIsBroken() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.disconnect(); - jedis.close(); - - jedis = pool.getResource(); - jedis.incr("foo"); - jedis.close(); - pool.destroy(); - } - - @Test(expected = JedisExhaustedPoolException.class) - public void checkPoolOverflow() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - - ShardedJedisPool pool = new ShardedJedisPool(config, shards); - - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "0"); - - ShardedJedis newJedis = pool.getResource(); - newJedis.incr("foo"); - } - - @Test - public void shouldNotShareInstances() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setMaxTotal(2); - - ShardedJedisPool pool = new ShardedJedisPool(config, shards); - - ShardedJedis j1 = pool.getResource(); - ShardedJedis j2 = pool.getResource(); - - assertNotSame(j1.getShard("foo"), j2.getShard("foo")); - } - - @Test - public void checkFailedJedisServer() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.incr("foo"); - jedis.close(); - pool.destroy(); - } - - @Test - public void startWithUrlString() { - Jedis j = new Jedis("localhost", 6380); - j.auth("foobared"); - j.set("foo", "bar"); - j.disconnect(); - - j = new Jedis("localhost", 6379); - j.auth("foobared"); - j.set("foo", "bar"); - j.disconnect(); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo("redis://:foobared@localhost:6380")); - shards.add(new JedisShardInfo("redis://:foobared@localhost:6379")); - - GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); - ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - - Jedis jedis = jedises[0]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - - jedis = jedises[1]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - } - - @Test - public void startWithUrl() throws URISyntaxException { - Jedis j = new Jedis("localhost", 6380); - j.auth("foobared"); - j.set("foo", "bar"); - j.disconnect(); - - j = new Jedis("localhost", 6379); - j.auth("foobared"); - j.set("foo", "bar"); - j.disconnect(); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6380"))); - shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6379"))); - - GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig(); - ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - - Jedis jedis = jedises[0]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - - jedis = jedises[1]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - } - - @Test - public void checkResourceIsCloseable() throws URISyntaxException { - GenericObjectPoolConfig config = new GenericObjectPoolConfig(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6380"))); - shards.add(new JedisShardInfo(new URI("redis://:foobared@localhost:6379"))); - - ShardedJedisPool pool = new ShardedJedisPool(config, shards); - - ShardedJedis jedis = pool.getResource(); - try { - jedis.set("hello", "jedis"); - } finally { - jedis.close(); - } - - ShardedJedis jedis2 = pool.getResource(); - try { - assertEquals(jedis, jedis2); - } finally { - jedis2.close(); - } - } - - @Test - public void checkOverrideFactoryValidateMethod() { - AtomicInteger counter = new AtomicInteger(0); - - ShardedJedisPool.ShardedJedisFactory overriddenFactory = new ShardedJedisPool.ShardedJedisFactory( - shards, Hashing.MURMUR_HASH, null) { - @Override public boolean validateObject(PooledObject pooledShardedJedis) { - counter.incrementAndGet(); - return super.validateObject(pooledShardedJedis); - } - }; - - GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig<>(); - poolConfig.setTestOnReturn(true); - ShardedJedisPool pool = new ShardedJedisPool(poolConfig, overriddenFactory); - try (ShardedJedis jedis = pool.getResource();) { - jedis.set("foo", "bar"); - assertEquals(0, counter.get()); - } - assertEquals(1, counter.get()); - - pool.destroy(); - } - -} diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolWithCompleteCredentialsTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolWithCompleteCredentialsTest.java deleted file mode 100644 index aaf38b499d..0000000000 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisPoolWithCompleteCredentialsTest.java +++ /dev/null @@ -1,274 +0,0 @@ -package redis.clients.jedis.tests; - -import org.apache.commons.pool2.impl.GenericObjectPoolConfig; -import org.junit.Before; -import org.junit.BeforeClass; -import org.junit.Test; -import redis.clients.jedis.*; -import redis.clients.jedis.exceptions.JedisExhaustedPoolException; -import redis.clients.jedis.tests.utils.RedisVersionUtil; - -import java.net.URI; -import java.net.URISyntaxException; -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.*; - -/** - * This test class is a copy of {@link ShardedJedisPoolTest} where all authentications are made with - * default:foobared credentials information - *

- * This test is only executed when the server/cluster is Redis 6. or more. - */ -public class ShardedJedisPoolWithCompleteCredentialsTest { - private static HostAndPort redis1 = HostAndPortUtil.getRedisServers().get(0); - private static HostAndPort redis2 = HostAndPortUtil.getRedisServers().get(1); - - private List shards; - - @BeforeClass - public static void shouldRun() throws Exception { - org.junit.Assume.assumeTrue("Not running ACL test on this version of Redis", - RedisVersionUtil.checkRedisMajorVersionNumber(6)); - } - - @Before - public void startUp() { - shards = new ArrayList<>(); - shards.add(new JedisShardInfo(redis1)); - shards.add(new JedisShardInfo(redis2)); - shards.get(0).setUser("default"); - shards.get(0).setPassword("foobared"); - shards.get(1).setUser("default"); - shards.get(1).setPassword("foobared"); - - for (JedisShardInfo shard : shards) { - try (Jedis j = new Jedis(shard)) { - j.flushAll(); - } - } - } - - @Test - public void checkConnections() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - jedis.close(); - pool.destroy(); - } - - @Test - public void checkCloseableConnections() throws Exception { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - jedis.close(); - pool.close(); - assertTrue(pool.isClosed()); - } - - @Test - public void checkConnectionWithDefaultPort() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "bar"); - assertEquals("bar", jedis.get("foo")); - jedis.close(); - pool.destroy(); - } - - @Test - public void checkJedisIsReusedWhenReturned() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "0"); - jedis.close(); - - jedis = pool.getResource(); - jedis.incr("foo"); - jedis.close(); - pool.destroy(); - } - - @Test - public void checkPoolRepairedWhenJedisIsBroken() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.disconnect(); - jedis.close(); - - jedis = pool.getResource(); - jedis.incr("foo"); - jedis.close(); - pool.destroy(); - } - - @Test(expected = JedisExhaustedPoolException.class) - public void checkPoolOverflow() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - - ShardedJedisPool pool = new ShardedJedisPool(config, shards); - - ShardedJedis jedis = pool.getResource(); - jedis.set("foo", "0"); - - ShardedJedis newJedis = pool.getResource(); - newJedis.incr("foo"); - } - - @Test - public void shouldNotShareInstances() { - GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); - config.setMaxTotal(2); - - ShardedJedisPool pool = new ShardedJedisPool(config, shards); - - ShardedJedis j1 = pool.getResource(); - ShardedJedis j2 = pool.getResource(); - - assertNotSame(j1.getShard("foo"), j2.getShard("foo")); - } - - @Test - public void checkFailedJedisServer() { - ShardedJedisPool pool = new ShardedJedisPool(new GenericObjectPoolConfig(), - shards); - ShardedJedis jedis = pool.getResource(); - jedis.incr("foo"); - jedis.close(); - pool.destroy(); - } - - @Test - public void startWithUrlString() { - Jedis j = new Jedis("localhost", 6380); - j.auth("default", "foobared"); - j.set("foo", "bar"); - - j = new Jedis("localhost", 6379); - j.auth("default", "foobared"); - j.set("foo", "bar"); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo("redis://default:foobared@localhost:6380")); - shards.add(new JedisShardInfo("redis://default:foobared@localhost:6379")); - - GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig<>(); - ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - - Jedis jedis = jedises[0]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - - jedis = jedises[1]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - } - - @Test - public void startWithUrl() throws URISyntaxException { - Jedis j = new Jedis("localhost", 6380); - j.auth("default", "foobared"); - j.set("foo", "bar"); - - j = new Jedis("localhost", 6379); - j.auth("default", "foobared"); - j.set("foo", "bar"); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo(new URI("redis://default:foobared@localhost:6380"))); - shards.add(new JedisShardInfo(new URI("redis://default:foobared@localhost:6379"))); - - GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig<>(); - ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - - Jedis jedis = jedises[0]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - - jedis = jedises[1]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - } - - @Test - public void connectWithURICredentials() throws URISyntaxException { - Jedis j1 = new Jedis("localhost", 6380); - j1.auth("default", "foobared"); - j1.set("foo", "bar"); - - // create user in shard 1 - j1.aclSetUser("alice", "on", ">alicePassword", "~*", "+@all"); - - Jedis j2 = new Jedis("localhost", 6379); - j2.auth("default", "foobared"); - j2.set("foo", "bar"); - - // create user in shard 2 - j2.aclSetUser("alice", "on", ">alicePassword", "~*", "+@all"); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo(new URI("redis://alice:alicePassword@localhost:6380"))); - shards.add(new JedisShardInfo(new URI("redis://alice:alicePassword@localhost:6379"))); - - GenericObjectPoolConfig redisConfig = new GenericObjectPoolConfig<>(); - ShardedJedisPool pool = new ShardedJedisPool(redisConfig, shards); - - Jedis[] jedises = pool.getResource().getAllShards().toArray(new Jedis[2]); - - Jedis jedis = jedises[0]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - - jedis = jedises[1]; - assertEquals("PONG", jedis.ping()); - assertEquals("bar", jedis.get("foo")); - - // delete user - j1.aclDelUser("alice"); - j2.aclDelUser("alice"); - } - - @Test - public void checkResourceIsCloseable() throws URISyntaxException { - GenericObjectPoolConfig config = new GenericObjectPoolConfig<>(); - config.setMaxTotal(1); - config.setBlockWhenExhausted(false); - - List shards = new ArrayList(); - shards.add(new JedisShardInfo(new URI("redis://default:foobared@localhost:6380"))); - shards.add(new JedisShardInfo(new URI("redis://default:foobared@localhost:6379"))); - - ShardedJedisPool pool = new ShardedJedisPool(config, shards); - - ShardedJedis jedis = pool.getResource(); - try { - jedis.set("hello", "jedis"); - } finally { - jedis.close(); - } - - ShardedJedis jedis2 = pool.getResource(); - try { - assertEquals(jedis, jedis2); - } finally { - jedis2.close(); - } - } - -} diff --git a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java b/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java deleted file mode 100644 index 5c914dd836..0000000000 --- a/src/test/java/redis/clients/jedis/tests/ShardedJedisTest.java +++ /dev/null @@ -1,361 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotSame; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; -import static redis.clients.jedis.Protocol.Command.PING; -import static redis.clients.jedis.Protocol.Command.SET; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; - -import org.junit.Test; - -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.ShardedJedis; -import redis.clients.jedis.tests.utils.ClientKillerUtil; -import redis.clients.jedis.util.Hashing; -import redis.clients.jedis.util.SafeEncoder; -import redis.clients.jedis.util.Sharded; - -public class ShardedJedisTest { - private static HostAndPort redis1 = HostAndPortUtil.getRedisServers().get(0); - private static HostAndPort redis2 = HostAndPortUtil.getRedisServers().get(1); - - /** - * Test for "Issue - BinaryShardedJedis.disconnect() may occur memory leak". You can find more - * detailed information at https://github.com/xetorthio/jedis/issues/808 - * @throws InterruptedException - */ - @Test - public void testAvoidLeaksUponDisconnect() throws InterruptedException { - List shards = new ArrayList(2); - // 6379 - JedisShardInfo shard1 = new JedisShardInfo(redis1); - shard1.setPassword("foobared"); - shards.add(shard1); - // 6380 - JedisShardInfo shard2 = new JedisShardInfo(redis2); - shard2.setPassword("foobared"); - shards.add(shard2); - - @SuppressWarnings("resource") - ShardedJedis shardedJedis = new ShardedJedis(shards); - // establish the connection for two redis servers - shardedJedis.set("a", "bar"); - JedisShardInfo ak = shardedJedis.getShardInfo("a"); - assertEquals(shard2, ak); - shardedJedis.set("b", "bar1"); - JedisShardInfo bk = shardedJedis.getShardInfo("b"); - assertEquals(shard1, bk); - - // We set a name to the instance so it's easy to find it - Iterator it = shardedJedis.getAllShards().iterator(); - Jedis deadClient = it.next(); - deadClient.clientSetname("DEAD"); - - ClientKillerUtil.killClient(deadClient, "DEAD"); - - assertTrue(deadClient.isConnected()); - assertFalse(deadClient.getClient().getSocket().isClosed()); - assertFalse(deadClient.isBroken()); // normal - not found - - shardedJedis.disconnect(); - - assertFalse(deadClient.isConnected()); - assertTrue(deadClient.getClient().getSocket().isClosed()); - assertTrue(deadClient.isBroken()); - - Jedis jedis2 = it.next(); - assertFalse(jedis2.isConnected()); - assertTrue(jedis2.getClient().getSocket().isClosed()); - assertFalse(jedis2.isBroken()); - - } - - private List getKeysDifferentShard(ShardedJedis jedis) { - List ret = new ArrayList(); - JedisShardInfo first = jedis.getShardInfo("a0"); - ret.add("a0"); - for (int i = 1; i < 100; ++i) { - JedisShardInfo actual = jedis.getShardInfo("a" + i); - if (actual != first) { - ret.add("a" + i); - break; - - } - - } - return ret; - } - - @Test - public void checkSharding() { - List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1)); - shards.add(new JedisShardInfo(redis2)); - ShardedJedis jedis = new ShardedJedis(shards); - List keys = getKeysDifferentShard(jedis); - JedisShardInfo s1 = jedis.getShardInfo(keys.get(0)); - JedisShardInfo s2 = jedis.getShardInfo(keys.get(1)); - assertNotSame(s1, s2); - } - - @Test - public void trySharding() { - List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1); - si.setPassword("foobared"); - shards.add(si); - si = new JedisShardInfo(redis2); - si.setPassword("foobared"); - shards.add(si); - ShardedJedis jedis = new ShardedJedis(shards); - jedis.set("a", "bar"); - JedisShardInfo s1 = jedis.getShardInfo("a"); - jedis.set("b", "bar1"); - JedisShardInfo s2 = jedis.getShardInfo("b"); - jedis.disconnect(); - - Jedis j = new Jedis(s1); - j.auth("foobared"); - assertEquals("bar", j.get("a")); - j.disconnect(); - - j = new Jedis(s2); - j.auth("foobared"); - assertEquals("bar1", j.get("b")); - j.disconnect(); - } - - @Test - public void tryShardingWithMurmure() { - List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1); - si.setPassword("foobared"); - shards.add(si); - si = new JedisShardInfo(redis2); - si.setPassword("foobared"); - shards.add(si); - ShardedJedis jedis = new ShardedJedis(shards, Hashing.MURMUR_HASH); - jedis.set("a", "bar"); - JedisShardInfo s1 = jedis.getShardInfo("a"); - jedis.set("b", "bar1"); - JedisShardInfo s2 = jedis.getShardInfo("b"); - jedis.disconnect(); - - Jedis j = new Jedis(s1); - j.auth("foobared"); - assertEquals("bar", j.get("a")); - j.disconnect(); - - j = new Jedis(s2); - j.auth("foobared"); - assertEquals("bar1", j.get("b")); - j.disconnect(); - } - - @Test - public void checkKeyTags() { - List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1)); - shards.add(new JedisShardInfo(redis2)); - ShardedJedis jedis = new ShardedJedis(shards, ShardedJedis.DEFAULT_KEY_TAG_PATTERN); - - assertEquals("foo", jedis.getKeyTag("foo")); - assertEquals("bar", jedis.getKeyTag("foo{bar}")); - assertEquals("bar", jedis.getKeyTag("foo{bar}}")); // Default pattern is non greedy - assertEquals("bar", jedis.getKeyTag("{bar}foo")); // Key tag may appear anywhere - assertEquals("bar", jedis.getKeyTag("f{bar}oo")); // Key tag may appear anywhere - - JedisShardInfo s1 = jedis.getShardInfo("abc{bar}"); - JedisShardInfo s2 = jedis.getShardInfo("foo{bar}"); - assertSame(s1, s2); - - List keys = getKeysDifferentShard(jedis); - JedisShardInfo s3 = jedis.getShardInfo(keys.get(0)); - JedisShardInfo s4 = jedis.getShardInfo(keys.get(1)); - assertNotSame(s3, s4); - - ShardedJedis jedis2 = new ShardedJedis(shards); - - assertEquals("foo", jedis2.getKeyTag("foo")); - assertNotEquals("bar", jedis2.getKeyTag("foo{bar}")); - - JedisShardInfo s5 = jedis2.getShardInfo(keys.get(0) + "{bar}"); - JedisShardInfo s6 = jedis2.getShardInfo(keys.get(1) + "{bar}"); - assertNotSame(s5, s6); - } - - @Test - public void testMD5Sharding() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); - Sharded sharded = new Sharded(shards, Hashing.MD5); - int shard_6379 = 0; - int shard_6380 = 0; - int shard_6381 = 0; - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer.toString(i)); - switch (jedisShardInfo.getPort()) { - case 6379: - shard_6379++; - break; - case 6380: - shard_6380++; - break; - case 6381: - shard_6381++; - break; - default: - fail("Attempting to use a non-defined shard!!:" + jedisShardInfo); - break; - } - } - assertTrue(shard_6379 > 300 && shard_6379 < 400); - assertTrue(shard_6380 > 300 && shard_6380 < 400); - assertTrue(shard_6381 > 300 && shard_6381 < 400); - } - - @Test - public void testMurmurSharding() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); - Sharded sharded = new Sharded(shards, - Hashing.MURMUR_HASH); - int shard_6379 = 0; - int shard_6380 = 0; - int shard_6381 = 0; - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer.toString(i)); - switch (jedisShardInfo.getPort()) { - case 6379: - shard_6379++; - break; - case 6380: - shard_6380++; - break; - case 6381: - shard_6381++; - break; - default: - fail("Attempting to use a non-defined shard!!:" + jedisShardInfo); - break; - } - } - assertTrue(shard_6379 > 300 && shard_6379 < 400); - assertTrue(shard_6380 > 300 && shard_6380 < 400); - assertTrue(shard_6381 > 300 && shard_6381 < 400); - } - - @Test - public void testMasterSlaveShardingConsistency() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1)); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2)); - Sharded sharded = new Sharded(shards, - Hashing.MURMUR_HASH); - - List otherShards = new ArrayList(3); - otherShards.add(new JedisShardInfo("127.0.0.1", Protocol.DEFAULT_PORT)); - otherShards.add(new JedisShardInfo("127.0.0.1", Protocol.DEFAULT_PORT + 1)); - otherShards.add(new JedisShardInfo("127.0.0.1", Protocol.DEFAULT_PORT + 2)); - Sharded sharded2 = new Sharded(otherShards, - Hashing.MURMUR_HASH); - - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer.toString(i)); - JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer.toString(i)); - assertEquals(shards.indexOf(jedisShardInfo), otherShards.indexOf(jedisShardInfo2)); - } - - } - - @Test - public void testMasterSlaveShardingConsistencyWithShardNaming() { - List shards = new ArrayList(3); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT, "HOST1:1234")); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 1, "HOST2:1234")); - shards.add(new JedisShardInfo("localhost", Protocol.DEFAULT_PORT + 2, "HOST3:1234")); - Sharded sharded = new Sharded(shards, - Hashing.MURMUR_HASH); - - List otherShards = new ArrayList(3); - otherShards.add(new JedisShardInfo("127.0.0.1", Protocol.DEFAULT_PORT, "HOST2:1234")); - otherShards.add(new JedisShardInfo("127.0.0.1", Protocol.DEFAULT_PORT + 1, "HOST3:1234")); - otherShards.add(new JedisShardInfo("127.0.0.1", Protocol.DEFAULT_PORT + 2, "HOST1:1234")); - Sharded sharded2 = new Sharded(otherShards, - Hashing.MURMUR_HASH); - - for (int i = 0; i < 1000; i++) { - JedisShardInfo jedisShardInfo = sharded.getShardInfo(Integer.toString(i)); - JedisShardInfo jedisShardInfo2 = sharded2.getShardInfo(Integer.toString(i)); - assertEquals(jedisShardInfo.getName(), jedisShardInfo2.getName()); - } - } - - @Test - public void checkCloseable() { - List shards = new ArrayList(); - shards.add(new JedisShardInfo(redis1)); - shards.add(new JedisShardInfo(redis2)); - shards.get(0).setPassword("foobared"); - shards.get(1).setPassword("foobared"); - - ShardedJedis jedisShard = new ShardedJedis(shards); - try { - jedisShard.set("shard_closeable", "true"); - } finally { - jedisShard.close(); - } - - for (Jedis jedis : jedisShard.getAllShards()) { - assertTrue(!jedis.isConnected()); - } - } - - @Test - public void testGeneralCommand() { - - List shards = new ArrayList(); - JedisShardInfo si = new JedisShardInfo(redis1); - si.setPassword("foobared"); - shards.add(si); - si = new JedisShardInfo(redis2); - si.setPassword("foobared"); - shards.add(si); - ShardedJedis jedis = new ShardedJedis(shards); - jedis.sendCommand(SET, "a", "bar"); - JedisShardInfo s1 = jedis.getShardInfo("a"); - jedis.sendCommand(SET, "b", "bar1"); - JedisShardInfo s2 = jedis.getShardInfo("b"); - jedis.disconnect(); - - Jedis j = new Jedis(s1); - j.auth("foobared"); - assertEquals("bar", j.get("a")); - j.disconnect(); - - j = new Jedis(s2); - j.auth("foobared"); - assertEquals("bar1", j.get("b")); - j.disconnect(); - - assertEquals("PONG", SafeEncoder.encode((byte[]) jedis.sendCommand(PING))); - - } - -} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/TupleSortedSetTest.java b/src/test/java/redis/clients/jedis/tests/TupleSortedSetTest.java deleted file mode 100644 index 35665b7182..0000000000 --- a/src/test/java/redis/clients/jedis/tests/TupleSortedSetTest.java +++ /dev/null @@ -1,80 +0,0 @@ -package redis.clients.jedis.tests; - -import static org.junit.Assert.assertEquals; - -import java.util.Set; -import java.util.SortedSet; -import java.util.TreeSet; - -import org.junit.Test; - -import redis.clients.jedis.Tuple; -import redis.clients.jedis.tests.commands.JedisCommandTestBase; - -public class TupleSortedSetTest extends JedisCommandTestBase { - final byte[] bfoo = { 0x01, 0x02, 0x03, 0x04 }; - final byte[] ba = { 0x0A }; - final byte[] bb = { 0x0B }; - final byte[] bc = { 0x0C }; - final byte[] bd = { 0x0D }; - final byte[] be = { 0x0E }; - final byte[] bf = { 0x0F }; - - @Test - public void testBinary() { - SortedSet sortedSet = new TreeSet(); - - jedis.zadd(bfoo, 0d, ba); - sortedSet.add(new Tuple(ba, 0d)); - - jedis.zadd(bfoo, 1d, bb); - sortedSet.add(new Tuple(bb, 1d)); - - Set zrange = jedis.zrangeWithScores(bfoo, 0, -1); - assertEquals(sortedSet, zrange); - - jedis.zadd(bfoo, -0.3, bc); - sortedSet.add(new Tuple(bc, -0.3)); - - jedis.zadd(bfoo, 0.3, bf); - sortedSet.add(new Tuple(bf, 0.3)); - - jedis.zadd(bfoo, 0.3, be); - sortedSet.add(new Tuple(be, 0.3)); - - jedis.zadd(bfoo, 0.3, bd); - sortedSet.add(new Tuple(bd, 0.3)); - - zrange = jedis.zrangeWithScores(bfoo, 0, -1); - assertEquals(sortedSet, zrange); - } - - @Test - public void testString() { - SortedSet sortedSet = new TreeSet(); - - jedis.zadd("foo", 0d, "a"); - sortedSet.add(new Tuple("a", 0d)); - - jedis.zadd("foo", 1d, "b"); - sortedSet.add(new Tuple("b", 1d)); - - Set range = jedis.zrangeWithScores("foo", 0, -1); - assertEquals(sortedSet, range); - - jedis.zadd("foo", -0.3, "c"); - sortedSet.add(new Tuple("c", -0.3)); - - jedis.zadd("foo", 0.3, "f"); - sortedSet.add(new Tuple("f", 0.3)); - - jedis.zadd("foo", 0.3, "e"); - sortedSet.add(new Tuple("e", 0.3)); - - jedis.zadd("foo", 0.3, "d"); - sortedSet.add(new Tuple("d", 0.3)); - - range = jedis.zrangeWithScores("foo", 0, -1); - assertEquals(sortedSet, range); - } -} diff --git a/src/test/java/redis/clients/jedis/tests/UdsTest.java b/src/test/java/redis/clients/jedis/tests/UdsTest.java deleted file mode 100644 index 699503684f..0000000000 --- a/src/test/java/redis/clients/jedis/tests/UdsTest.java +++ /dev/null @@ -1,88 +0,0 @@ -package redis.clients.jedis.tests; - -import java.io.File; -import java.io.IOException; -import java.net.Socket; -import org.junit.Test; -import org.newsclub.net.unix.AFUNIXSocket; -import org.newsclub.net.unix.AFUNIXSocketAddress; - -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisSocketFactory; -import redis.clients.jedis.Protocol; -import redis.clients.jedis.exceptions.JedisConnectionException; - -import static org.junit.Assert.assertEquals; - -public class UdsTest { - - @Test - public void testConnectsToUds() { - try (Jedis jedis = new Jedis(new UdsJedisSocketFactory())) { - assertEquals("PONG", jedis.ping()); - } - } - - private static class UdsJedisSocketFactory implements JedisSocketFactory { - - private static final File UDS_SOCKET = new File("/tmp/redis_uds.sock"); - - @Override - public Socket createSocket() throws JedisConnectionException { - try { - Socket socket = AFUNIXSocket.newStrictInstance(); - socket.connect(new AFUNIXSocketAddress(UDS_SOCKET), Protocol.DEFAULT_TIMEOUT); - return socket; - } catch (IOException ioe) { - throw new JedisConnectionException("Failed to create UDS connection.", ioe); - } - } - - @Override - public void updateHostAndPort(HostAndPort hostAndPort) { - throw new UnsupportedOperationException("UDS cannot update host and port"); - } - - @Override - public String getDescription() { - return UDS_SOCKET.toString(); - } - - @Override - public String getHost() { - return UDS_SOCKET.toString(); - } - - @Override - public void setHost(String host) { - } - - @Override - public int getPort() { - return 0; - } - - @Override - public void setPort(int port) { - } - - @Override - public int getConnectionTimeout() { - return Protocol.DEFAULT_TIMEOUT; - } - - @Override - public void setConnectionTimeout(int connectionTimeout) { - } - - @Override - public int getSoTimeout() { - return Protocol.DEFAULT_TIMEOUT; - } - - @Override - public void setSoTimeout(int soTimeout) { - } - } -} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java b/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java deleted file mode 100644 index c6e9c87d2b..0000000000 --- a/src/test/java/redis/clients/jedis/tests/benchmark/HashingBenchmark.java +++ /dev/null @@ -1,49 +0,0 @@ -package redis.clients.jedis.tests.benchmark; - -import java.io.IOException; -import java.net.UnknownHostException; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Collection; -import java.util.List; - -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.JedisShardInfo; -import redis.clients.jedis.ShardedJedis; -import redis.clients.jedis.tests.HostAndPortUtil; - -public class HashingBenchmark { - private static HostAndPort hnp1 = HostAndPortUtil.getRedisServers().get(0); - private static HostAndPort hnp2 = HostAndPortUtil.getRedisServers().get(1); - private static final int TOTAL_OPERATIONS = 100000; - - public static void main(String[] args) throws UnknownHostException, IOException { - List shards = new ArrayList(); - JedisShardInfo shard = new JedisShardInfo(hnp1); - shard.setPassword("foobared"); - shards.add(shard); - shard = new JedisShardInfo(hnp2); - shard.setPassword("foobared"); - shards.add(shard); - ShardedJedis jedis = new ShardedJedis(shards); - Collection allShards = jedis.getAllShards(); - for (Jedis j : allShards) { - j.flushAll(); - } - - long begin = Calendar.getInstance().getTimeInMillis(); - - for (int n = 0; n <= TOTAL_OPERATIONS; n++) { - String key = "foo" + n; - jedis.set(key, "bar" + n); - jedis.get(key); - } - - long elapsed = Calendar.getInstance().getTimeInMillis() - begin; - - jedis.disconnect(); - - System.out.println(((1000 * 2 * TOTAL_OPERATIONS) / elapsed) + " ops"); - } -} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java b/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java deleted file mode 100644 index c58b55948d..0000000000 --- a/src/test/java/redis/clients/jedis/tests/commands/ConnectionHandlingCommandsTest.java +++ /dev/null @@ -1,26 +0,0 @@ -package redis.clients.jedis.tests.commands; - -import static org.junit.Assert.assertEquals; - -import org.junit.Test; - -import redis.clients.jedis.BinaryJedis; -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.tests.HostAndPortUtil; - -public class ConnectionHandlingCommandsTest { - private static HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); - - @Test - public void quit() { - Jedis jedis = new Jedis(hnp); - assertEquals("OK", jedis.quit()); - } - - @Test - public void binary_quit() { - BinaryJedis bj = new BinaryJedis(hnp); - assertEquals("OK", bj.quit()); - } -} \ No newline at end of file diff --git a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java b/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java deleted file mode 100644 index 208367b28d..0000000000 --- a/src/test/java/redis/clients/jedis/tests/commands/JedisCommandTestBase.java +++ /dev/null @@ -1,38 +0,0 @@ -package redis.clients.jedis.tests.commands; - -import org.junit.After; -import org.junit.Before; - -import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; -import redis.clients.jedis.tests.HostAndPortUtil; - -public abstract class JedisCommandTestBase { - protected static final HostAndPort hnp = HostAndPortUtil.getRedisServers().get(0); - - protected Jedis jedis; - - public JedisCommandTestBase() { - super(); - } - - @Before - public void setUp() throws Exception { - jedis = new Jedis(hnp.getHost(), hnp.getPort(), 500); - jedis.connect(); - jedis.auth("foobared"); - jedis.flushAll(); - } - - @After - public void tearDown() throws Exception { - jedis.close(); - } - - protected Jedis createJedis() { - Jedis j = new Jedis(hnp); - j.connect(); - j.auth("foobared"); - return j; - } -} diff --git a/src/test/java/redis/clients/jedis/tests/utils/KeyMergeUtilTest.java b/src/test/java/redis/clients/jedis/tests/utils/KeyMergeUtilTest.java deleted file mode 100644 index 4508cebd17..0000000000 --- a/src/test/java/redis/clients/jedis/tests/utils/KeyMergeUtilTest.java +++ /dev/null @@ -1,25 +0,0 @@ -package redis.clients.jedis.tests.utils; - -import org.junit.Assert; -import org.junit.Test; -import redis.clients.jedis.util.KeyMergeUtil; - -public class KeyMergeUtilTest { - - @Test - public void mergeByteArray() { - byte[][] bytes = KeyMergeUtil.merge(new byte[] {3, 2, 1}, new byte[][] {{1, 2, 3}, {2, 4, 8}}); - - Assert.assertArrayEquals(new byte[] { 3, 2, 1 }, ((bytes)[0])); - Assert.assertArrayEquals(new byte[] { 1, 2, 3 }, ((bytes)[1])); - Assert.assertArrayEquals(new byte[] { 2, 4, 8 }, ((bytes)[2])); - } - - @Test - public void mergeString() { - String[] strings = KeyMergeUtil.merge("1234", new String[] { "fooBar" }); - - Assert.assertEquals("1234", strings[0]); - Assert.assertEquals("fooBar", strings[1]); - } -} diff --git a/src/test/java/redis/clients/jedis/tests/utils/AssertUtil.java b/src/test/java/redis/clients/jedis/util/AssertUtil.java similarity index 96% rename from src/test/java/redis/clients/jedis/tests/utils/AssertUtil.java rename to src/test/java/redis/clients/jedis/util/AssertUtil.java index e84eb1372c..2b26b41ad1 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/AssertUtil.java +++ b/src/test/java/redis/clients/jedis/util/AssertUtil.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; @@ -9,7 +9,6 @@ import java.util.List; import java.util.Objects; import java.util.Set; - import org.junit.ComparisonFailure; public class AssertUtil { @@ -36,7 +35,7 @@ public static void assertByteArraySetEquals(Set expected, Set ac while (e.hasNext()) { byte[] next = e.next(); boolean contained = false; - for (byte[] element : expected) { + for (byte[] element : actual) { if (Arrays.equals(next, element)) { contained = true; break; diff --git a/src/test/java/redis/clients/jedis/tests/utils/ByteArrayComparatorTest.java b/src/test/java/redis/clients/jedis/util/ByteArrayComparatorTest.java similarity index 83% rename from src/test/java/redis/clients/jedis/tests/utils/ByteArrayComparatorTest.java rename to src/test/java/redis/clients/jedis/util/ByteArrayComparatorTest.java index a02ed968e8..54cd1ca62f 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/ByteArrayComparatorTest.java +++ b/src/test/java/redis/clients/jedis/util/ByteArrayComparatorTest.java @@ -1,12 +1,9 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import static org.junit.Assert.assertTrue; import org.junit.Test; -import redis.clients.jedis.util.ByteArrayComparator; -import redis.clients.jedis.util.SafeEncoder; - public class ByteArrayComparatorTest { @Test diff --git a/src/test/java/redis/clients/jedis/tests/utils/ByteArrayUtil.java b/src/test/java/redis/clients/jedis/util/ByteArrayUtil.java similarity index 94% rename from src/test/java/redis/clients/jedis/tests/utils/ByteArrayUtil.java rename to src/test/java/redis/clients/jedis/util/ByteArrayUtil.java index 08dccf1e09..e5bd01acca 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/ByteArrayUtil.java +++ b/src/test/java/redis/clients/jedis/util/ByteArrayUtil.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import java.util.Arrays; import java.util.Collection; diff --git a/src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java b/src/test/java/redis/clients/jedis/util/ClientKillerUtil.java similarity index 71% rename from src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java rename to src/test/java/redis/clients/jedis/util/ClientKillerUtil.java index 23e9082622..f68db0f341 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/ClientKillerUtil.java +++ b/src/test/java/redis/clients/jedis/util/ClientKillerUtil.java @@ -1,18 +1,17 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; -import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; public class ClientKillerUtil { + public static void killClient(Jedis jedis, String clientName) { for (String clientInfo : jedis.clientList().split("\n")) { if (clientInfo.contains("name=" + clientName)) { // Ugly, but cmon, it's a test. String hostAndPortString = clientInfo.split(" ")[1].split("=")[1]; - String[] hostAndPortParts = HostAndPort.extractParts(hostAndPortString); // It would be better if we kill the client by Id as it's safer but jedis doesn't implement // the command yet. - jedis.clientKill(hostAndPortParts[0] + ":" + hostAndPortParts[1]); + jedis.clientKill(hostAndPortString); } } } diff --git a/src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java b/src/test/java/redis/clients/jedis/util/FragmentedByteArrayInputStream.java similarity index 95% rename from src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java rename to src/test/java/redis/clients/jedis/util/FragmentedByteArrayInputStream.java index 5eb1c363c4..176cb52d1f 100644 --- a/src/test/java/redis/clients/jedis/tests/FragmentedByteArrayInputStream.java +++ b/src/test/java/redis/clients/jedis/util/FragmentedByteArrayInputStream.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests; +package redis.clients.jedis.util; import java.io.ByteArrayInputStream; diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16Test.java b/src/test/java/redis/clients/jedis/util/JedisClusterCRC16Test.java similarity index 94% rename from src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16Test.java rename to src/test/java/redis/clients/jedis/util/JedisClusterCRC16Test.java index 313028b89a..fe5cfb9729 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterCRC16Test.java +++ b/src/test/java/redis/clients/jedis/util/JedisClusterCRC16Test.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotEquals; @@ -6,12 +6,8 @@ import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; - import org.junit.Test; -import redis.clients.jedis.util.JedisClusterCRC16; -import redis.clients.jedis.util.SafeEncoder; - public class JedisClusterCRC16Test { @Test diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java b/src/test/java/redis/clients/jedis/util/JedisClusterTestUtil.java similarity index 98% rename from src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java rename to src/test/java/redis/clients/jedis/util/JedisClusterTestUtil.java index 03027b134c..75aaba1613 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisClusterTestUtil.java +++ b/src/test/java/redis/clients/jedis/util/JedisClusterTestUtil.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import redis.clients.jedis.HostAndPort; import redis.clients.jedis.Jedis; diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java b/src/test/java/redis/clients/jedis/util/JedisSentinelTestUtil.java similarity index 83% rename from src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java rename to src/test/java/redis/clients/jedis/util/JedisSentinelTestUtil.java index 1a3597da05..801d8d5b9f 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisSentinelTestUtil.java +++ b/src/test/java/redis/clients/jedis/util/JedisSentinelTestUtil.java @@ -1,14 +1,16 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import java.util.concurrent.atomic.AtomicReference; import redis.clients.jedis.HostAndPort; -import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; +import redis.clients.jedis.Sentinel; +import redis.clients.jedis.exceptions.FailoverAbortedException; public class JedisSentinelTestUtil { + public static HostAndPort waitForNewPromotedMaster(final String masterName, - final Jedis sentinelJedis, final Jedis commandJedis) throws InterruptedException { + final Sentinel sentinelJedis, final Sentinel commandJedis) throws InterruptedException { final AtomicReference newmaster = new AtomicReference(""); diff --git a/src/test/java/redis/clients/jedis/tests/utils/JedisURIHelperTest.java b/src/test/java/redis/clients/jedis/util/JedisURIHelperTest.java similarity index 95% rename from src/test/java/redis/clients/jedis/tests/utils/JedisURIHelperTest.java rename to src/test/java/redis/clients/jedis/util/JedisURIHelperTest.java index eab21d8777..0a6f743842 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/JedisURIHelperTest.java +++ b/src/test/java/redis/clients/jedis/util/JedisURIHelperTest.java @@ -1,4 +1,4 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @@ -6,11 +6,8 @@ import java.net.URI; import java.net.URISyntaxException; - import org.junit.Test; -import redis.clients.jedis.util.JedisURIHelper; - public class JedisURIHelperTest { @Test diff --git a/src/test/java/redis/clients/jedis/tests/utils/RedisVersionUtil.java b/src/test/java/redis/clients/jedis/util/RedisVersionUtil.java similarity index 87% rename from src/test/java/redis/clients/jedis/tests/utils/RedisVersionUtil.java rename to src/test/java/redis/clients/jedis/util/RedisVersionUtil.java index 799a3f81c7..8b125ca7d3 100644 --- a/src/test/java/redis/clients/jedis/tests/utils/RedisVersionUtil.java +++ b/src/test/java/redis/clients/jedis/util/RedisVersionUtil.java @@ -1,10 +1,10 @@ -package redis.clients.jedis.tests.utils; +package redis.clients.jedis.util; import redis.clients.jedis.Jedis; public class RedisVersionUtil { - public static int getRedisMajorVersionNumber() { + public static Integer getRedisMajorVersionNumber() { String completeVersion = null; try (Jedis jedis = new Jedis()) { @@ -20,7 +20,7 @@ public static int getRedisMajorVersionNumber() { } if (completeVersion == null) { - return 0; + return null; } return Integer.parseInt(completeVersion.substring(0, completeVersion.indexOf("."))); }